async def wait(self, timeout: float = None): """ Waits for the token to be imported by a previously-authorized client, either by scanning the QR, launching the URL directly, or calling the import method. This method **must** be called before the QR code is scanned, and must be executing while the QR code is being scanned. Otherwise, the login will not complete. Will raise `asyncio.TimeoutError` if the login doesn't complete on time. Arguments timeout (float): The timeout, in seconds, to wait before giving up. By default the library will wait until the token expires, which is often what you want. Returns On success, an instance of :tl:`User`. On failure it will raise. """ if timeout is None: timeout = (self._resp.expires - datetime.datetime.now( tz=datetime.timezone.utc)).total_seconds() event = asyncio.Event() async def handler(_update): event.set() self._client.add_event_handler(handler, events.Raw(types.UpdateLoginToken)) try: # Will raise timeout error if it doesn't complete quick enough, # which we want to let propagate await asyncio.wait_for(event.wait(), timeout=timeout) finally: self._client.remove_event_handler(handler) # We got here without it raising timeout error, so we can proceed resp = await self._client(self._request) if isinstance(resp, types.auth.LoginTokenMigrateTo): await self._client._switch_dc(resp.dc_id) resp = await self._client( functions.auth.ImportLoginTokenRequest(resp.token)) # resp should now be auth.loginTokenSuccess if isinstance(resp, types.auth.LoginTokenSuccess): user = resp.authorization.user self._client._on_login(user) return user raise TypeError('Login token response was unexpected: {}'.format(resp))
def add_event_handler(self: 'TelegramClient', callback: callable, event: EventBuilder = None): """ Registers a new event handler callback. The callback will be called when the specified event occurs. Arguments callback (`callable`): The callable function accepting one parameter to be used. Note that if you have used `telethon.events.register` in the callback, ``event`` will be ignored, and instead the events you previously registered will be used. event (`_EventBuilder` | `type`, optional): The event builder class or instance to be used, for instance ``events.NewMessage``. If left unspecified, `telethon.events.raw.Raw` (the :tl:`Update` objects with no further processing) will be passed instead. Example .. code-block:: python from telethon import TelegramClient, events client = TelegramClient(...) async def handler(event): ... client.add_event_handler(handler, events.NewMessage) """ builders = events._get_handlers(callback) if builders is not None: for event in builders: self._event_builders.append((event, callback)) return if isinstance(event, type): event = event() elif not event: event = events.Raw() self._event_builders.append((event, callback))
@borg.on(events.NewMessage(incoming=True, func=lambda e: e.message.mentioned)) async def on_mentioned(event): if utils.get_peer_id(event.from_id) not in blocked_user_ids: return peer = await borg.get_input_entity(event.chat_id) if isinstance(peer, InputPeerChannel): o = tlf.channels.ReadMessageContentsRequest(peer, [event.message.id]) else: o = tlf.messages.ReadMessageContentsRequest([event.message.id]) await borg(o) @borg.on(events.Raw(types=UpdatePeerBlocked)) async def on_blocked(event): id = utils.get_peer_id(event.peer_id) if event.blocked: blocked_user_ids.add(id) else: blocked_user_ids.discard(id) async def fetch_blocked_users(): global blocked_user_ids while 1: offset = 0 blocked_ids = set() while 1: blocked = await borg(GetBlockedRequest(offset=offset, limit=100))
# someone added me to chat the_message = "" the_message += "#MessageActionChatAddUser\n\n" the_message += f"[User](tg://user?id={added_by_user}): `{added_by_user}`\n" the_message += f"[Private Link](https://t.me/c/{chat_id}/{message_id})\n" await event.client.send_message( entity=Config.PM_LOGGR_BOT_API_ID, message=the_message, # reply_to=, # parse_mode="html", link_preview=False, # file=message_media, silent=True) @borg.on(events.Raw()) async def on_new_channel_message(event): if Config.PM_LOGGR_BOT_API_ID is None: return try: if tgbot is None: return except Exception as e: logger.info(str(e)) return # logger.info(event.stringify()) if isinstance(event, types.UpdateChannel): channel_id = event.channel_id message_id = 2 # someone added me to channel # TODO: https://t.me/TelethonChat/153947
AUTH_TIME = 60 * 10 async def on_added(inviter_id, chat_id): if inviter_id == borg.uid: logger.info(f'Ignoring self add to {chat_id}') return if add_auths.get(inviter_id, 0) >= time.time(): logger.info(f'Removing temporary auth for {inviter_id}') del add_auths[inviter_id] return logger.info(f'Leaving {chat_id} (added by {inviter_id})') await borg.kick_participant(chat_id, 'me') # seems to happen on joining/leaving a channel @borg.on(events.Raw(types=UpdateChannel)) async def on_update_chan(e): channel_id = utils.get_peer_id(PeerChannel(e.channel_id)) entity = e._entities.get(channel_id) if isinstance(entity, tl.types.ChannelForbidden): return if isinstance(entity, tl.types.Channel) and (entity.left or not entity.broadcast): return channel = await borg.get_input_entity(channel_id) self_participant = await borg(GetParticipantRequest(channel, InputUserSelf())) if not hasattr(self_participant.participant, 'inviter_id'): return # assume the participant date is the added date (idk what else it could be) added_on = getattr(self_participant.participant, 'date', None) if not added_on: return
def __init__(self): config = configparser.ConfigParser() config.read('config.ini') api_id = config.get('telegram_api', 'api_id') api_hash = config.get('telegram_api', 'api_hash') workers = config.get('telegram_api', 'workers') session_name = config.get('telegram_api', 'session_name') self.timezone = int(config.get('other', 'timezone')) self.message_dialog_len = int(config.get('app', 'message_dialog_len')) # proxy settings if config.get('proxy', 'type') == "HTTP": proxy_type = socks.HTTP elif config.get('proxy', 'type') == "SOCKS4": proxy_type = socks.SOCKS4 elif config.get('proxy', 'type') == "SOCKS5": proxy_type = socks.SOCKS5 else: proxy_type = None proxy_addr = config.get('proxy', 'addr') proxy_port = int(config.get('proxy', 'port')) if config.get('proxy', 'port').isdigit() else None proxy_username = config.get('proxy', 'username') proxy_password = config.get('proxy', 'password') proxy = (proxy_type, proxy_addr, proxy_port, False, proxy_username, proxy_password) # create connection self.client = TelegramClient(session_name, api_id, api_hash, update_workers=int(workers), spawn_read_thread=True, proxy=proxy) self.client.start() self.me = self.client.get_me() self.dialogs = self.client.get_dialogs(limit=self.message_dialog_len) self.messages = len(self.dialogs) * [None] self.online = len(self.dialogs) * [""] self.messages[0] = self.client.get_message_history(self.dialogs[0].entity, limit=self.message_dialog_len) # event for new messages @self.client.on(events.NewMessage) def my_event_handler(event): for i in range(len(self.dialogs)): # if event message from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event._chat_peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event._chat_peer.chat_id: self.event_message(i) # from chat elif hasattr(self.dialogs[i].dialog.peer, 'channel_id') and hasattr(event._chat_peer, 'channel_id') and \ self.dialogs[i].dialog.peer.channel_id == event._chat_peer.channel_id: self.event_message(i) # other else: pass # event for read messages @self.client.on(events.Raw()) def my_event_handler(event): if hasattr(event, 'confirm_received') and hasattr(event, 'max_id'): for i in range(len(self.dialogs)): # from user if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event.peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event.peer.user_id: self.dialogs[i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # from chat elif hasattr(self.dialogs[i].dialog.peer, 'chat_id') and hasattr(event.peer, 'chat_id') and \ self.dialogs[i].dialog.peer.chat_id == event.peer.chat_id: self.dialogs[i].dialog.read_outbox_max_id = event.max_id self.need_update_current_user = i # other else: pass self.need_update_read_messages = 1 # event for online/offline @self.client.on(events.UserUpdate(chats=None, blacklist_chats=False)) def my_event_handler(event): for i in range(len(self.dialogs)): if hasattr(self.dialogs[i].dialog.peer, 'user_id') and hasattr(event._chat_peer, 'user_id') and \ self.dialogs[i].dialog.peer.user_id == event._chat_peer.user_id: # I think need little bit change this if event.online: self.online[i] = "Online" elif event.last_seen is not None: self.online[i] = "Last seen at " + str(event.last_seen + (timedelta(self.timezone) // 24)) else: self.online[i] = "" self.need_update_current_user = i self.need_update_online = 1
try: return cast(value) except ValueError as e: print(e, file=sys.stderr) time.sleep(1) bot = TelegramClient(os.environ.get('TG_SESSION', 'payment'), get_env('TG_API_ID', 'Enter your API ID: ', int), get_env('TG_API_HASH', 'Enter your API hash: '), proxy=None) # That event is handled when customer enters his card/etc, on final pre-checkout # If we don't `SetBotPrecheckoutResults`, money won't be charged from buyer, and nothing will happen next. @bot.on(events.Raw(_tl.UpdateBotPrecheckoutQuery)) async def payment_pre_checkout_handler(event: _tl.UpdateBotPrecheckoutQuery): if event.payload.decode('UTF-8') == 'product A': # so we have to confirm payment await bot( _tl.fn.messages.SetBotPrecheckoutResults(query_id=event.query_id, success=True, error=None)) elif event.payload.decode('UTF-8') == 'product B': # same for another await bot( _tl.fn.messages.SetBotPrecheckoutResults(query_id=event.query_id, success=True, error=None)) else: # for example, something went wrong (whatever reason). We can tell customer about that:
def __init__(self, watcher: SubscriptionWatcher): super().__init__( events.Raw(types.UpdateNewChannelMessage, func=filter_migration)) self.watcher = watcher
await e.edit(msg_text) return await process.kill() @client.on(events.NewMessage(pattern=r'^!zen.*', outgoing=True)) async def send_python_zen(event): with io.open('zen.txt', 'r', encoding='utf-8') as zen_fp: text = ''.join(zen_fp.readlines()) await asyncio.sleep(0.5) await client( SetTypingRequest(event.input_chat, SendMessageTypingAction())) await asyncio.sleep(2.5) await event.reply(text, parse_mode='Markdown') @client.on(events.Raw(types=UpdateDraftMessage)) async def translator(event: events.NewMessage.Event): global draft_semaphore await draft_semaphore.acquire() try: draft_list = await client.get_drafts() for draft in draft_list: if draft.is_empty: continue text = draft.text for lang_code in supported_langs.values(): if text.endswith('/{0}'.format(lang_code)): translated = mtranslate.translate( text[:-(len(lang_code) + 1)], lang_code, 'auto') for i in range(3): try:
await asyncio.sleep(sleep) await e.reply(msg) chat = await e.get_chat() if e.is_group and not sender.bot: if sender.username: await uname_stuff(e.sender_id, sender.username, sender.first_name) elif e.is_private and not sender.bot: if chat.username: await uname_stuff(e.sender_id, chat.username, chat.first_name) if detector and is_profan(e.chat_id) and e.text: x, y = detector(e.text) if y: await e.delete() @ultroid_bot.on(events.Raw(types.UpdateUserName)) async def uname_change(e): await uname_stuff(e.user_id, e.username, e.first_name) async def uname_stuff(id, uname, name): if udB.get_key("USERNAME_LOG") == "True": old_ = udB.get_key("USERNAME_DB") or {} old = old_.get(id) # Ignore Name Logs if old and old == uname: return if old and uname: await asst.send_message( LOG_CHANNEL, get_string("can_2").format(old, uname),
# someone added me to chat the_message = "" the_message += "#MessageActionChatAddUser\n\n" the_message += f"[User](tg://user?id={added_by_user}): `{added_by_user}`\n" the_message += f"[Private Link](https://t.me/c/{chat_id}/{message_id})\n" await event.client.send_message( entity=Config.PM_LOGGR_BOT_API_ID, message=the_message, # reply_to=, # parse_mode="html", link_preview=False, # file=message_media, silent=True) @borg.on(events.Raw()) # pylint:disable=E0602 async def on_new_channel_message(event): if Config.PM_LOGGR_BOT_API_ID is None: return try: if tgbot is None: return except Exception as e: logger.info(str(e)) return # logger.info(event.stringify()) if isinstance(event, types.UpdateChannel): channel_id = event.channel_id message_id = 2 # someone added me to channel # TODO: https://t.me/TelethonChat/153947
'Hungarian': 'hu', 'Vietnamese': 'vi', 'Icelandic': 'is', 'Welsh': 'cy', 'Indonesian': 'id', 'Yiddish': 'yi' } client = TelegramClient('opentfd_session', secret.api_id, secret.api_hash).start() last_msg = None break_date = None translated = mtranslate.translate('Тест', 'en', 'auto') print(translated) @client.on(events.Raw()) async def typing_handler(event): drafts = await client.get_drafts() for draft in drafts: if draft.is_empty: continue text = str(draft.text) for lang_code in supported_langs.values(): if text.endswith('/{0}'.format(lang_code)): translated = mtranslate.translate(text[:-(len(lang_code) + 1)], lang_code, 'auto') await draft.set_message(text=translated) print(draft.text) @client.on(events.NewMessage(incoming=True))
if not found: await sheets.append_col(sheetUrl, wsTitle, 1, date) if not exists: fName = userObject.first_name if userObject.first_name else '' lName = userObject.last_name if userObject.last_name else '' name = f'{fName} {lName}' await sheets.addUser(sheetUrl, wsTitle, [userId, name]) exists, userRow = await sheets.userExists(sheetUrl, wsTitle, userId, totalHeading=question, typeTitle='Day') await sheets.append_col(sheetUrl, wsTitle, userRow, value, colum=col) @client.on(events.Raw(types=[UpdateMessagePoll])) async def poll(event): pollId = event.poll_id # print(event.stringify()) if not await dbUtils.pollExists(pollId): return chosenAnswer = await dbUtils.getSelected(pollId, event.results.results) pollData = await dbUtils.getPollData(pollId) subject = pollData['subject'] questionNumber = pollData['questionNumber'] if chosenAnswer.option == b'0': value = 1 else: value = 0 newVoterId = event.results.recent_voters[0] admin = await client.get_me()