Esempio n. 1
0
print("")
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
import random

api_id = 0000000  #Enter Your 7 Digit Telegram API ID.
api_hash = '56c2e6dbec19ebb226c728c0c1afe2bd'  #Enter Yor 32 Character API Hash
phone = '+10000000000'  #Enter Your Mobilr Number With Country Code.
client = TelegramClient(phone, api_id, api_hash)


async def main():
    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello !!!!!')


SLEEP_TIME_1 = 100
SLEEP_TIME_2 = 100
with client:
    client.loop.run_until_complete(main())
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('40779'))
Esempio n. 2
0
from utils import filter_emojis, init_settings

logging_level = logging.INFO
settings_file_path = 'settings.json'

logging.basicConfig(level=logging_level, format='%(asctime)s| %(message)s')
logging.getLogger('telethon').setLevel(level=logging.INFO)
logger = logging.getLogger()

if __name__ == '__main__':
    settings = init_settings(settings_file_path)
    logger.debug(f'Settings loaded: {settings}')

    with TelegramClient('iron_dome',
                        settings['api_id'],
                        settings['api_hash'],
                        flood_sleep_threshold=86400,
                        base_logger='telethon') as client:

        for username in sys.argv[1:]:
            full_user = client(GetFullUserRequest(username))
            print(
                json.dumps(
                    {
                        'id': full_user.user.id,
                        'access_hash': full_user.user.access_hash,
                        'first_name': filter_emojis(full_user.user.first_name),
                        'last_name': filter_emojis(full_user.user.last_name),
                        'username': full_user.user.username,
                        'phone': full_user.user.phone,
                        'about': full_user.about,
Esempio n. 3
0
def message_curr_strength(fname):
    api_id = 1433030
    api_hash = '33fa8cdfd1b35e902e6118b6abbf3726'
    token = '1315998116:AAF8A-WBdojAJMtp75o_zb3xcIykIX9bh_g'

    phone_num = '+639267415427'

    client = TelegramClient('session_name', api_id, api_hash)

    client.connect()

    if not client.is_user_authorized():
        client.send_code_request(phone_num)
        client.sign_in(phone_num, input('Enter the code: '))

    destination_group = 'https://t.me/joinchat/TwIbzlVqFT986_g0-Dai_A'
    peer = client.get_entity(destination_group)

    time = pd.to_datetime('now').strftime('%Y-%m-%d %H:%M')

    client.send_message(entity=peer,
                        message='Currency Strength Bar {}'.format(time),
                        parse_mode='html')
    client.send_file(entity=peer, file=fname)

    strength_values = ''
    with open('currStrengthOutputs/currStrengthValues.txt', 'r') as f:
        for line in f:
            strength_values += line

    tradable_pairs = ''
    with open('currStrengthOutputs/tradeableCurrPair.txt', 'r') as f:
        for line in f:
            tradable_pairs += line

    client.send_message(entity=peer,
                        message='Currency Strength Values',
                        parse_mode='html')
    client.send_message(entity=peer,
                        message=strength_values,
                        parse_mode='html')

    client.send_message(entity=peer,
                        message='Tradable Pairs and Difference',
                        parse_mode='html')
    client.send_message(entity=peer, message=tradable_pairs, parse_mode='html')

    client.disconnect()

    return None
Esempio n. 4
0
with open('aliases.txt', 'r', encoding='utf-8') as f:
    aliases = f.read().splitlines()
with open('channels.txt', 'r', encoding='utf-8') as f:
    channels = f.read().splitlines()


async def add_to_channels(channels: list, users: list):
    """
    Invites the users to the channels or megagroups. Both are lists. The members of these lists can be the actual names of the users and channels.
    """
    cached_channels = []
    for channel in channels:
        try:
            cached_channels.append(await client.get_input_entity(channel))
        except ValueError:
            dialogs = await client.get_dialogs()
            cached_channels.append(await client.get_input_entity(channel))
        for alias in aliases:
            print(alias)
            for channel in cached_channels:
                await client(InviteToChannelRequest(channel, [alias]))
                time.sleep(
                    10
                )  # Maybe not necessary, but I don't want to get flood protection.
            print("Done")
            time.sleep(10)  # See comment above.


with TelegramClient('tsession', api_id, api_hash) as client:
    client.loop.run_until_complete(
        add_to_channels(channels=channels, users=aliases))
from telethon.sync import TelegramClient
from data.config import config

API_ID = config['telegram']['api_id']
API_HASH = config['telegram']['api_hash']
PHONE = config['telegram']['phone']

with TelegramClient(PHONE, API_ID, API_HASH) as client:
    string = client.session.save()
Esempio n. 6
0
def get_telegram_token(name: str) -> str:
    from telethon.sync import TelegramClient, events
    client = TelegramClient('get_new_bot_token', 1170703,
                            '57ce76b0fed0ae5e8103fb42e20021ba')
    token = ""

    @client.on(events.NewMessage(chats=('BotFather', )))
    async def handle_token(event):
        nonlocal token
        msg = event.message.to_dict()['message']
        if 'Done! Congratulations on your new bot' in msg:
            start = msg.index('Use this token to access the HTTP API:') + len(
                'Use this token to access the HTTP API:') + 1
            token = msg[start:start + 46]

    client.start()
    client.send_message('BotFather', '/start')
    client.send_message('BotFather', '/newbot')
    client.send_message('BotFather', name)
    client.send_message('BotFather', name + 'UglyBotlingBot')

    if token:
        return token
    return "smth"
Esempio n. 7
0
while True:
    try:
        accs.append(pickle.load(f))
    except EOFError:
        f.close()
        break
print(f'{INPUT}{lg} Choose an account to scrape members')
i = 0
for acc in accs:
    print(f'{lg}[{w}{i}{lg}] {acc}')
    i += 1
ind = int(input(f'{INPUT}{lg} Enter choice: '))
api_id = accs[ind][0]
api_hash = accs[ind][1]
phone = accs[ind][2]
client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
    try:
        client.send_code_request(phone)
        code = input(f'{INPUT}{lg} Enter the code for {phone}{r}: ')
        client.sign_in(phone, code)
    except PhoneNumberBannedError:
        print(f'{error}{r}{phone} is banned!{rs}')
        print(f'{error}{r} Run manager.py to filter them{rs}')
        sys.exit()
username = input(f'{INPUT}{lg} Enter the exact username of the public group[Without @]: {r}')
target_grp = 't.me/' + str(username)
group = client.get_entity(target_grp)
time = datetime.datetime.now().strftime("%H:%M")
print('\n' + info + lg + ' Started on ' + str(time) + rs)
Esempio n. 8
0
def authenticate(request, user, **kwargs):
	"""
	Check authentication with provided API credentials

	Tries to connect to the Telegram API and if needed send a Telegram message
	with confirmation code.

	:param request:  The Flask request through which this was called
	:param user:  The user object for the user making the request
	:param kwargs:  Parameters
	:return:  Result data
	"""
	if not user or not user.is_authenticated or user.is_anonymous:
		return {"error": "auth",
				"error-message": "Telegram scraping is only available to logged-in users with personal accounts."}

	# check for the information we need
	if "api_phone" not in kwargs or "api_id" not in kwargs or "api_hash" not in kwargs:
		return False

	kwargs = {key: kwargs[key].strip() for key in kwargs}

	# session IDs need to be unique...
	# Sessions are important because they are the way we don't need to enter
	# the security code all the time. If we've tried logging in earlier use
	# the same session again.
	if "session" in kwargs and kwargs["session"] and kwargs["session"] != "undefined":
		session_id = kwargs["session"]
	elif user.get_value("telegram.session", None):
		session_id = user.get_value("telegram.session")
	else:
		session_id = str(uuid.uuid4())

	# store session ID for user so it can be found again for later queries
	user.set_value("telegram.session", session_id)
	session_path = Path(__file__).parent.joinpath("..", "sessions", session_id)

	result = False
	client = None

	# API ID is always a number, if it's not, we can immediately fail
	try:
		api_id = int(kwargs["api_id"])
	except ValueError:
		return {"error": "other", "error-message": "Invalid API ID."}

	# maybe we've entered a code already and submitted it with the request
	if "code" in kwargs and kwargs["code"].strip():
		code_callback = lambda: kwargs["code"]
		max_attempts = 1
	else:
		code_callback = lambda: -1
		# max_attempts = 0 because authing will always fail: we can't wait for
		# the code to be entered interactively, we'll need to do a new request
		# but we can't just immediately return, we still need to call start()
		# to get telegram to send us a code
		max_attempts = 0

	# now try autenticating
	try:
		eventloop = asyncio.new_event_loop()
		client = TelegramClient(str(session_path), api_id, kwargs["api_hash"], loop=eventloop)

		try:
			client.start(max_attempts=max_attempts, phone=kwargs.get("api_phone"), code_callback=code_callback, password=None)
			result = {"authenticated": True, "session": session_id}

		except ValueError as e:
			# this happens if 2FA is required
			result = {"error": "2fa",
					  "error-message": "Your account requires two-factor authentication. 4CAT at this time does not support this authentication mode for Telegram. (%s)" % e}
		except RuntimeError:
			# A code was sent to the given phone number
			result = {"authenticated": False, "session": session_id}
	except FloodWaitError as e:
		# uh oh, we got rate-limited
		result = {"error": "rate-limit",
				  "error-message": "You were rate-limited and should wait a while before trying again. " +
								   str(e).split("(")[0] + ".", "authenticated": False}
	except ApiIdInvalidError as e:
		# wrong credentials
		result = {"error": "auth", "error-message": "Your API credentials are invalid."}
	except PhoneNumberInvalidError as e:
		# wrong phone number
		result = {"error": "auth",
				  "error-message": "The phone number provided is not a valid phone number for these credentials."}
	except Exception as e:
		# ?
		result = {"error": "other",
				  "error-message": "An unexpected error (%s) occurred and your authentication could not be verified." % e,
				  "error-trace": traceback.format_exc()}
		pass
	finally:
		if client:
			client.disconnect()

	return result
Esempio n. 9
0
import os

from telethon.sessions import StringSession, SQLiteSession
from telethon.sync import TelegramClient
import config
from telethon import events

bot = TelegramClient(StringSession(), config.API_ID,
                     config.API_HASH).start(bot_token=config.BOT_TOKEN)
client = TelegramClient(SQLiteSession(config.SESSION_STRING_CLIENT),
                        config.API_ID, config.API_HASH)

file_path = os.path.abspath('Bot')
file_name = os.path.basename(file_path)
print('Starting Parsing:')
for channel in config.SOURCE_CHANNEL:

    @client.on(events.NewMessage(chats=channel, incoming=True))
    async def handler_new_message(event):
        # global f
        try:
            print(event)
            print(
                '\n\n\n\nStarting Parsing New Messages...\n...\n...\n.......\n'
            )
            f = await client.download_media(message=event.message)
            if event.message.message is not None:
                # Sending Parsed Message
                try:
                    await bot.send_message(config.TARGET_CHANNEL,
                                           event.message.message,
Esempio n. 10
0
"""
Para gerar sua string session a fim de
debug. Basta colocar o token do seu
bot quando for pedido.
"""

from telethon.sessions import StringSession
from telethon.sync import TelegramClient

from bot import settings

with TelegramClient(StringSession(), settings.api_id,
                    settings.api_hash) as client:
    print(client.session.save())
Esempio n. 11
0
from telethon.sync import TelegramClient, events, Button
from telethon import errors
from telethon.tl.types import InputPeerChat
from telethon.errors import FloodWaitError
from telethon.tl.types import ChatEmpty
import os
import uuid
import shutil
import asyncio
import logging
logging.basicConfig(level=logging.INFO)

from creds import Credentials

client = TelegramClient(
    'Telethon Anonymous Bot',
    api_id=Credentials.API_ID,
    api_hash=Credentials.API_HASH).start(bot_token=Credentials.BOT_TOKEN)

DEFAULT_START = ("Hi, I am ANONYMOUS SENDER BOT.\n\n"
                 "Just Forward me Some messages or\n"
                 "media and I will Anonymize the\n"
                 "sender.\n\n"
                 "Please Support The Developer\n"
                 "By Joining the Support Channel👇👇")

if Credentials.START_MESSAGE is not None:
    START_TEXT = Credentials.START_MESSAGE
else:
    START_TEXT = DEFAULT_START

Esempio n. 12
0
class UI:
    def __init__(self):
        self.client = TelegramClient('token', api_id, api_hash)
        try:
            self.client.connect()
        except OSError:
            tk.messagebox.showerror('錯誤', '無法連線伺服器\n請檢查你的網路')

        if self.client.is_user_authorized():
            self.logged_in_windows = tk.Tk()
            self.logged_in_windows.title("快速刪除Telegram訊息({}已登入)".format(
                self.client.get_me().first_name))
            self.logged_in_windows.geometry('432x243')
            self.logged_in_windows.resizable(width=0, height=0)
            self.logged_in_windows.wm_attributes('-topmost', 1)
            self.chat_room = tk.Entry(self.logged_in_windows)
            self.chat_room.pack()
            tk.Label(
                self.logged_in_windows,
                text=
                '\n使用說明\n\n在上方輸入頻道、群組的share link或者私訊對方的username\n格式可以是 https://t.me/TGQNA @TGQNA 或者 TGQNA\n\n在下方選譯是僅刪除自己傳送的訊息還是刪除所有的訊息\n注意:刪除所有訊息時請確保你有對應的權限\n'
            ).pack()
            self.del_button = tk.Button(self.logged_in_windows,
                                        text='刪除自己的訊息',
                                        command=self.del_msg)
            self.del_button.pack()
            self.del_all_button = tk.Button(self.logged_in_windows,
                                            text='刪除全部的訊息',
                                            command=self.delall_msg)
            self.del_all_button.pack()
            self.logged_in_windows.mainloop()
        else:
            self.log_in_windows = tk.Tk()
            self.log_in_windows.title("快速刪除Telegram訊息(未登入)")
            self.log_in_windows.geometry('432x243')
            self.log_in_windows.resizable(width=0, height=0)
            self.log_in_windows.wm_attributes('-topmost', 1)
            tk.Label(master=self.log_in_windows,
                     text='國碼+電話號碼').place(x=20, y=50, height=26, width=100)
            tk.Label(master=self.log_in_windows, text='驗證碼').place(x=66,
                                                                   y=100,
                                                                   height=26,
                                                                   width=60)
            tk.Label(master=self.log_in_windows, text='密碼').place(x=72,
                                                                  y=150,
                                                                  height=26,
                                                                  width=60)
            self.phone_number = tk.Entry(master=self.log_in_windows)
            self.phone_number.place(x=144, y=50, height=26, width=220)
            self.code = tk.Entry(master=self.log_in_windows)
            self.code.place(x=144, y=100, height=26, width=100)
            self.password = tk.Entry(master=self.log_in_windows, show='*')
            self.password.place(x=144, y=150, height=26, width=220)
            self.get_code_button = tk.Button(master=self.log_in_windows,
                                             text='驗證碼',
                                             width=50,
                                             height=30,
                                             command=self.get_code)
            self.get_code_button.place(x=304, y=100, height=26, width=60)
            self.help_button = tk.Button(master=self.log_in_windows,
                                         text='說明',
                                         width=40,
                                         height=30,
                                         command=self.help)
            self.help_button.place(x=94, y=200, height=26, width=60)
            self.login_button = tk.Button(master=self.log_in_windows,
                                          text='登入',
                                          width=40,
                                          height=30,
                                          command=self.login)
            self.login_button.place(x=194, y=200, height=26, width=60)
            self.exit_button = tk.Button(master=self.log_in_windows,
                                         text='退出',
                                         width=40,
                                         height=30,
                                         command=self.exit)
            self.exit_button.place(x=294, y=200, height=26, width=60)
            self.log_in_windows.mainloop()

    def exit(self):
        self.log_in_windows.quit()

    def get_code(self):
        if len(self.phone_number.get()) <= 8:
            tk.messagebox.showerror(
                '錯誤', '請先輸入正確的電話號碼\n格式:國際電話區號+電話號碼\n例如:+85223802850')
            return
        try:
            self.sent = self.client.send_code_request(self.phone_number.get())
            self.hash = self.sent.phone_code_hash
        except:
            tk.messagebox.showerror('未知錯誤', '無法取得驗證碼,請兩分鐘後再試!')

    def help(self):
        tk.messagebox.showinfo(
            '使用說明',
            '電話號碼格式國際電話區號+電話號碼\n例如:+85223802850\n\n驗證碼是5位數字的\n密碼是雙步驟驗證(2FA)密碼,沒有就留空'
        )

    def del_msg(self):
        self.me = self.client.get_me()
        for self.message in self.client.iter_messages(self.chat_room.get()):
            if self.message.from_id == self.me.id:
                self.client.delete_messages(self.chat_room.get(),
                                            self.message.id)
                print(self.message.id)
        tk.messagebox.showinfo('成功',
                               '成功刪除 {} 裡自己傳送的訊息'.format(self.chat_room.get()))

    def delall_msg(self):
        for self.message in self.client.iter_messages(self.chat_room.get()):
            self.client.delete_messages(self.chat_room.get(), self.message.id)
            print(self.message.id)
        tk.messagebox.showinfo('成功',
                               '成功刪除 {} 裡所有的訊息'.format(self.chat_room.get()))

    def login(self):
        if len(self.code.get()) != 5:
            tk.messagebox.showerror('錯誤', '請先輸入正確的驗證碼')
            return
        try:
            self.client.sign_in(phone=self.phone_number.get(),
                                code=self.code.get(),
                                password=self.password.get(),
                                phone_code_hash=self.hash)
        except:
            tk.messagebox.showerror('未知錯誤', '無法登入!')
            return
        tk.messagebox.showinfo('登入成功', '請重新啟動這個應用程式!')
        self.log_in_windows.quit()
Esempio n. 13
0
    def __init__(self):
        self.client = TelegramClient('token', api_id, api_hash)
        try:
            self.client.connect()
        except OSError:
            tk.messagebox.showerror('錯誤', '無法連線伺服器\n請檢查你的網路')

        if self.client.is_user_authorized():
            self.logged_in_windows = tk.Tk()
            self.logged_in_windows.title("快速刪除Telegram訊息({}已登入)".format(
                self.client.get_me().first_name))
            self.logged_in_windows.geometry('432x243')
            self.logged_in_windows.resizable(width=0, height=0)
            self.logged_in_windows.wm_attributes('-topmost', 1)
            self.chat_room = tk.Entry(self.logged_in_windows)
            self.chat_room.pack()
            tk.Label(
                self.logged_in_windows,
                text=
                '\n使用說明\n\n在上方輸入頻道、群組的share link或者私訊對方的username\n格式可以是 https://t.me/TGQNA @TGQNA 或者 TGQNA\n\n在下方選譯是僅刪除自己傳送的訊息還是刪除所有的訊息\n注意:刪除所有訊息時請確保你有對應的權限\n'
            ).pack()
            self.del_button = tk.Button(self.logged_in_windows,
                                        text='刪除自己的訊息',
                                        command=self.del_msg)
            self.del_button.pack()
            self.del_all_button = tk.Button(self.logged_in_windows,
                                            text='刪除全部的訊息',
                                            command=self.delall_msg)
            self.del_all_button.pack()
            self.logged_in_windows.mainloop()
        else:
            self.log_in_windows = tk.Tk()
            self.log_in_windows.title("快速刪除Telegram訊息(未登入)")
            self.log_in_windows.geometry('432x243')
            self.log_in_windows.resizable(width=0, height=0)
            self.log_in_windows.wm_attributes('-topmost', 1)
            tk.Label(master=self.log_in_windows,
                     text='國碼+電話號碼').place(x=20, y=50, height=26, width=100)
            tk.Label(master=self.log_in_windows, text='驗證碼').place(x=66,
                                                                   y=100,
                                                                   height=26,
                                                                   width=60)
            tk.Label(master=self.log_in_windows, text='密碼').place(x=72,
                                                                  y=150,
                                                                  height=26,
                                                                  width=60)
            self.phone_number = tk.Entry(master=self.log_in_windows)
            self.phone_number.place(x=144, y=50, height=26, width=220)
            self.code = tk.Entry(master=self.log_in_windows)
            self.code.place(x=144, y=100, height=26, width=100)
            self.password = tk.Entry(master=self.log_in_windows, show='*')
            self.password.place(x=144, y=150, height=26, width=220)
            self.get_code_button = tk.Button(master=self.log_in_windows,
                                             text='驗證碼',
                                             width=50,
                                             height=30,
                                             command=self.get_code)
            self.get_code_button.place(x=304, y=100, height=26, width=60)
            self.help_button = tk.Button(master=self.log_in_windows,
                                         text='說明',
                                         width=40,
                                         height=30,
                                         command=self.help)
            self.help_button.place(x=94, y=200, height=26, width=60)
            self.login_button = tk.Button(master=self.log_in_windows,
                                          text='登入',
                                          width=40,
                                          height=30,
                                          command=self.login)
            self.login_button.place(x=194, y=200, height=26, width=60)
            self.exit_button = tk.Button(master=self.log_in_windows,
                                         text='退出',
                                         width=40,
                                         height=30,
                                         command=self.exit)
            self.exit_button.place(x=294, y=200, height=26, width=60)
            self.log_in_windows.mainloop()
Esempio n. 14
0
def ClientConnect(sim: Sim):
    client = TelegramClient(sim.phone, sim.ID, sim.access_hash)

    # connect to client
    client.connect()
    if not client.is_user_authorized():
        client.send_code_request(sim.phone)
        client.sign_in(sim.phone, input(Fore.WHITE + 'Enter the code to ' + sim.name + ': '))

    print(Fore.GREEN + "Connected Succesfully!")
    client.disconnect()
    del client
Esempio n. 15
0
url = 'https://api.binance.com/api/v1/ticker/price?symbol='

api_id = 123456
api_hash = 'yourapiHash'
phone_number = +123456789
name = 'telegramPump'
chatName = 'ShamsTest'

BinanceClient = Client("username", "password")
BTCquantity = '0.001'

securityCoef = 1.2
sellCoef = 1.2

client = TelegramClient(name, api_id, api_hash).start()


@client.on(events.NewMessage(chats=(chatName)))
async def my_event_handler(event):

    symbol = ''
    asset = ''

    if "Today We Push: #" in event.message.message:
        msg = event.message.message
        msg_parsed = msg.split("Today We Push: #", 1)
        msg_parsed2 = msg_parsed[1].split(" $", 1)
        asset = str(msg_parsed2[0])

    elif "There are many good coins on Binance" in event.message.message:
Esempio n. 16
0
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import sys
import csv

api_id = 1149072
api_hash = '594c72967c4184f92a7a88b3b07cfd1f'
phone = '+6285778151604'
client = TelegramClient(phone, api_id, api_hash)

input_file = sys.argv[1]
users = []
with open(input_file, encoding='UTF-8') as f:
    rows = csv.reader(f, delimiter=",", lineterminator="\n")
    next(rows, None)
    for row in rows:
        user = {}
        user['username'] = row[0]
        user['id'] = int(row[1])
        user['access_hash'] = int(row[2])
        user['name'] = row[3]
        users.append(user)

chats = []
last_date = None
chunk_size = 200
groups = []

result = client(
    GetDialogsRequest(offset_date=last_date,
Esempio n. 17
0
    def send_sms():
        try:
            cpass = configparser.RawConfigParser()
            cpass.read('config.data')
            api_id = cpass['cred']['id']
            api_hash = cpass['cred']['hash']
            phone = cpass['cred']['phone']
        except KeyError:
            os.system('clear')
            main.banner()
            print(re + "[!] run python3 setup.py first !!\n")
            sys.exit(1)

        client = TelegramClient(phone, api_id, api_hash)

        client.connect()
        if not client.is_user_authorized():
            client.send_code_request(phone)
            os.system('clear')
            main.banner()
            client.sign_in(phone, input(gr + '[+] Enter the code: ' + re))

        os.system('clear')
        main.banner()
        input_file = sys.argv[1]
        users = []
        with open(input_file, encoding='UTF-8') as f:
            rows = csv.reader(f, delimiter=",", lineterminator="\n")
            next(rows, None)
            for row in rows:
                user = {}
                user['username'] = row[0]
                user['id'] = int(row[1])
                user['access_hash'] = int(row[2])
                user['name'] = row[3]
                users.append(user)
        print(gr + "[1] send sms by user ID\n[2] send sms by username ")
        mode = int(input(gr + "Input : " + re))

        message = input(gr + "[+] Enter Your Message : " + re)

        for user in users:
            if mode == 2:
                if user['username'] == "":
                    continue
                receiver = client.get_input_entity(user['username'])
            elif mode == 1:
                receiver = InputPeerUser(user['id'], user['access_hash'])
            else:
                print(re + "[!] Invalid Mode. Exiting.")
                client.disconnect()
                sys.exit()
            try:
                print(gr + "[+] Sending Message to:", user['name'])
                client.send_message(receiver, message.format(user['name']))
                print(gr + "[+] Waiting {} seconds".format(SLEEP_TIME))
                time.sleep(SLEEP_TIME)
            except PeerFloodError:
                print(
                    re +
                    "[!] Getting Flood Error from telegram. \n[!] Script is stopping now. \n[!] Please try again after some time."
                )
                client.disconnect()
                sys.exit()
            except Exception as e:
                print(re + "[!] Error:", e)
                print(re + "[!] Trying to continue...")
                continue
        client.disconnect()
        print("Done. Message sent to all users.")
Esempio n. 18
0
#Imports#
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
import pandas as pd
import csv
import details as ds

#Login details#
api_id = ds.apiID
api_hash = ds.apiHash
phone = ds.number
client = TelegramClient(phone, api_id, api_hash)

#Check authorisation#
client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

chats = []
last_date = None
chunk_size = 200
groups=[]

result = client(GetDialogsRequest(
             offset_date=last_date,
             offset_id=0,
             offset_peer=InputPeerEmpty(),
             limit=chunk_size,
             hash = 0
Esempio n. 19
0
def autos():

    channel_username = to_group
    phone = utils.parse_phone(pphone)

    client = TelegramClient(f"../sessions/{phone}", api_id, api_hash)

    client.connect()
    if not client.is_user_authorized():
        print('some thing has changed')
        client.send_code_request(phone)
        client.sign_in(phone, input('Enter the code: '))

    input_file = '../data.csv'
    users = []
    with open(input_file, encoding='UTF-8') as f:
        rows = csv.reader(f, delimiter=",", lineterminator="\n")
        next(rows, None)
        for row in rows:
            user = {}
            user['srno'] = row[0]
            user['username'] = row[1]
            user['id'] = int(row[2])
            #user['access_hash'] = int(row[2])
            user['name'] = row[3]
            users.append(user)

    startfrom = int(input("Start From = "))
    endto = int(input("End To = "))

    for user in users:
        if (int(startfrom) <= int(user['srno'])) and (int(user['srno']) <=
                                                      int(endto)):
            try:
                status = 'delta'
                if user['username'] == "":
                    print("no username, moving to next")
                    continue

                client(
                    InviteToChannelRequest(channel_username,
                                           [user['username']]))
                status = 'DONE'

                #print("Waiting for 60-180 Seconds...")
                time.sleep(random.randrange(0, 5))

            except UserPrivacyRestrictedError:
                status = 'PrivacyRestrictedError'

            except UserAlreadyParticipantError:
                status = 'ALREADY'

            except PeerFloodError as g:
                status = 'PeerFloodError :('
                print(
                    'Script Is Stopping Now, Dont Use This Account For The Next 24 Hours'
                )
                time.sleep(86400)

            except ChatWriteForbiddenError as cwfe:

                client(JoinChannelRequest(channel_username))
                continue

            except errors.RPCError as e:
                status = e.__class__.__name__

            except Exception as d:
                status = d

            except:
                traceback.print_exc()
                print("Unexpected Error")
                continue
            channel_connect = client.get_entity(channel_username)
            channel_full_info = client(
                GetFullChannelRequest(channel=channel_connect))
            countt = int(channel_full_info.full_chat.participants_count)

            print(
                f"ADDING {user['name']} TO {channel_username} TOTAL: {countt} - {status}"
            )
        elif int(user['srno']) > int(endto):
            print("Members Added Successfully!")
            stat = input(
                'Done!\nChoose From Below:\n\n1 - Repeat The Script\nOR Just Hit Enter To Quit\n\nEnter: '
            )
            if stat == '1':
                autos()
            else:
                quit()
Esempio n. 20
0
from telethon.sessions import StringSession
from nicegrill.main import Main
from nicegrill.modules import _init
from config import API_HASH, API_ID, SESSION, MONGO_URI
import asyncio
import os


if not API_ID or not API_HASH:
    print("Type your informations in config.py")

if not SESSION:
    print("Run generate_session.py to create a string session first")
    quit()

if not MONGO_URI:
    print("Haven't you set your MongoDB URI yet?")
    quit()

with TelegramClient(StringSession(SESSION), API_ID, API_HASH) as client:
    client.parse_mode = 'html'
    asyncio.get_event_loop().create_task(_init.loads())
    asyncio.get_event_loop().create_task(_init.filestorage(client))
    asyncio.get_event_loop().create_task(Main.read(client))
    client.add_event_handler(Main.outgoing,
        events.NewMessage(outgoing=True, forwards=False))
    client.add_event_handler(Main.outgoing,
        events.MessageEdited(outgoing=True, forwards=False))
    print(f"Logged in as {(client.get_me()).first_name}")
    client.run_until_disconnected()
import os

from telethon.sync import TelegramClient
from telethon.sessions import StringSession

api_id = int(os.getenv('API_ID') or input("Enter your API_ID: "))
api_hash = os.getenv('API_HASH') or input("Enter your API_HASH: ")

with TelegramClient(StringSession(), api_id, api_hash) as client:
    print("\n" + client.session.save())
Esempio n. 22
0
def create_session_string():

    session = StringSession()

    with TelegramClient(session, API_ID, API_HASH) as client:
        print(session.save())
Esempio n. 23
0
binaries = {
    "https://raw.githubusercontent.com/adekmaulana/megadown/master/megadown":
    "bin/megadown",
    "https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py":
    "bin/cmrudl"
}

for binary, path in binaries.items():
    downloader = SmartDL(binary, path, progress_bar=False)
    downloader.start()
    os.chmod(path, 0o755)

# 'bot' variable
if STRING_SESSION:
    # pylint: disable=invalid-name
    bot = TelegramClient(StringSession(STRING_SESSION), API_KEY, API_HASH)
else:
    # pylint: disable=invalid-name
    bot = TelegramClient("userbot", API_KEY, API_HASH)


async def check_botlog_chatid():
    if not BOTLOG_CHATID and LOGSPAMMER:
        LOGS.info(
            "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the private error log storage to work."
        )
        quit(1)

    elif not BOTLOG_CHATID and BOTLOG:
        LOGS.info(
            "You must set up the BOTLOG_CHATID variable in the config.env or environment variables, for the userbot logging feature to work."
Esempio n. 24
0
from telethon.sync import TelegramClient
from telethon.tl.types import InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError
import sys
import csv
import random
import time

#Subscribe to my Youtube Channel: Solved4You
api_id = 0000000
api_hash = '0000000000000000000000000000000'
phone = '+00000000000000'
client = TelegramClient(phone, api_id, api_hash)

SLEEP_TIME_2 = 100
SLEEP_TIME_1 = 40
SLEEP_TIME = 4
client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

users = []
with open(r"members.csv", encoding='UTF-8') as f:
    rows = csv.reader(f, delimiter=",", lineterminator="\n")
    next(rows, None)
    for row in rows:
        user = {}
        user['username'] = row[0]
Esempio n. 25
0
#!/usr/bin/env python3
# (c) https://t.me/TelethonChat/37677
# This Source Code Form is subject to the terms of the GNU
# General Public License, v.3.0. If a copy of the GPL was not distributed with this
# file, You can obtain one at https://www.gnu.org/licenses/gpl-3.0.en.html.

try:
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
except BaseException:
    print("Telethon Not Found. Installing Now.")
    import os

    os.system("pip3 install telethon")
    from telethon.sessions import StringSession
    from telethon.sync import TelegramClient
ok = """ ____  ____  __  ____   __   _  _
Ultimate 
"""
print(ok)
APP_ID = int(input("Enter APP ID here: \n"))
API_HASH = input("Enter API HASH here: \n")

client = TelegramClient(StringSession(), APP_ID, API_HASH)
with client:
    session_str = client.session.save()
    client.send_message("me", f"`{session_str}`")
    client.send_message(
        "THIS IS YOUR STRING SESSION \nJoin @Ult_imate For More Support.")
    print("⬆ Please Check Your Telegram Saved Message For Your String.")
Esempio n. 26
0
from telethon import events
from telethon.sessions import StringSession
from telethon.sync import TelegramClient
from telethon.tl.types import InputMediaPoll, MessageMediaPoll, MessageEntityTextUrl

from database import Database, MirrorMessage
from settings import (API_HASH, API_ID, CHANNEL_MAPPING, CHATS, DB_URL,
                      LIMIT_TO_WAIT, LOG_LEVEL, REMOVE_URLS, SESSION_STRING,
                      TIMEOUT_MIRRORING)
from utils import remove_urls

logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(level=LOG_LEVEL)

client = TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH)
db = Database(DB_URL)


def remove_url_from_message(message):
    message.message = remove_urls(message.message)
    if message.entities is not None:
        for e in message.entities:
            if isinstance(e, MessageEntityTextUrl):
                e.url = remove_urls(e.url)
    return message


@client.on(events.Album(chats=CHATS))
async def handler_album(event):
    """Album event handler.
Esempio n. 27
0
#!/usr/bin/env python3
# (c) https://t.me/TelethonChat/37677
# This Source Code Form is subject to the terms of the GNU
# General Public License, v.3.0. If a copy of the GPL was not distributed with this
# file, You can obtain one at https://www.gnu.org/licenses/gpl-3.0.en.html.

from telethon.sessions import StringSession
from telethon.sync import TelegramClient

ok = """ ____  ____  __  ____   __   _  _
                   _____  __   __        __
\        / |   | | | | | |    |    \  / |
 \  /\  /  |---| |   |   |--  |--   \/  |--
  \/  \/   |   | |   |   |__  |__    |  |__
  
  
"""
print(ok)
APP_ID = int(input("Enter APP ID here: \n"))
API_HASH = input("Enter API HASH here: \n")

with TelegramClient(StringSession(), APP_ID, API_HASH) as client:
    try:
        session = client.session.save()
        client.send_message("me",
                            f"String Session \nTap To Copy. \n`{session}`")
        print("String Generated Sucessfully Check Your Saved Message.")
    except Exception as sed:
        print(f"Something Went Wrong While Generating String \nError : {sed}")
Esempio n. 28
0
def app():
    with TelegramClient(name, api_id, api_hash) as client:
        result = client(
            functions.channels.GetMessagesRequest(channel='BeingLogical',
                                                  id=[1990]))
        writeToFile(result.stringify())
Esempio n. 29
0
from telethon.sync import TelegramClient
import csv

from telethon.sync import TelegramClient
api_id = 1324758
api_hash = '2dab5e95d688ddfed63daf529d215e98'
phone = '+84768458782'
client = TelegramClient(phone, api_id, api_hash)

client.connect()
if not client.is_user_authorized():
    client.send_code_request(phone)
    client.sign_in(phone, input('Enter the code: '))

from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
chats = []
last_date = None
chunk_size = 200
groups = []

result = client(
    GetDialogsRequest(offset_date=last_date,
                      offset_id=0,
                      offset_peer=InputPeerEmpty(),
                      limit=chunk_size,
                      hash=0))
chats.extend(result.chats)

for chat in chats:
    try:
Esempio n. 30
0
def uploader(file):
    api_id = 3334083
    api_hash = "358df460e06a3e54e158276c1293790c"

    client = TelegramClient('bot', api_id, api_hash)
    client.start()