当前位置: 首页>>代码示例>>Python>>正文


Python events.NewMessage方法代码示例

本文整理汇总了Python中telethon.events.NewMessage方法的典型用法代码示例。如果您正苦于以下问题:Python events.NewMessage方法的具体用法?Python events.NewMessage怎么用?Python events.NewMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在telethon.events的用法示例。


在下文中一共展示了events.NewMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: list_event_handlers

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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] 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:22,代码来源:updates.py

示例2: can_react

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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. 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:20,代码来源:replier.py

示例3: create_token_file

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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 
开发者ID:mkaraniya,项目名称:BotHub,代码行数:23,代码来源:gdrivenew.py

示例4: translator

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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() 
开发者ID:SlavikMIPT,项目名称:opentfd,代码行数:25,代码来源:opentfd.py

示例5: on

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:28,代码来源:updates.py

示例6: remove_event_handler

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:40,代码来源:updates.py

示例7: start_handler

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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'
        )
    ) 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:10,代码来源:payment.py

示例8: handler

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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() 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:14,代码来源:assistant.py

示例9: message_handler

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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
                )) 
开发者ID:LonamiWebs,项目名称:Telethon,代码行数:32,代码来源:interactive_telegram_client.py

示例10: start

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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')) 
开发者ID:XiaomiFirmwareUpdater,项目名称:xiaomi_uranus_chatbot,代码行数:43,代码来源:main.py

示例11: _

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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) 
开发者ID:mkaraniya,项目名称:BotHub,代码行数:31,代码来源:Qoutly.py

示例12: choser

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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)) 
开发者ID:mkaraniya,项目名称:BotHub,代码行数:17,代码来源:randomsticker.py

示例13: _

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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}") 
开发者ID:mkaraniya,项目名称:BotHub,代码行数:30,代码来源:sangmata.py

示例14: _

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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) 
开发者ID:mkaraniya,项目名称:BotHub,代码行数:30,代码来源:nice.py

示例15: _

# 需要导入模块: from telethon import events [as 别名]
# 或者: from telethon.events import NewMessage [as 别名]
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}") 
开发者ID:mkaraniya,项目名称:BotHub,代码行数:33,代码来源:antivirus.py


注:本文中的telethon.events.NewMessage方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。