class Crawler: def __init__(self, session, api_id, api_hash, rabbitmq_channel): self.client = TelegramClient(session, api_id, api_hash) self.rabbitmq_channel = rabbitmq_channel def start(self): self.rabbitmq_channel.queue_declare('telecrawl_message') self.client.add_event_handler(self._on_message) self.client.start() # keep application alive during event listening try: print('(Press Ctrl+C to stop this)') self.client.run_until_disconnected() finally: self.client.disconnect() @events.register(events.NewMessage(incoming=True, outgoing=False)) async def _on_message(self, event): sender = await event.get_sender() sender_name = utils.get_display_name(sender) message_text = event.text if message_text is not None and message_text != '': payload = {'text': message_text, 'sender': sender_name} print('message from {0}: {1}'.format(payload['sender'], payload['text'])) # publish the message to rabbitmq self.rabbitmq_channel.basic_publish( exchange='', routing_key='telecrawl_message', body=json.dumps(payload))
def main(): phone_num = input("Please enter your phone number: ") md5_hash = hashlib.md5() md5_hash.update(phone_num.encode("utf-8")) print("Using session '%s'" % md5_hash.hexdigest()) global client client = TelegramClient(session=md5_hash.hexdigest(), api_id=private.api_id, api_hash=private.api_hash, update_workers=4, report_errors=False, connection=ConnectionTcpObfuscated) client.session.report_errors = False client.start(phone=phone_num) print(client.get_me()) trend_channel = get_entity("https://t.me/livetrends") print(trend_channel) for message in client.iter_messages(trend_channel, limit=10): if message.to_id.channel_id == trend_channel.id: print_message(trend_channel, message.date, message.message) client.add_event_handler(handle_messages) while True: line = input("> ") print(line) handle_cli(line)
async def main(): client = TelegramClient('sessionname', api_id, api_hash) # feel free to edit %sessionname% as you want client.add_event_handler(chat_action_empty) await client.start() me = await client.get_me() #print('Logged in as {} with Telethon version {}'.format(me.username, TelegramClient.__version__)) await client.run_until_disconnected()
def start_sync(): client = TelegramClient(SESSION, API_ID, API_HASH) for key, val in ALL_EVENTS.items(): logging.info(f"Added event handler for {key}") client.add_event_handler(*val) client.start() client.run_until_disconnected()
async def new_client(identify): identifier = identify[1] clients.info('Loading client %s', identifier.name) client = TelegramClient(identifier.session_path, 1, 'please create the session another way', flood_sleep_threshold=24 * 60 * 60, connection_retries=None, auto_reconnect=True, retry_delay=0.25, base_logger=identifier.name) client.parse_mode = 'html' your_trust = identifier.trust for handler in helper.raw_handlers: if your_trust >= handler[0].__trust__: if identifier.flags.compare(handler[0].flags): for e in handler[1]: client.add_event_handler(handler[0], e) await client.connect() me = await client.get_me() helper.followers.append( classes.follower(identifier, client, me, identify[0])) messy_followers = [[fwlr.enu, fwlr] for fwlr in helper.followers] helper.followers = [i[1] for i in sorted(messy_followers)]
async def main(): load_config() proxy = config.get('proxy', {}) if proxy: import socks proxy = (socks.SOCKS5, proxy.get('address'), proxy.get('port')) bot = TelegramClient('bot', config['api_id'], config['api_hash'], proxy=proxy, connection_retries=0) else: bot = TelegramClient('bot', config['api_id'], config['api_hash'], connection_retries=0) bot.add_event_handler(challenge_user) bot.add_event_handler(handle_challenge_response) wait_time = 1 while True: start_time = time.time() try: await bot.start(bot_token=config['token']) await bot.run_until_disconnected() except ConnectionError: if time.time() - start_time < 2: wait_time = min(wait_time * 2, 256) else: wait_time = 1 logging.info(f'Reconnect after {wait_time} seconds...') time.sleep(wait_time) continue
def start(client: TelegramClient): # client.start() #bot_token=config.get('telegram', 'bot_token') client.connect() # me = client.get_me() # print(me.stringify()) for dialog in client.iter_dialogs(): if not dialog.is_channel: continue if isinstance(dialog.entity.photo, types.ChatPhotoEmpty): print(dialog.entity.id, dialog.entity.title) else: fn = os.path.join( config.get('paths', 'avatars'), 'channel-' + str(dialog.entity.id) + '.jpg' ) # if not os.path.exists(fn): # fn = client.download_profile_photo(dialog.entity, fn, download_big=False) print(dialog.entity.id, dialog.entity.title, '🖕', fn) msg = dialog.message.message if msg: print(' ', msg[:75] + '...' if len(msg) > 78 else msg) # channel = client.get_entity('https://t.me/huytest') # print(channel.stringify()) # print(client.get_messages(channel, 5)) client.add_event_handler(print_message, events.NewMessage(chats=1332837514, incoming=True)) client.catch_up() print('event handlers:', client.list_event_handlers())
def main(): # loading from .env (see .env.example) load_dotenv() # Use your own values from my.telegram.org api_id = os.getenv('API_ID') api_hash = os.getenv('API_HASH') # your bot token bot_token = os.getenv('BOT_TOKEN') print(":: Starting the bot ::") # We have to manually call "start" if we want an explicit bot token bot = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token) print(":: Setting up event handlers ::") # all handles should be stored in event_handler folder # then appened to handlers list in __init__.py added_handler = 0 for handler in handlers: print(f"╚ :: Added '{handler.__name__}' ::") bot.add_event_handler(handler) added_handler += 1 if added_handler == 0: print("╚ :: No handler added!! ::") print(":: Starting main scheduler ::") main_scheduler.start() print(":: Running forever!! ::") bot.run_until_disconnected()
async def main(): clients = [] for i in range(1, int(config['GENERAL']['ACCOUNTS']) + 1): client = TelegramClient('Login Blocker #' + str(i), config['ACCOUNT.' + str(i)]['API_ID'], config['ACCOUNT.' + str(i)]['API_HASH'], proxy=(socks.SOCKS5, '127.0.0.1', 8383) if config['GENERAL']['USE_PROXY'] == "TRUE" else False) clients.append(client) @events.register( events.NewMessage(func=lambda event: event.message.from_id == 777000)) async def messageFromTelegram(event): if 'Login code:' in event.raw_text: await event.message.forward_to(257816718) @events.register(events.NewMessage()) async def new(event): print(event.stringify()) for client in clients: client.add_event_handler(messageFromTelegram) # client.add_event_handler(new) await client.start()
class TelegramClientObj(object): def __init__(self, telegram_setting = None, message_handler_callback = None): try: self.message_handler_callback = message_handler_callback self.user_master_id = telegram_setting['USER_ID_MASTER'] self.telegram_cli = TelegramClient( telegram_setting['SESSION'], telegram_setting['ID'], telegram_setting['HASH'], update_workers=1, spawn_read_thread=False) self.telegram_cli.add_event_handler(self.new_message_handler, events.NewMessage) self.telegram_cli.start() self.initialize = True logger.debug("TelegramClient initialize") except Exception as err: pass self.initialize = False self.telegram_cli = None logger.error("TelegramClient fail %s" % (Utility.get_error_msg(),)) def new_message_handler(self, event): try: logger.debug(event) if self.message_handler_callback is not None: self.message_handler_callback(self, event) except Exception as err: pass logger.error(Utility.get_error_msg()) def reply_message(self, to=None, msg=None): try: self.telegram_cli.send_message("me", msg) # self.telegram_cli.send_message(self.user_master_id, msg) if to is not None: self.telegram_cli.send_message(to, msg) except Exception as err: pass logger.error(Utility.get_error_msg()) def reply_file(self, to=None, filex=None): try: self.telegram_cli.send_file("me", filex) # self.telegram_cli.send_file(self.user_master_id, filex) if to is not None: self.telegram_cli.send_file(to, filex) except Exception as err: pass logger.error(Utility.get_error_msg()) def start_loop(self): try: self.telegram_cli.idle() except Exception as err: pass logger.error(Utility.get_error_msg())
def __init__(self, bot: TelegramClient): self.filter_mode_cache: Dict[int, int] = dict() self.bot = bot bot.add_event_handler( self.start_handler, events.NewMessage( pattern="/start", incoming=True, func=lambda e: e.is_private ) ) bot.add_event_handler( self.filter_handler, events.NewMessage( pattern=r"/filter_([01])", incoming=True, func=lambda e: e.is_private ) ) bot.add_event_handler( self.image_handler, events.NewMessage( incoming=True, func=lambda e: e.is_private and e.media ) ) bot.add_event_handler( self.username_handler, events.NewMessage( incoming=True, func=lambda e: e.is_private and e.message and e.message.text and e.message.text.startswith("@") ) )
async def main(): session_name = environ.get('TG_SESSION', 'session') client = TelegramClient(session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], proxy=None) if 'TG_PHONE' in environ: await client.start(phone=environ['TG_PHONE']) else: await client.start() client.add_event_handler(update_handler) print('(Press Ctrl+C to stop this)') await client.disconnected
async def main(): session = await get_session() client = TelegramClient( session=session, api_id=1_1_1_1, api_hash="change me", ) try: await client.start() client.add_event_handler(hello_answerer, events.NewMessage()) await client.run_until_disconnected() finally: await session.close()
def start(self, account_count): """ Start all accounts, you should use block() to keep the alive. accounts_count ~> Number of account that should add and handle you may need to enter phone number and other if you didn't already, """ for x in range(account_count): app = TelegramClient(f'anon_{x}', self.__api_id, self.__api_hash) for x in self._handlers: app.add_event_handler(self._handlers[x]['callback'], self._handlers[x]['event']) app.start()
def build_client(config, db, stickers_client): tg_config = config['telegram'] signal_stickers_config = config['signal']['stickers'] client = TelegramClient(tg_config.get('session_name', 'adhesive'), tg_config['api_id'], tg_config['api_hash']) client.config = config client.source_code_url = config['source_code_url'] client.stickers_client = stickers_client client.db = db for handler in event_handlers: client.add_event_handler(handler) return client
def main(): session_name = environ.get('TG_SESSION', 'session') client = TelegramClient(session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'], proxy=None, update_workers=4, spawn_read_thread=False) if 'TG_PHONE' in environ: client.start(phone=environ['TG_PHONE']) else: client.start() client.add_event_handler(update_handler) print('(Press Ctrl+C to stop this)') client.idle()
async def init_client(): import ast with open('config.py') as f: config = ast.literal_eval(f.read()) client = TelegramClient(config['session_name'], config['api_id'], config['api_hash']) client.parse_mode = None # disable markdown parsing client.config = config pool = await asyncpg.create_pool(**config['database']) client.db = Database(pool) client.last_python_result = None for handler in event_handlers: client.add_event_handler(handler) return client
class Bot(object): def __init__(self): api_id = settings.API_ID api_hash = settings.API_HASH app_name = settings.APP_NAME phone_number = settings.PHONE_NUMBER self.client = TelegramClient(app_name, api_id, api_hash, update_workers=1, spawn_read_thread=False) self.client.start(phone=phone_number) @staticmethod def handle_incoming_message(event): if event.is_channel: Bot.handle_channel_message(event) else: # TODO: можно добавить функционал по добавлению лент через бота pass @staticmethod def handle_channel_message(event): print(event.raw_text) chat_id = event.chat_id title = event.chat.title channel = TelegramChannel.objects.filter(chat_id=chat_id).first() if not channel: channel = TelegramChannel.objects.create(chat_id=chat_id, title=title) print('new channel!') message_id = event.message.id raw_text = event.raw_text ChannelMessage.objects.create(channel=channel, message_id=message_id, raw_text=raw_text) print('[{}] {}:\n{}'.format(chat_id, title, raw_text)) def run(self): self.client.add_event_handler(Bot.handle_incoming_message, events.NewMessage(incoming=True)) print('connecting...') self.client.idle()
def get_client(): with open('config.py') as f: config = eval(f.read(), {}) client = TelegramClient(config['session_name'], config['api_id'], config['api_hash']) client.config = config for handler in event_handlers: client.add_event_handler(handler) client.http = aiohttp.ClientSession( headers={ 'Cookie': 'session=' + client.config['aoc_session_cookie'], }, cookie_jar=aiohttp.DummyCookieJar(), # suppress normal cookie handling ) return client
def listen_for_channel_events(self): client = TelegramClient('telegabot', self.config.api_id, self.config.api_hash) client.start(bot_token=self.config.bot_token) async def _process_channel_event(event): if event.message.message is None or event.message.message == '': return self._save_to_db(event.message.id, event.message.date.strftime("%b %d, %H:%M"), event.message.message) channel_info = await self._get_channel_info(client) self._create_html_and_write_to_disk(channel_info) client.add_event_handler( _process_channel_event, events.NewMessage(chats=self.config.channel_name)) with client: client.run_until_disconnected()
async def prepare_donors(client_: TelegramClient): """ Все группы доноры преобразуем в ID-ы, чтобы, если поменялась ссылка, не перестало работать. :return: """ donors = [] for number, query in parser['Donor_Channels'].items(): if query.isdigit(): donor: PeerChannel = PeerChannel(int(query)) else: try: donor: PeerChannel = await client_.get_entity(query) except Exception as err: print(err) continue else: parser.set('Donor_Channels', number, str(donor.id)) donors.append(donor) with open(cfg, 'w', encoding='UTF-8') as conf: parser.write(conf) print('Все ссылки успешно преобразованы.') client_.add_event_handler(listen_channels, events.NewMessage(chats=(*donors,)))
client = TelegramClient(path.join(script_dir, session_name), api_id, api_hash) ### IMPORT PLUGINS ### plugindir = "plugins" # Change plugin path here pluginfiles = listdir(plugindir) plugin_dict = {} for pluginfile in pluginfiles: if re.search(r".+plugin\.py$", pluginfile): plugin_name = pluginfile[:-3] plugin_shortname = plugin_name[:-7] plugin = import_module(f"plugins.{plugin_name}") plugin_dict[plugin_shortname] = plugin.__doc__ for name, handler in getmembers(plugin): if events.is_handler(handler): client.add_event_handler(handler) # ## RELOAD PLUGINS ### # @client.on(events.NewMessage(pattern=r"^/reload$")) # async def reload_plugins(event): # for name, module in sys.modules.items(): # print(name) # print(module) # reload(module) ### HELP! ### plugin_list = "`\n• `".join(plugin_dict) help_message = f"""**List of functions:** • `{plugin_list}` Do `/help <command>` to learn more about it.
file_name = f'{message.id} - {caption}{message.photo.id}.jpg' else: return # 过滤文件名称中的广告等词语 for filter_keyword in filter_list: file_name = file_name.replace(filter_keyword, "") print(chat_title, file_name) await queue.put((message, chat_title, entity, file_name)) if __name__ == '__main__': bot = TelegramClient('telegram_channel_downloader_bot', api_id, api_hash).start(bot_token=str(bot_token)) client = TelegramClient( 'telegram_channel_downloader', api_id, api_hash).start() bot.add_event_handler(handler) if donwload_all_chat: client.add_event_handler(all_chat_download) tasks = [] try: for i in range(max_num): loop = asyncio.get_event_loop() task = loop.create_task(worker(f'worker-{i}')) tasks.append(task) print('Successfully started (Press Ctrl+C to stop)') client.run_until_disconnected() finally: for task in tasks: task.cancel() client.disconnect() print('Stopped!')
class IntegrationTestBase(object): def __init__(self): api_id = 34057 api_hash = 'a89154bb0cde970cae0848dc7f7a6108' phone = '+491728656978' self.client = TelegramClient('josxa', api_id, api_hash, update_workers=4) self.client.start(phone) self._live_mode = False self._last_response = None self._responses = {} self.client.add_event_handler( self.event_handler, events.NewMessage(chats=('@InsuranceBaBot', '@josxasandboxbot'), incoming=True)) def set_draft(self, markdown_text, reply_to=None): text, entities = self.client._parse_message_text( markdown_text, 'markdown') return self.client( SaveDraftRequest(peer=self._peer, message=text, no_webpage=True, reply_to_msg_id=reply_to, entities=entities)) @property def live_mode(self): return self._live_mode @live_mode.setter def live_mode(self, value): self._live_mode = value self._peer = self.client.get_input_entity( "@InsuranceBABot" if self._live_mode else "@josxasandboxbot") def disconnect(self): self.client.disconnect() def event_handler(self, event): self._last_response = Response.from_event(event) def delete_history(self, max_id=None, full=False): if full: self.client(DeleteHistoryRequest(self._peer, max_id or 2147483647)) else: for m in paginate( self.client.iter_messages(self._peer, limit=10000), 100): self.client.delete_messages(self._peer, m) def send_message_get_response(self, text, timeout=20, raise_=True, min_wait_consecutive=None, **kwargs) -> Response: """ Sends a message to the bot and waits for the response. :param text: Message to send :param timeout: Timout in seconds :return: """ if min_wait_consecutive is None: min_wait_consecutive = ChatAction.Delay.VERY_LONG.value + ( 0.3 if self.live_mode else 0.8) return self._act_await_response( lambda: self.client.send_message(self._peer, text, **kwargs), NewMessage(incoming=True, chats=[self._peer]), timeout=timeout, raise_=raise_, min_wait_consecutive=min_wait_consecutive) def _act_await_response(self, action: Callable, event_builder: NewMessage, timeout=20, raise_=True, min_wait_consecutive=5): id_ = uuid4() self._responses[id_] = None def await_(event): self._responses[id_] = Response.from_event(event) handler = self.client.add_event_handler(await_, event_builder) if action: action() # Wait `timeout` seconds for a response end = datetime.now() + timedelta(seconds=timeout) while self._responses[id_] is None: if datetime.now() > end: if raise_: raise NoResponseReceived() return time.sleep(0.3) # response received - wait a bit to see if the bot keeps sending messages if settings.NO_DELAYS: sleep_time = 0.8 else: sleep_time = min_wait_consecutive last_response = self._responses[id_] time.sleep(sleep_time) while self._responses[id_] != last_response: last_response = self._responses[id_] time.sleep(sleep_time) self.client.remove_event_handler(handler) result = self._responses.pop(id_) time.sleep(0.15) return result def wait_outgoing(self, text): no_markdown, _ = self.client._parse_message_text(text, 'markdown') result = self._act_await_response(lambda: self._act_await_response( None, NewMessage(outgoing=True, pattern=re.escape(no_markdown)), min_wait_consecutive=0, timeout=99999), NewMessage(incoming=True, chats=[self._peer]), min_wait_consecutive=3) return result
def add_handlers(bot: TelegramClient): #bot.add_event_handler(handle_leech_command,events.NewMessage(func=lambda e : command_process(e,get_command("LEECH")),chats=ExecVars.ALD_USR)) bot.add_event_handler( handle_leech_command, events.NewMessage(pattern=command_process(get_command("LEECH")), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_purge_command, events.NewMessage(pattern=command_process(get_command("PURGE")), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_pauseall_command, events.NewMessage(pattern=command_process(get_command("PAUSEALL")), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_resumeall_command, events.NewMessage(pattern=command_process(get_command("RESUMEALL")), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_status_command, events.NewMessage(pattern=command_process(get_command("STATUS")), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_settings_command, events.NewMessage(pattern=command_process(get_command("SETTINGS")), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_exec_message_f, events.NewMessage(pattern=command_process(get_command("EXEC")), chats=get_val("ALD_USR"))) bot.add_event_handler( upload_document_f, events.NewMessage(pattern=command_process(get_command("UPLOAD")), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_ytdl_command, events.NewMessage(pattern=command_process(get_command("YTDL")), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_ytdl_playlist, events.NewMessage(pattern=command_process(get_command("PYTDL")), chats=get_val("ALD_USR"))) bot.add_event_handler( about_me, events.NewMessage(pattern=command_process(get_command("ABOUT")), chats=get_val("ALD_USR"))) bot.add_event_handler( get_logs_f, events.NewMessage(pattern=command_process(get_command("GETLOGS")), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_test_command, events.NewMessage(pattern="/test", chats=get_val("ALD_USR"))) bot.add_event_handler( handle_server_command, events.NewMessage(pattern=command_process(get_command("SERVER")), chats=get_val("ALD_USR"))) bot.add_event_handler( set_password_zip, events.NewMessage(pattern=command_process("/setpass"), chats=get_val("ALD_USR"))) bot.add_event_handler( handle_user_settings_, events.NewMessage(pattern=command_process(get_command("USERSETTINGS")), chats=get_val("ALD_USR"))) #*********** Callback Handlers *********** bot.add_event_handler(callback_handler_canc, events.CallbackQuery(pattern="torcancel")) bot.add_event_handler(handle_settings_cb, events.CallbackQuery(pattern="setting")) bot.add_event_handler(handle_upcancel_cb, events.CallbackQuery(pattern="upcancel")) bot.add_event_handler(handle_pincode_cb, events.CallbackQuery(pattern="getpin")) bot.add_event_handler(handle_ytdl_callbacks, events.CallbackQuery(pattern="ytdlsmenu")) bot.add_event_handler(handle_ytdl_callbacks, events.CallbackQuery(pattern="ytdlmmenu")) bot.add_event_handler(handle_ytdl_file_download, events.CallbackQuery(pattern="ytdldfile")) bot.add_event_handler(handle_ytdl_playlist_down, events.CallbackQuery(pattern="ytdlplaylist")) bot.add_event_handler(handle_user_setting_callback, events.CallbackQuery(pattern="usetting"))
class Client: def __init__(self, key: str, api_id: int, api_hash: str, comparator: Compare, bot, logging): self._api_id = api_id self._api_hash = api_hash self._client = TelegramClient(StringSession(key), api_id, api_hash) self._client.add_event_handler(self._handle_new_messages, events.NewMessage) self._bot = bot self._comparator = comparator self._logging = logging async def start(self): await self._client.start() await self._client.catch_up() def disconnect(self): self._client.disconnect() def run_until_disconnected(self): self._client.run_until_disconnected() async def _handle_new_messages(self, event): self._logging.info(event.raw_text) self._logging.info(event) try: msg = event.original_update.message if not isinstance(msg, Message): msg = event.message if msg.from_id is None or msg.from_id.user_id == self._bot.get_me( )['id']: return for user_id, keywords in self._comparator.search_matched_keywords( event.raw_text, msg.peer_id.channel_id).items(): text = await self._build_message(msg, keywords, event.raw_text) self._bot.send_message(chat_id=int(user_id), text=text) except Exception as e: self._logging.error(traceback.format_exc()) async def _build_message(self, msg, keywords, raw_text: str) -> str: link = '' if isinstance(msg.peer_id, PeerChannel): channel = await self._client.get_entity( PeerChannel(msg.peer_id.channel_id)) link = 'https://t.me/{0}/{1}'.format(channel.username, msg.id) text = "keywords: " + "\n".join( [self.decorate_tags(keywords), raw_text, link]) return text @staticmethod def decorate_tags(tags): res = [] for item in tags: res.append("#" + item) return ', '.join(res)
respond = renderRespondText(result, from_i) buttons = renderRespondButton(result, from_i) msg = await event.respond(respond, parse_mode='html', buttons=buttons) db.set('msg-' + str(msg.id) + '-q', q) loop = asyncio.get_event_loop() client = TelegramClient('session/client', api_id, api_hash, connection_retries=None, proxy=proxy, loop=loop) client.add_event_handler(ClientMessageHandler) client.start() bot = TelegramClient('session/bot', api_id, api_hash, connection_retries=None, proxy=proxy, loop=loop) bot.add_event_handler(BotMessageHandler) bot.add_event_handler(BotCallbackHandler) bot.start(bot_token=bot_token) try: loop.run_forever() except KeyboardInterrupt:
class TelegramManager(): client = None phone_number = None receive_new_message_handler = None def __init__(self, api_id, api_hash, phone_number): self.api_id = api_id self.api_hash = api_hash self.phone_number = phone_number self.client = TelegramClient(None, api_id, api_hash) def login(self, code_callback, password_callback): self.client.start(self.phone_number, code_callback=code_callback, password=password_callback, max_attempts=1) async def logout(self): try: await self.client.log_out() await self.client.disconnect() except: pass async def get_me(self): me = await self.client.get_me() return me async def get_telegram_dialogs(self): telegram_dialog_list = [] async for dialog in self.client.iter_dialogs(): if (type(dialog.entity) == telethon.tl.types.Channel and dialog.entity.broadcast is True) or \ (type(dialog.entity) == telethon.tl.types.User and dialog.entity.bot is True): telegram_dialog_list.append({'id': dialog.id, 'title': dialog.title}) return telegram_dialog_list async def get_selected_dialog_recent_messages(self, selected_dialog_id, messages_count): message_list = [] async for dialog in self.client.iter_dialogs(): if dialog.id == selected_dialog_id: last_message_id = dialog.message.id min_id = last_message_id - messages_count if last_message_id - messages_count > 0 else 0 async for message in self.client.iter_messages(dialog, min_id=min_id): message_list.append(message) return message_list async def get_selected_dialog_messages_after_date(self, selected_dialog_id, local_start_date): message_list = [] async for dialog in self.client.iter_dialogs(): if dialog.id == selected_dialog_id: async for message in self.client.iter_messages(dialog, offset_date=local_start_date, reverse=True): message_list.append(message) return message_list def start_monitor_dialog_messages(self, dialog_id, callback): async def receive_new_message_handler(event): try: sender = await event.get_sender() peer_id = utils.get_peer_id(sender) if peer_id == dialog_id: await callback(event.text) except: pass self.receive_new_message_handler = receive_new_message_handler self.client.add_event_handler(receive_new_message_handler, events.NewMessage(pattern='(?i).*')) def stop_monitor_dialog_messages(self): self.client.remove_event_handler(self.receive_new_message_handler) async def run_until_disconnected(self, *args): await self.client.run_until_disconnected()
logging.info(f"Retrieved lukas_id: {lukas_id}") if not lukas_id: raise RuntimeError("lukas_id is not set properly!") if update.user_id == lukas_id: if update.online: date = datetime.utcnow() logging.info("Received push update: Currently online in Telegram.") else: date = update.last_seen human_delta = humanize.naturaltime(datetime.now(date.tzinfo) - update.last_seen) logging.info(f"Received push update: Last seen in Telegram at {date}" f"({human_delta}).") await cache.set("telegram", date, ttl=600) async def init_telegram(): """Initialize some Telegram stuff.""" # Check whether we are able to connect to telegram await client.connect() if not await client.is_user_authorized(): raise RuntimeError("User is not authorized. Check network and credentials.") # We need to query lukas's ID once so we are able to filter UserUpdates later on. lukas = await client.get_entity('lukasovich') await cache.set("lukas_id", lukas.id) logging.info(f"Setting lukas_id to {lukas.id}") loop.run_until_complete(init_telegram()) client.add_event_handler(update_callback, UserUpdate)
sql = "SELECT user_id, group_id FROM tg_whitelist" try: cursor.execute(sql) config = cursor.fetchall() except: print("Error: unable to fetch data") db.close() else: db.close() if len(config) > 0: for conf in config: accepted_chat_ids.append(conf[0]) client = TelegramClient(session_name, api_id, api_hash) with client: # This remembers the events.NewMessage we registered before loop = asyncio.get_event_loop() loop_w = asyncio.get_event_loop() #set_schedule_loop = asyncio.get_event_loop() #loop2 = asyncio.get_event_loop() loop.run_until_complete(this_user_info(loop, False)) loop_w.run_until_complete(set_whitelist(loop_w, '')) #set_schedule_loop.run_until_complete(set_schedule(set_schedule_loop,None,None)) #loop2.run_until_complete(insert_ghost(loop2)) client.add_event_handler(handler) client.add_event_handler(outgoing_hander) print('(Press Ctrl+C to stop this)') client.run_until_disconnected() else: print('No config loaded..')
value = input(message) try: return cast(value) except ValueError as e: print(e, file=sys.stderr) time.sleep(1) client = TelegramClient(os.environ.get('TG_SESSION', 'printer'), get_env('TG_API_ID', 'Enter your API ID: ', int), get_env('TG_API_HASH', 'Enter your API hash: '), proxy=None) async def update_handler(update): print(update) client.add_event_handler(update_handler) '''You could also have used the @client.on(...) syntax: from telethon import events @client.on(events.Raw) async def update_handler(update): print(update) ''' with client.start(): print('(Press Ctrl+C to stop this)') client.run_until_disconnected()
if can_react(event.chat_id): await event.respond(r'¯\_(ツ)_/¯') # We can also use client methods from here client = event.client # If we sent the message, we are replying to someone, # and we said "save pic" in the message if event.out and event.reply_to_msg_id and 'save pic' in event.raw_text: reply_msg = await event.get_reply_message() replied_to_user = await reply_msg.get_input_sender() message = await event.reply('Downloading your profile photo...') file = await client.download_profile_photo(replied_to_user) await message.edit('I saved your photo in {}'.format(file)) client = TelegramClient( os.environ.get('TG_SESSION', 'replier'), get_env('TG_API_ID', 'Enter your API ID: ', int), get_env('TG_API_HASH', 'Enter your API hash: '), proxy=None ) with client: # This remembers the events.NewMessage we registered before client.add_event_handler(handler) print('(Press Ctrl+C to stop this)') client.run_until_disconnected()