如何在收到特定消息时停止Telethon对话 [英] How to stop telethon conversation on receiving a specific message
问题描述
我使用Telethon库制作了一个电报机器人,该库使用button.inline
和button.text
方法接收用户的响应.但是我想在用户输入特定消息(例如再见)后立即停止对话.
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)] ] )
...
...
每当用户发送"Hi"时,机器人就会开始使用按钮进行查询.
Whenever the user sends 'Hi', the bot starts querying using buttons.
在 telethon文档中,cancel()
和cancel_all()
方法.但是我该如何实现它们,以便在收到消息再见时结束对话?
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 ?
推荐答案
根据文档,conv.cancel_all()
取消该聊天的所有对话.我注意到我无法打开多个对话,因为设置了默认值exclusive=True
.
所以,我所做的是:
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()
当有新消息显示为"/cancel"时,它将打开一个对话,并致电.cancel_all()
取消旧对话.
When there's a new message with text "/cancel", it will open a conversation, and call .cancel_all()
to cancel the old conversation.
这篇关于如何在收到特定消息时停止Telethon对话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!