def __init__(self, config): logger.info('Initiating bot') # TODO: obtain this dynamicly self.name = 'sluvka_bot' self.chat_id = -1001280237846 api_id = config['API_ID'] api_hash = config['API_HASH'] if config['USE_PROXY']: conn = tele.connection.ConnectionTcpMTProxyRandomizedIntermediate proxy_address = (config['PROXY_HOST'], config['PROXY_PORT'], config['PROXY_SECRET']) logger.info(f'Using proxy {proxy_address[0]}:{proxy_address[1]}') self.client = tele.TelegramClient('bot', api_id, api_hash, connection=conn, proxy=proxy_address) else: self.client = tele.TelegramClient('bot', api_id, api_hash) self.client.start(bot_token=config['TOKEN']) logger.info('Started Telegram Client') logger.info('Registering handlers') self.handler = Handler(self) logger.info('Bot initiated')
def __init__(self, loop: asyncio.AbstractEventLoop): self.client = telethon.TelegramClient( StringSession(), #self.config.SESS_NAME, self.config.APP_ID, self.config.API_HASH, loop=loop).start(bot_token=self.config.BOT_TOKEN) self.client2 = telethon.TelegramClient( StringSession(), #self.config.SESS_NAME2, self.config.APP_ID, self.config.API_HASH, loop=loop).start(bot_token=self.config.BOT_TOKEN2)
def __init__(self, loop: asyncio.AbstractEventLoop): self.client = telethon.TelegramClient( StringSession(), #self.config.SESS_NAME, self.config.APP_ID, self.config.API_HASH, loop=loop ).start(bot_token=self.config.BOT_TOKEN) self.client2 = telethon.TelegramClient( StringSession(), #self.config.SESS_NAME2, self.config.APP_ID, self.config.API_HASH, loop=loop ).start(bot_token=self.config.BOT_TOKEN2) self.master = telethon.TelegramClient( StringSession(self.config.MASTER_TOKEN), self.config.APP_ID, self.config.API_HASH, loop=loop ).start() print (self.master.session.save()) future = asyncio.ensure_future(set_online(self.master)) @self.client.on(events.NewMessage) @self.client2.on(events.NewMessage) async def download(event : events.NewMessage.Event): if event.is_private : #await self.set(event.sender_id , "dlgram") try: await event.client(functions.channels.GetParticipantRequest(channel=self.config.channel,user_id=event.sender_id)) except errors.UserNotParticipantError: await event.reply(f"First join to our official channel to access the bot or get the newest news about the bot\n\n@{self.config.channel}\n\nAfter that /start the bot aging.") return if event.file : sender = await event.get_sender() msg = await event.client.send_file(self.config.STATS_CHANNEL, file=event.message.media, caption=f"@{sender.username}|[{event.sender_id}](tg://user?id={event.sender_id})/{event.message.id}") #url = f"{msg.chat_id}/{msg.id}/{urllib.parse.quote(self.get_file_name(event))}" hash = self.encode(f"{msg.id}") url = f"{hash}/{urllib.parse.quote(self.get_file_name(event))}" await event.reply(f"Link to download file: \n\n🌍 : {self.config.ROOT_URI}/w/{url} \n\n🌍 : {self.config.ROOT_URI_3}/w/{url}") return elif urls := self.Find(event.raw_text) : await event.reply("Link to File \n Coming Soon ...") await event.reply("Send an image or file to get a link to download it")
def serve(arg): """ Run the REST API server, start listening from Telegram. """ vdb = store.VedisDB(':mem:') tgl = TelegramListener(telethon.TelegramClient('tg2pub', arg.api_id, args.api_hash), callback=lambda m: vdb.add_messages([m])) loop = asyncio.get_event_loop() j = pubs.JRPC(vdb, tgl) def bg_task(lp): def d(): asyncio.set_event_loop(lp) lp.run_until_complete(tgl.run()) return d # noinspection PyShadowingNames,PyUnusedLocal def signal_handler(sig, frame): tasks = [ t for t in asyncio.all_tasks() if t is not asyncio.current_task() ] [task.cancel() for task in tasks] sys.exit(0) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) t = threading.Thread(target=bg_task(loop)) t.start() j.start(5000)
async def initialize_telegram(self): # Setup media folder self.telegram_media_dir = os.path.join(self.config_dir, 'media') if not os.path.exists(self.telegram_media_dir): os.makedirs(self.telegram_media_dir) # Setup session folder self.telegram_session_dir = os.path.join(self.config_dir, 'session') if not os.path.exists(self.telegram_session_dir): os.makedirs(self.telegram_session_dir) # Construct Telegram client telegram_session = os.path.join(self.telegram_session_dir, 'telegram') self.telegram_client = telethon.TelegramClient(telegram_session, TELEGRAM_API_ID, TELEGRAM_API_HASH ) # Initialize Telegram ID to IRC nick mapping self.tid_to_iid = {} # Register Telegram callbacks callbacks = ( (self.handle_telegram_message , telethon.events.NewMessage), (self.handle_telegram_chat_action, telethon.events.ChatAction), ) for handler, event in callbacks: self.telegram_client.add_event_handler(handler, event) # Start Telegram client await self.telegram_client.connect() if await self.telegram_client.is_user_authorized(): self.authorized = True await self.init_mapping()
def _init_client(self, client_session): """Init a Telegram Client Args: client_session: dict Returns: A TelegramClient Object """ fn.stdout_title('\nLaunching client "%s" ...' % client_session['name']) client = telethon.TelegramClient(client_session['name'], conf.tg_api_id, conf.tg_api_hash, proxy=client_session['proxy']) client.connect() if client.is_user_authorized(): fn.print_success(' DONE') return client else: fn.print_warning(' Login by "%s"' % client_session['phone']) client.send_code_request(client_session['phone']) me = client.sign_in( client_session['phone'], input(colorama.Fore.LIGHTMAGENTA_EX + ' Login code: ')) fn.print_success(' Login for "%s" is SUCCESSFUL' % self._get_user_display_name(me)) if client.is_user_authorized(): return client else: return self._init_client(client_session)
async def start(self) -> None: logging.info( "NOTE: To receive NewMessage events in groups, you must disable group privacy for your bot using @BotFather." ) self._client = telethon.TelegramClient( session=self._opts["session_file"], api_id=self._opts["api_id"], api_hash=self._opts["api_hash"]) self._client.add_event_handler(self._on_receive, telethon.events.NewMessage) self._client.add_event_handler(self._on_chat_action, telethon.events.ChatAction) await self._client.start(bot_token=self._opts["bot_token"]) if not self._client.is_connected(): logging.error("Failed to connect") return # Cache this, so it can be accessed in non async methods when needed, e.g. Message.is_editable. me = await self._client.get_me() self._me = User(self, me) logging.info("Logged in as %s %s (%s, %s)", me.first_name, me.last_name, me.username, me.id) await self._on_ready() async with self._client: await self._client.run_until_disconnected()
def auth(arg): """ Authorize into Telegram account and create a session. """ tgl = TelegramListener( telethon.TelegramClient('tg2pub', arg.api_id, arg.api_hash), None) loop = asyncio.get_event_loop() loop.run_until_complete(tgl.auth())
def start_client(self): api_key, api_hash, bot_token = self._check_config() self.client = telethon.TelegramClient(self.settings.get_config("session_name", "bot0"), api_key, api_hash, connection=CTA) try: self.client.start(bot_token=bot_token) except (TokenInvalidError, AccessTokenExpiredError, AccessTokenInvalidError): self.logger.error("The bot token provided is invalid, exiting.") sys.exit(2)
async def on_startup(): for phone_number in CONFIG["phone_numbers"]: client = telethon.TelegramClient(f"sessions/{phone_number}", api_id=CONFIG["api_id"], api_hash=CONFIG["api_hash"]) client.add_event_handler(functools.partial(check_incoming_tg_message, phone_number), event=NewMessage()) auth_codes[phone_number] = None # noinspection PyTypeChecker,PyUnresolvedReferences await client.start(phone_number)
def __init__(self, phone, api_id, api_hash, group_id, auth_key=None, test_dc=0): self.phone = phone self.group_id = group_id self.auth_key = auth_key session = telethon.sessions.MemorySession() if not auth_key else telethon.sessions.StringSession(auth_key) if test_dc: session.set_dc(test_dc, "149.154.167.40", 80) self.login_code = str(test_dc) * 5 else: self.login_code = None self.client = telethon.TelegramClient(session, api_id, api_hash, connection_retries=None)
def launch(self): """ Запускает файл с параметрами: -s: выбираем куда логгировать: в файл или в консоль -l: проверяем логин и вводим телефон (только для одного пользователя) -c: показываем код в запущенном ТГ (только для одного пользователя) -r: «перезапуск»: все действия откладываются, чтобы не спамить все остальные аргументы будут приняты как имена сессии """ # -l if self.login: if len(self.users) > 1: sys.exit("Логин возможен только для одного пользователя") user = self.users[0] print(user) params = SESSIONS.get(user) print(params) client = telethon.TelegramClient('sessions/' + user, API_ID, API_HASH) client.connect() #bot = ChatWarsFarmBot(user, params) #bot.connect() if not client.is_user_authorized(): #client.send_code_request(params["phone"]) client.send_code_request(params["phone"]) client.sign_in(params['phone'], input('Enter the code: ')) sys.exit("Код уже был введен!") # -c #if self.code: # if len(self.users) > 1: # sys.exit("Могу показать код только у одного пользователя") # user = self.users[0] # params = SESSIONS.get(user) # bot = ChatWarsFarmBot(user, params, self.silent) # bot.connect() # _, message = bot.client.get_message(bot.updater.chats["telegram"]) # sys.exit(message[:23]) # Остальной набор jobs = [] for _, user in enumerate(self.users): params = SESSIONS.get(user) if not params: continue worker = mp.Process(target=self.launch_user, args=(user, params)) jobs.append(worker) worker.start()
def clientLogin(api_id: int,api_hash: str) -> object: # TODO: Support 2FA. client = telethon.TelegramClient(session='backup', api_id, api_hash) # Start a TelegramClient try: client.connect() if client.is_user_authorized(): # Check if user is logon return client else: print("It appears we don't have your Telegram Session, Now we will try log you in.") phone = input('Please enter you Telegram phone number: ') client.send_code_request(phone) # Request phone number client.sign_in(phone, input('Please enter the code you recieved')) # Login with verify code return client except Exception as e: print('Unexcepted error %e', e)
def __init__(self, config, config_path): self.commands = {} self.modules = {} self.listeners = {} self.log = logging.getLogger('bot') self.client = tg.TelegramClient('anon', config['telegram']['api_id'], config['telegram']['api_hash']) self.http_session = aiohttp.ClientSession() self.config = config self.config_path = config_path self.prefix = config['bot']['prefix'] self.last_saved_cfg = toml.dumps(config)
def __init__(self, config, config_path): self.commands = {} self.modules = {} self.listeners = {} self.log = logging.getLogger("bot") self.client = tg.TelegramClient("anon", config["telegram"]["api_id"], config["telegram"]["api_hash"]) self.http_session = aiohttp.ClientSession() self.config = config self.config_path = config_path self.prefix = config["bot"]["prefix"] self.last_saved_cfg = toml.dumps(config)
def __init__(self, config): logger.info('Initiating bot') self.mode = config['mode'] self.name = config.get('bot_name', '') telegram = config['telegram'] if telegram.get('use_proxy'): conn = tele.connection.ConnectionTcpMTProxyRandomizedIntermediate proxy = (telegram['proxy']['host'], telegram['proxy']['port'], telegram['proxy']['secret']) logger.info(f'Using proxy {proxy[0]}:{proxy[1]}') self.client = tele.TelegramClient('bot', telegram['api_id'], telegram['api_hash'], connection=conn, proxy=proxy) else: self.client = tele.TelegramClient('bot', telegram['api_id'], telegram['api_hash']) self.client.start(bot_token=telegram['token']) logger.info('Started Telegram Client') bot = config.get('bot', {}) self.slavka = Slavka(bot.get('model', {}), bot.get('phrases_path')) logger.info('Initiated Slavka') self.handler = HandlerManager(self.client, self.slavka, max_dialogs=bot.get('max_dialogs'), cache_size=bot.get('cache_size')) logger.info(f'Bot initiated')
def prepare_client(): with open(CONFIG_PATH) as f: CONFIG = json.load(f) session = Session.try_load_or_create_new(CONFIG['SESSION']) client = telethon.TelegramClient(session, CONFIG['API_ID'], CONFIG['API_HASH']) client.connect() if not client.is_user_authorized(): print('Not authorized') if not CONFIG['PRODUCTION']: authorize(client, CONFIG['PHONE_NUMBER']) else: raise Exception( 'Unable to authorize on production. Please deliver valid auth token' ) return client
async def init_client(self: "Bot") -> None: # Get Telegram parameters from config and check types session_name = self.tg_config["session_name"] if not isinstance(session_name, str): raise TypeError("Session name must be a string") api_id = self.tg_config["api_id"] if not isinstance(api_id, int): raise TypeError("API ID must be an integer") api_hash = self.tg_config["api_hash"] if not isinstance(api_hash, str): raise TypeError("API hash must be a string") # Initialize Telegram client with gathered parameters self.client = tg.TelegramClient(session_name, api_id, api_hash)
async def save_channel_posts(): try: with open(CONFIG_FILE_PATH) as f: cfg = json.load(f) client = telethon.TelegramClient(cfg['SESSION_ID'], cfg['API_ID'], cfg['API_HASH']) await client.connect() if not await client.is_user_authorized(): logger.error('User is not authorized') await client.send_code_request(cfg['PHONE']) try: await client.sign_in(cfg['PHONE'], input('Enter auth code: ')) except SessionPasswordNeededError: await client.sign_in(password=cfg['TWO_STEP_AUTH_PWD']) # To get channels from your own dialogs: # async for dialog in client.iter_dialogs(): # if isinstance(dialog.entity, Channel): # channel_name = dialog.name # client_id = dialog.entity.id # To get channels by their link/id for channel_name in ['@relative_strength_index']: logger.info(channel_name) dialog = await client(GetFullChannelRequest(channel_name)) update_time = int(time.time()) client_id = dialog.full_chat.id async for message in client.iter_messages(client_id, limit=30): post_id = message.id post_views = message.views publish_time = message.date msg = message.message if is_msg_valid(msg) and post_views: logger.info(msg) logger.info("{},{},{},{},{}".format( update_time, channel_name, post_id, from_utc_dtm_to_utc_timestamp(publish_time), post_views)) time.sleep(5) except Exception as e: logger.error(str(e))
async def send_tg_code(self, request): text = await request.text() phone = telethon.utils.parse_phone(text) if not phone: return web.Response(status=400) client = telethon.TelegramClient( telethon.sessions.MemorySession(), self.api_token.ID, self.api_token.HASH, connection=self.connection, proxy=self.proxy, connection_retries=None, ) await client.connect() await client.send_code_request(phone) self.sign_in_clients[phone] = client return web.Response()
async def set_configuration(self, request): if self.client_data and await self.check_user(request) is None: return web.Response(status=302, headers={"Location": "/"}) # User not connected. # Get data data = await request.text() if len(data) < 56: return web.Response(status=400) split = data.split("\n", 3) if len(split) != 4: return web.Response(status=400) api_id = split[0] api_hash = split[1] phone = telethon.utils.parse_phone(split[2]) api_key = split[3] # Check phone if not phone: return web.Response(status=400) # Check Heroku API Key if not re.fullmatch(r"[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}", api_key): return web.Response(status=400) self.heroku_api_key = api_key # Set api if any(c not in string.hexdigits for c in api_hash) or any(c not in string.digits for c in api_id): return web.Response(status=400) with open(os.path.join(utils.get_base_dir(), "telegram_api.py"), "w") as f: f.write("HASH = \"" + api_hash + "\"\nID = \"" + api_id + "\"\n") self.telegram_api = collections.namedtuple("telegram_api", ("ID", "HASH"))(api_id, api_hash) self.api_set.set() # Send code client = telethon.TelegramClient(telethon.sessions.MemorySession(), self.telegram_api.ID, self.telegram_api.HASH) await client.connect() await client.send_code_request(phone) self.sign_in_clients[phone] = client return web.Response()