How to use the telethon.events 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 Nukesor / archivebot / archivebot / archivebot.py View on Github external
@archive.on(events.NewMessage(pattern='/accept'))
@session_wrapper()
async def accepted_media_types(event, session):
    """Set the allowed media types for this chat."""
    to_id, to_type = get_peer_information(event.message.to_id)
    subscriber = Subscriber.get_or_create(session, to_id, to_type, event.message)

    # Convert the incoming text into an boolean
    arguments = event.message.message.lower().split(' ')[1:]
    accepted_media = set()
    for argument in arguments:
        if argument in possible_media:
            accepted_media.add(argument)

    accepted_media = list(accepted_media)
    accepted_media.sort()
github LonamiWebs / Telethon / telethon_examples / gui.py View on Github external
# The chat where to send and show messages from
        tkinter.Label(self, text='Target chat:').grid(row=1, column=0)
        self.chat = tkinter.Entry(self)
        self.chat.grid(row=1, column=1, columnspan=2, sticky=tkinter.EW)
        self.columnconfigure(1, weight=1)
        self.chat.bind('', self.check_chat)
        self.chat.bind('', self.check_chat)
        self.chat.focus()
        self.chat_id = None

        # Message log (incoming and outgoing); we configure it as readonly
        self.log = tkinter.scrolledtext.ScrolledText(self)
        allow_copy(self.log)
        self.log.grid(row=2, column=0, columnspan=3, sticky=tkinter.NSEW)
        self.rowconfigure(2, weight=1)
        self.cl.add_event_handler(self.on_message, events.NewMessage)

        # Save shown message IDs to support replying with ".rN reply"
        # For instance to reply to the last message ".r1 this is a reply"
        # Deletion also works with ".dN".
        self.message_ids = []

        # Save the sent texts to allow editing with ".s text/replacement"
        # For instance to edit the last "hello" with "bye" ".s hello/bye"
        self.sent_text = collections.deque(maxlen=10)

        # Sending messages
        tkinter.Label(self, text='Message:').grid(row=3, column=0)
        self.message = tkinter.Entry(self)
        self.message.grid(row=3, column=1, sticky=tkinter.EW)
        self.message.bind('', self.send_message)
        tkinter.Button(self, text='Send',
github Dark-Princ3 / X-tra-Telegram / userbot / plugins / locks.py View on Github external
@borg.on(events.MessageEdited())  # pylint:disable=E0602
@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(
github LonamiWebs / Telethon / telethon / full_sync.py View on Github external
asyncio.set_event_loop(loop)
        loop.run_forever()

    __asyncthread = threading.Thread(
        target=start, name="__telethon_async_thread__", daemon=True
    )
    __asyncthread.start()
    __asyncthread.loop = loop
    __asyncthread.executor = executor

    TelegramClient.__init__ = functools.partialmethod(
        TelegramClient.__init__, loop=loop
    )

    event_cls = filter(None, (
        getattr(getattr(events, name), 'Event', None)
        for name in dir(events)
    ))
    _syncify(TelegramClient, Draft, Dialog, MessageButton, ChatGetter,
             SenderGetter, Forward, Message, InlineResult, Conversation,
             *event_cls,
             loop=loop, thread_ident=__asyncthread.ident)
    _syncify_wrap(TelegramClient, "start", loop, __asyncthread.ident)

    old_add_event_handler = TelegramClient.add_event_handler
    old_remove_event_handler = TelegramClient.remove_event_handler
    proxied_event_handlers = {}

    @functools.wraps(old_add_event_handler)
    def add_proxied_event_handler(self, callback, *args, **kwargs):
        async def _proxy(*pargs, **pkwargs):
            await loop.run_in_executor(
github Dark-Princ3 / X-tra-Telegram / userbot / utils.py View on Github external
def decorator(func):
            if allow_edited_updates:
                bot.add_event_handler(func, events.MessageEdited(**args))
            bot.add_event_handler(func, events.NewMessage(**args))
            try:
                LOAD_PLUG[file_test].append(func)
            except:
                LOAD_PLUG.update({file_test: [func]})
            return func
github LonamiWebs / Telethon / telethon_examples / replier.py View on Github external
@events.register(events.NewMessage)
async def handler(event):
    # There are better ways to do this, but this is simple.
    # If the message is not outgoing (i.e. someone else sent it)
    if not event.out:
        if 'emacs' in event.raw_text:
            if can_react(event.chat_id):
                await event.reply('> emacs\nneeds more vim')

        elif 'vim' in event.raw_text:
            if can_react(event.chat_id):
                await event.reply('> vim\nneeds more emacs')

        elif 'chrome' in event.raw_text:
            if can_react(event.chat_id):
                await event.reply('> chrome\nneeds more firefox')
github Dark-Princ3 / X-tra-Telegram / userbot / plugins / _inlinebot.py View on Github external
    @tgbot.on(events.callbackquery.CallbackQuery(  # pylint:disable=E0602
        data=re.compile(b"us_plugin_(.*)")
    ))
    async def on_plug_in_callback_query_handler(event):
        plugin_name = event.data_match.group(1).decode("UTF-8")
        help_string = ""
        try:
            for i in CMD_LIST[plugin_name]:
                help_string += i
                help_string += "\n"
        except:
            pass
        if help_string is "":
            reply_pop_up_alert = "{} is useless".format(plugin_name)
        else:
            reply_pop_up_alert = help_string
        reply_pop_up_alert += "\n Use .unload {} to remove this plugin\n\
github kandnub / TG-UserBot / userbot / utils / client.py View on Github external
def wrapper(func: callable) -> callable:
            events.register(NewMessage(**kwargs))(func)

            if edited:
                events.register(MessageEdited(**kwargs))(func)

            if self.register_commands and command:
                handlers = events._get_handlers(func)
                category = "misc"
                doc_args.setdefault('prefix', self.prefix or '.')
                if isinstance(command, tuple):
                    if len(command) == 2:
                        com, category = command
                    else:
                        raise ValueError
                else:
                    com = command
                help_doc = info or func.__doc__ or no_info
github pug-ma / PUGMA-bot / bot / plugins / default.py View on Github external
    @bot.on(events.NewMessage(pattern=r"(?i).*(babaca|babaquice|arch)"))
    @hidden
    async def arch(event):
        """
        Envia o sticker do babaca quando ocorre um match com o regex. É
        escondido da saída do '/help' através do decorator @hidden.
        """
        population = ["arch", "babaca", "babaquice", None]
        weights = [0.1, 0.15, 0.1, 0.65]

        result = choices(population, weights)[0]

        if result is not None:
            try:
                stickers = await bot(
                    GetStickerSetRequest(
                        stickerset=InputStickerSetID(
github LonamiWebs / Telethon / telethon_examples / assistant.py View on Github external
@bot.on(events.ChatAction)
async def handler(event):
    if event.user_joined:
        if event.chat_id in last_welcome:
            try:
                await last_welcome[event.chat_id].delete()
            except errors.MessageDeleteForbiddenError:
                # We believe this happens when trying to delete old messages
                pass

        last_welcome[event.chat_id] = await event.reply(WELCOME[event.chat_id])