How to use the telethon.events.NewMessage function in Telethon

To help you get started, we’ve selected a few Telethon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github blueset / efb-telegram-master / tests / integration / helper / helper.py View on Github external
# Telethon client to use
        self.client: TelegramClient = TelegramClient(
            StringSession(session), api_id, api_hash, proxy=proxy, loop=loop,
            sequential_updates=True
        )

        # Queue for incoming messages
        self.queue: "asyncio.queues.Queue[EventCommon]" = asyncio.queues.Queue()

        # Collect mappings from message ID to its chat (as Telegram API is not sending them)
        self.message_chat_map: Dict[int, TypeInputPeer] = dict()

        self.chats = list(map(abs, chats))
        self.client.parse_mode = "html"
        self.client.add_event_handler(self.new_message_handler,
                                      NewMessage(chats=self.chats, incoming=True, from_users=[bot_id]))
        # self.client.add_event_handler(self.new_message_handler,
        #                               NewMessage(incoming=True))
        self.client.add_event_handler(self.deleted_message_handler, MessageDeleted())
        self.client.add_event_handler(self.update_handler, UserUpdate(chats=self.chats))
        self.client.add_event_handler(self.update_handler, MessageEdited(chats=self.chats))
        self.client.add_event_handler(self.update_handler, ChatAction(chats=self.chats))

        self.logger = logging.getLogger(__name__)
github LonamiWebs / Telethon / telethon_examples / assistant.py View on Github external
@bot.on(events.NewMessage(pattern='#search (.+)', forwards=False))
async def handler(event):
    """#search query: Searches for "query" in the method reference."""
    query = urllib.parse.quote(event.pattern_match.group(1))
    await asyncio.wait([
        event.delete(),
        event.respond(SEARCH.format(query), reply_to=event.reply_to_msg_id)
    ])
github Dark-Princ3 / X-tra-Telegram / userbot / utils.py View on Github external
def __init__(self, func=None, **args):
        self.Var = Var
        bot.add_event_handler(func, events.NewMessage(**args))
github voidbar / forwardgram / forwardgram.py View on Github external
    @client.on(events.NewMessage(chats=input_channels_entities))
    async def handler(event):
        for output_channel in output_channel_entities:
            await client.forward_messages(output_channel, event.message)
github Dark-Princ3 / X-tra-Telegram / userbot / plugins / shout.py View on Github external
@borg.on(events.NewMessage(pattern=r"\.shout", outgoing=True))
async def shout(args):
    if args.fwd_from:
        return
    else:
        msg = "```"
        messagestr = args.text
        messagestr = messagestr[7:]
        text = " ".join(messagestr)
        result = []
        result.append(' '.join([s for s in text]))
        for pos, symbol in enumerate(text[1:]):
            result.append(symbol + ' ' + '  ' * pos + symbol)
        result = list("\n".join(result))
        result[0] = text[0]
        result = "".join(result)
        msg = "\n" + result
github vtr0n / TelegramTUI / telegramtui / src / telegramApi.py View on Github external
        @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:
github kdrag0n / pyrobud / pyrobud / bot.py View on Github external
self.uid = user.id

        # Set Sentry username if enabled
        if self.config["bot"]["report_username"]:
            with sentry_sdk.configure_scope() as scope:
                scope.set_user({"username": self.user.username})

        # Record start time and dispatch start event
        self.start_time_us = util.time.usec()
        await self.dispatch_event("start", self.start_time_us)

        # Register handlers
        self.client.add_event_handler(self.on_message, tg.events.NewMessage())
        self.client.add_event_handler(self.on_message_edit, tg.events.MessageEdited())
        self.client.add_event_handler(
            self.on_command, tg.events.NewMessage(outgoing=True, func=self.command_predicate),
        )
        self.client.add_event_handler(self.on_chat_action, tg.events.ChatAction())

        self.log.info("Bot is ready")

        # Catch up on missed events
        self.log.info("Catching up on missed events")
        await self.client.catch_up()
        self.log.info("Finished catching up")
github Dark-Princ3 / X-tra-Telegram / userbot / utils.py View on Github external
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)
github Dark-Princ3 / X-tra-Telegram / userbot / plugins / locks.py View on Github external
@borg.on(events.NewMessage())  # pylint:disable=E0602
async def check_incoming_messages(event):
    # TODO: exempt admins from locks
    peer_id = event.chat_id
    if is_locked(peer_id, "commands"):
        entities = event.message.entities
        is_command = False
        if entities:
            for entity in entities:
                if isinstance(entity, types.MessageEntityBotCommand):
                    is_command = True
        if is_command:
            try:
                await event.delete()
            except Exception as e:
                await event.reply(
                    "I don't seem to have ADMIN permission here. \n`{}`".format(str(e))