How to stop telethon conversation on receiving a specific message

旧巷老猫 提交于 2020-07-23 09:59:10

问题


I have made a telegram bot using telethon library which takes reponses from user using button.inline and button.text methods. But I want to stop the conversation as soon as a specific message(like bye) is entered by the user.

@bot.on(events.NewMessage(incoming=True, pattern='Hi'))
async def main(event):
    global SENDER
    MSG = event.raw_text
    SENDER=event.chat_id

    async with bot.conversation(SENDER) as conv:
        await conv.send_message('choose', buttons=[[Button.inline('Yes'), Button.inline('No')] ])

        await conv.send_message('<b> Want More ? </b>', parse_mode='html', buttons=[ [Button.text('Yes', resize=True,single_use=True), Button.text('No', resize=True,single_use=True)], [Button.text('More', resize=True,single_use=True)] ] )
       ...
       ...

Whenever the user sends 'Hi', the bot starts querying using buttons.

In the telethon docs , cancel() and cancel_all() methods are provided. But how can I implement them such that on getting message bye, it ends the conversation ?


回答1:


According to the docs, conv.cancel_all() cancels all conversations of that chat. I noticed I wasn't able to open more than one conversation, because default value exclusive=True was set.
So, what I did was:

@client.on(events.NewMessage(func=lambda e: e.is_private))
async def handler(event):
    try:
        rawmsg = event.message.message
        if rawmsg == "/cancel":
            # set exclusive=False so we can still create a conversation, even when there's an existing (exclusive) one.
            async with client.conversation(await event.get_chat(), exclusive=False) as conv:
                await conv.cancel_all()
                await event.respond("Operation is cancelled.")
                return


        async with client.conversation(await event.get_chat(), exclusive=True) as conv:
            await conv.send_message("Hey, I'll send you back whatever you write! To cancel, do /cancel")
            while True:
                resp = (await conv.get_response()).raw_text
                await conv.send_message(resp)

#   except telethon.errors.common.AlreadyInConversationError:
#       pass
    except:
        traceback.print_exc()

When there's a new message with text "/cancel", it will open a conversation, and call .cancel_all() to cancel the old conversation.



来源:https://stackoverflow.com/questions/61302289/how-to-stop-telethon-conversation-on-receiving-a-specific-message

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!