Python telethon.events.NewMessage() Examples
The following are 30
code examples of telethon.events.NewMessage().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
telethon.events
, or try the search function
.
Example #1
Source File: replier.py From Telethon with MIT License | 7 votes |
def can_react(chat_id): # Get the time when we last sent a reaction (or 0) last = recent_reacts[chat_id] # Get the current time now = time.time() # If 10 minutes as seconds have passed, we can react if now - last < 10 * 60: # Make sure we updated the last reaction time recent_reacts[chat_id] = now return True else: return False # Register `events.NewMessage` before defining the client. # Once you have a client, `add_event_handler` will use this event.
Example #2
Source File: opentfd.py From opentfd with Apache License 2.0 | 6 votes |
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 draft.set_message(text=translated) await asyncio.sleep(7) return except Exception as e: print(e) except Exception as e: print(e) finally: draft_semaphore.release()
Example #3
Source File: glink.py From BotHub with Apache License 2.0 | 6 votes |
def create_token_file(token_file, event): # Run through the OAuth flow and retrieve credentials flow = OAuth2WebServerFlow( CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI ) authorize_url = flow.step1_get_authorize_url() async with event.client.conversation(Config.PRIVATE_GROUP_BOT_API_ID) as conv: await conv.send_message(f"Go to the following link in your browser: {authorize_url} and reply the code") response = conv.wait_event(events.NewMessage( outgoing=True, chats=Config.PRIVATE_GROUP_BOT_API_ID )) response = await response code = response.message.message.strip() credentials = flow.step2_exchange(code) storage = Storage(token_file) storage.put(credentials) return storage
Example #4
Source File: gdrivenew.py From BotHub with Apache License 2.0 | 6 votes |
def create_token_file(token_file, event): # Run through the OAuth flow and retrieve credentials flow = OAuth2WebServerFlow( CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, redirect_uri=REDIRECT_URI ) authorize_url = flow.step1_get_authorize_url() async with event.client.conversation(Config.PRIVATE_GROUP_BOT_API_ID) as conv: await conv.send_message(f"Go to the following link in your browser: {authorize_url} and reply the code") response = conv.wait_event(events.NewMessage( outgoing=True, chats=Config.PRIVATE_GROUP_BOT_API_ID )) response = await response code = response.message.message.strip() credentials = flow.step2_exchange(code) storage = Storage(token_file) storage.put(credentials) return storage
Example #5
Source File: sangmata.py From BotHub with Apache License 2.0 | 5 votes |
def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.text: await event.edit("```reply to text message```") return chat = "@fakemailbot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit("```Processing```") async with borg.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=177914997)) await borg.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```Please unblock @sangmatainfo_bot and try again```") return if response.text.startswith("send"): await event.edit("```can you kindly disable your forward privacy settings for good?```") else: await event.edit(f"{response.message.message}")
Example #6
Source File: telegram.py From tgfilestream with GNU Affero General Public License v3.0 | 5 votes |
def handle_message(evt: events.NewMessage.Event) -> None: if not evt.is_private: await evt.reply(group_chat_message) return if not evt.file: await evt.reply(start_message) return url = public_url / str(pack_id(evt)) / get_file_name(evt) await evt.reply(f"Link to download file: [{url}]({url})") log.info(f"Replied with link for {evt.id} to {evt.from_id} in {evt.chat_id}") log.debug(f"Link to {evt.id} in {evt.chat_id}: {url}")
Example #7
Source File: opentfd.py From opentfd with Apache License 2.0 | 5 votes |
def bash(e: events.NewMessage.Event): cmd = e.pattern_match.group(1) print(cmd) # Wait for at most 1 second try: await asyncio.wait_for(run_command_shell(cmd, e), timeout=60.0) except asyncio.TimeoutError: print('timeout!')
Example #8
Source File: opentfd.py From opentfd with Apache License 2.0 | 5 votes |
def break_updater(event: events.NewMessage.Event): global break_time global last_msg with suppress(Exception): if event.chat: if event.chat.bot: return if last_msg: try: if (event.message.to_id.user_id == last_msg.from_id and last_msg.to_id.user_id == event.message.sender_id): break_time = time() except Exception: if event.to_id == last_msg.to_id: break_time = time()
Example #9
Source File: opentfd.py From opentfd with Apache License 2.0 | 5 votes |
def typing_imitate(message: events.NewMessage.Event): text, text_out = str(message.raw_text).split('->')[-1], str() word = list(text) with suppress(Exception): for letter in word: text_out += letter try: if word.index(letter) % 2 == 1: await message.edit(f'`{text_out}`|') else: await message.edit(f'`{text_out}`') await asyncio.sleep(0.2) except errors.MessageNotModifiedError: continue
Example #10
Source File: frybot.py From X-tra-Telegram with Apache License 2.0 | 5 votes |
def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.media: await event.edit("```reply to text message```") return chat = "@image_deepfrybot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit("```Processing```") async with borg.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=432858024)) await borg.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```Please unblock @sangmatainfo_bot and try again```") return if response.text.startswith("Forward"): await event.edit("```can you kindly disable your forward privacy settings for good?```") else: await borg.send_file(event.chat_id, response.message.media)
Example #11
Source File: randomsticker.py From X-tra-Telegram with Apache License 2.0 | 5 votes |
def choser(cmd, pack, blacklist={}): docs = None @borg.on(events.NewMessage(pattern=rf'\.{cmd}', outgoing=True)) async def handler(event): await event.delete() nonlocal docs if docs is None: docs = [ utils.get_input_document(x) for x in (await borg(functions.messages.GetStickerSetRequest(types.InputStickerSetShortName(pack)))).documents if x.id not in blacklist ] await event.respond(file=random.choice(docs))
Example #12
Source File: utils.py From X-tra-Telegram with Apache License 2.0 | 5 votes |
def __init__(self, func=None, **args): self.Var = Var bot.add_event_handler(func, events.NewMessage(**args))
Example #13
Source File: util.py From BotHub with Apache License 2.0 | 5 votes |
def admin_cmd(pattern=None, allow_sudo=False, **args): # get the pattern from the decorator if pattern is not None: if pattern.startswith("\#"): # special fix for snip.py args["pattern"] = re.compile(pattern) else: args["pattern"] = re.compile(Config.COMMAND_HAND_LER + pattern) args["func"] = lambda e: e.via_bot_id is None args["outgoing"] = True # should this command be available for other users? if allow_sudo: args["from_users"] = list(Config.SUDO_USERS) # Mutually exclusive with outgoing (can only set one of either). args["incoming"] = True # error handling condition check elif "incoming" in args and not args["incoming"]: args["outgoing"] = True # add blacklist chats, UB should not respond in these chats args["blacklist_chats"] = True black_list_chats = list(Config.UB_BLACK_LIST_CHAT) if len(black_list_chats) > 0: args["chats"] = black_list_chats # check if the plugin should allow edited updates allow_edited_updates = False if "allow_edited_updates" in args and args["allow_edited_updates"]: allow_edited_updates = args["allow_edited_updates"] del args["allow_edited_updates"] # check if the plugin should listen for outgoing 'messages' is_message_enabled = True return events.NewMessage(**args)
Example #14
Source File: antivirus.py From BotHub with Apache License 2.0 | 5 votes |
def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.media: await event.edit("```reply to a media message```") return chat = "@DrWebBot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit(" **covid19 will end with the end of April-2020 from the globe.** `still let me check this thing.`") async with borg.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=161163358)) await borg.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```Please unblock @sangmatainfo_bot and try again```") return if response.text.startswith("Forward"): await event.edit("```can you kindly disable your forward privacy settings for good?```") else: if response.text.startswith("Select"): await event.edit("`Please go to` @DrWebBot `and select your language.`") else: await event.edit(f"`Antivirus scan was completed.`\n**covid19 will end with the end of April-2020 from the globe.**\n`YAH, I got dem final results.`\n {response.message.message}")
Example #15
Source File: nice.py From BotHub with Apache License 2.0 | 5 votes |
def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.media: await event.edit("```reply to text message```") return chat = "@image_deepfrybot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit("```Processing```") async with borg.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=432858024)) await borg.send_message(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```Please unblock @sangmatainfo_bot and try again```") return if response.text.startswith("Forward"): await event.edit("```can you kindly disable your forward privacy settings for good?```") else: await borg.send_file(event.chat_id, response.message.media)
Example #16
Source File: assistant.py From Telethon with MIT License | 5 votes |
def handler(event): await event.delete() text = 'Available commands:\n' for callback, handler in bot.list_event_handlers(): if isinstance(handler, events.NewMessage) and callback.__doc__: text += f'\n{callback.__doc__.strip()}' text += '\n\nYou can suggest new commands [here](https://docs.google.com/'\ 'spreadsheets/d/12yWwixUu_vB426_toLBAiajXxYKvR2J1DD6yZtQz9l4/edit).' message = await event.respond(text, link_preview=False) await asyncio.sleep(1 * text.count(' ')) # Sleep ~1 second per word await message.delete()
Example #17
Source File: updates.py From Telethon with MIT License | 5 votes |
def on(self: 'TelegramClient', event: EventBuilder): """ Decorator used to `add_event_handler` more conveniently. Arguments event (`_EventBuilder` | `type`): The event builder class or instance to be used, for instance ``events.NewMessage``. Example .. code-block:: python from telethon import TelegramClient, events client = TelegramClient(...) # Here we use client.on @client.on(events.NewMessage) async def handler(event): ... """ def decorator(f): self.add_event_handler(f, event) return f return decorator
Example #18
Source File: updates.py From Telethon with MIT License | 5 votes |
def remove_event_handler( self: 'TelegramClient', callback: callable, event: EventBuilder = None) -> int: """ Inverse operation of `add_event_handler()`. If no event is given, all events for this callback are removed. Returns how many callbacks were removed. Example .. code-block:: python @client.on(events.Raw) @client.on(events.NewMessage) async def handler(event): ... # Removes only the "Raw" handling # "handler" will still receive "events.NewMessage" client.remove_event_handler(handler, events.Raw) # "handler" will stop receiving anything client.remove_event_handler(handler) """ found = 0 if event and not isinstance(event, type): event = type(event) i = len(self._event_builders) while i: i -= 1 ev, cb = self._event_builders[i] if cb == callback and (not event or isinstance(ev, event)): del self._event_builders[i] found += 1 return found
Example #19
Source File: updates.py From Telethon with MIT License | 5 votes |
def list_event_handlers(self: 'TelegramClient')\ -> 'typing.Sequence[typing.Tuple[callable, EventBuilder]]': """ Lists all registered event handlers. Returns A list of pairs consisting of ``(callback, event)``. Example .. code-block:: python @client.on(events.NewMessage(pattern='hello')) async def on_greeting(event): '''Greets someone''' await event.reply('Hi') for callback, event in client.list_event_handlers(): print(id(callback), type(event)) """ return [(callback, event) for event, callback in self._event_builders]
Example #20
Source File: payment.py From Telethon with MIT License | 5 votes |
def start_handler(event: events.NewMessage.Event): await bot.send_message( event.chat_id, 'Sending invoice A', file=generate_invoice( price_label='Pay', price_amount=10000, currency='RUB', title='Title A', description='description A', payload='product A', start_param='abc' ) )
Example #21
Source File: payment.py From Telethon with MIT License | 5 votes |
def start_handler(event: events.NewMessage.Event): await bot.send_message( event.chat_id, 'Sending invoice B', file=generate_invoice( price_label='Pay', price_amount=20000, currency='RUB', title='Title B', description='description B', payload='product B', start_param='abc' ) )
Example #22
Source File: payment.py From Telethon with MIT License | 5 votes |
def start_handler(event: events.NewMessage.Event): await bot.send_message( event.chat_id, 'Sending invoice C', file=generate_invoice( price_label='Pay', price_amount=50000, currency='RUB', title='Title C', description='description c - shall cause an error', payload='product C', start_param='abc' ) )
Example #23
Source File: sangmata.py From BotHub with Apache License 2.0 | 5 votes |
def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.text: await event.edit("```reply to text message```") return chat = "@SangMataInfo_bot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit("```Processing```") async with borg.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=461843263)) await borg.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```Please unblock @sangmatainfo_bot and try again```") return if response.text.startswith("Forward"): await event.edit("```can you kindly disable your forward privacy settings for good?```") else: await event.edit(f"{response.message.message}")
Example #24
Source File: interactive_telegram_client.py From Telethon with MIT License | 5 votes |
def message_handler(self, event): """Callback method for received events.NewMessage""" # Note that message_handler is called when a Telegram update occurs # and an event is created. Telegram may not always send information # about the ``.sender`` or the ``.chat``, so if you *really* want it # you should use ``get_chat()`` and ``get_sender()`` while working # with events. Since they are methods, you know they may make an API # call, which can be expensive. chat = await event.get_chat() if event.is_group: if event.out: sprint('>> sent "{}" to chat {}'.format( event.text, get_display_name(chat) )) else: sprint('<< {} @ {} sent "{}"'.format( get_display_name(await event.get_sender()), get_display_name(chat), event.text )) else: if event.out: sprint('>> "{}" to user {}'.format( event.text, get_display_name(chat) )) else: sprint('<< {} sent "{}"'.format( get_display_name(chat), event.text ))
Example #25
Source File: main.py From xiaomi_uranus_chatbot with GNU General Public License v3.0 | 5 votes |
def start(event): """Send a message when the command /start is sent.""" # sender_info = await get_user_info(event) # DATABASE.add_chat_to_db(sender_info) locale = DATABASE.get_locale(event.chat_id) if not event.is_private: message, buttons = await welcome_in_pm_message(locale) try: await event.reply(message, buttons=buttons) except ChatWriteForbiddenError: pass return try: key = event.message.message.split('/start ')[1] except IndexError: key = None if event.message.message.endswith('help'): await show_help(event) elif key and key != 'start': try: decoded = b64decode(key).decode() if "/subscribe" in decoded: event.message.message = decoded await subscribe(event) except UnicodeDecodeError: pass else: message, buttons = await welcome_message(locale) try: await event.reply(message, buttons=buttons, link_preview=False) except UserIsBlockedError: pass raise events.StopPropagation # Other handlers won't have an event to work with # @BOT.on(events.NewMessage) # async def echo(event): # """Echo the user message.""" # await event.respond(event.text) # # await event.respond('A single button, with "clk1" as data', # # buttons=Button.inline('Click me', b'clk1'))
Example #26
Source File: Qoutly.py From BotHub with Apache License 2.0 | 5 votes |
def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.text: await event.edit("```Reply to text message```") return chat = "@QuotLyBot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit("```Making a Quote```") async with event.client.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=1031952739)) await event.client.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```Please unblock me (@QuotLyBot) u Nigga```") return if response.text.startswith("Hi!"): await event.edit("```Can you kindly disable your forward privacy settings for good?```") else: await event.delete() await event.client.send_message(event.chat_id, response.message)
Example #27
Source File: randomsticker.py From BotHub with Apache License 2.0 | 5 votes |
def choser(cmd, pack, blacklist={}): docs = None @borg.on(events.NewMessage(pattern=rf'\.{cmd}', outgoing=True)) async def handler(event): await event.delete() nonlocal docs if docs is None: docs = [ utils.get_input_document(x) for x in (await borg(functions.messages.GetStickerSetRequest(types.InputStickerSetShortName(pack)))).documents if x.id not in blacklist ] await event.respond(file=random.choice(docs))
Example #28
Source File: utils.py From X-tra-Telegram with Apache License 2.0 | 4 votes |
def register(**args): """ Register a new event. """ args["func"] = lambda e: e.via_bot_id is None stack = inspect.stack() previous_stack_frame = stack[1] file_test = Path(previous_stack_frame.filename) file_test = file_test.stem.replace(".py", "") pattern = args.get('pattern', None) disable_edited = args.get('disable_edited', True) if pattern is not None and not pattern.startswith('(?i)'): args['pattern'] = '(?i)' + pattern if "disable_edited" in args: del args['disable_edited'] reg = re.compile('(.*)') if not pattern == None: try: cmd = re.search(reg, pattern) try: cmd = cmd.group(1).replace("$", "").replace("\\", "").replace("^", "") except: pass try: CMD_LIST[file_test].append(cmd) except: CMD_LIST.update({file_test: [cmd]}) except: pass def decorator(func): if not disable_edited: bot.add_event_handler(func, events.MessageEdited(**args)) bot.add_event_handler(func, events.NewMessage(**args)) try: LOAD_PLUG[file_test].append(func) except Exception as e: LOAD_PLUG.update({file_test: [func]}) return func return decorator
Example #29
Source File: utils.py From X-tra-Telegram with Apache License 2.0 | 4 votes |
def admin_cmd(pattern=None, **args): args["func"] = lambda e: e.via_bot_id is None stack = inspect.stack() previous_stack_frame = stack[1] file_test = Path(previous_stack_frame.filename) file_test = file_test.stem.replace(".py", "") allow_sudo = args.get("allow_sudo", False) # get the pattern from the decorator if pattern is not None: if pattern.startswith("\#"): # special fix for snip.py args["pattern"] = re.compile(pattern) else: args["pattern"] = re.compile("\." + pattern) cmd = "." + pattern try: CMD_LIST[file_test].append(cmd) except: CMD_LIST.update({file_test: [cmd]}) args["outgoing"] = True # should this command be available for other users? if allow_sudo: args["from_users"] = list(Var.SUDO_USERS) # Mutually exclusive with outgoing (can only set one of either). args["incoming"] = True del args["allow_sudo"] # error handling condition check elif "incoming" in args and not args["incoming"]: args["outgoing"] = True # add blacklist chats, UB should not respond in these chats allow_edited_updates = False if "allow_edited_updates" in args and args["allow_edited_updates"]: allow_edited_updates = args["allow_edited_updates"] del args["allow_edited_updates"] # check if the plugin should listen for outgoing 'messages' is_message_enabled = True return events.NewMessage(**args)
Example #30
Source File: antivirus2.py From X-tra-Telegram with Apache License 2.0 | 4 votes |
def _(event): if event.fwd_from: return if not event.reply_to_msg_id: await event.edit("```Reply to any user message.```") return reply_message = await event.get_reply_message() if not reply_message.media: await event.edit("```reply to a media message```") return chat = "@DrWebBot" sender = reply_message.sender if reply_message.sender.bot: await event.edit("```Reply to actual users message.```") return await event.edit(" `Sliding my tip, of fingers over it`") async with borg.conversation(chat) as conv: try: response = conv.wait_event(events.NewMessage(incoming=True,from_users=161163358)) await borg.forward_messages(chat, reply_message) response = await response except YouBlockedUserError: await event.reply("```Please unblock @sangmatainfo_bot and try again```") return if response.text.startswith("Forward"): await event.edit("```can you kindly disable your forward privacy settings for good?```") else: if response.text.startswith("Select"): await event.edit("`Please go to` @DrWebBot `and select your language.`") else: await event.edit(f"**Antivirus scan was completed. I got dem final results.**\n {response.message.message}")