如何解决在用户对电报机器人进行有效答复之前,如何重复执行功能和处理程序?
我刚开始学习使用telegram-bot-api-python模块构建Telegram bot。我做了三个功能,其中一个是/start
命令功能,可以开始通话,该功能要求用户提供电话号码,并将其发送给其他名为reply_with_number
的处理程序或函数,在其中使用{{1}可以验证用户的回复} if
语句,如果用户答复有效,则将其发送到另一个称为else
的处理程序或函数,这是最后一个处理程序或函数,他将通过链接答复我。一切都很好,但是当用户输入诸如“ ask_link
”之类的字符串而不是电话号码时,功能thisstring
应该继续运行或继续询问有效的电话号码,直到他键入有效的电话号码为止。但是我只是离开了reply_with_number
而运行了下一个reply_with_number
处理程序,而不必等待回复。如何解决这个问题?
我的代码:
ask_link
解决方法
在这种情况下,您应该使用ConversationHandler
,并返回正确的消息供用户重试,并返回正确的消息,以便漫游器知道用户仍在对话处理程序的同一步骤中,例如:
from telegram.ext import CommandHandler,MessageHandler,Filters,ConversationHandler
FIRST_STEP,SECOND_STEP = range(2)
conversation_handler = ConversationHandler(
entry_points=[CommandHandler('start',start)],states={
FIRST_STEP: [MessageHandler(Filters.text & ~Filters.command,first_step)],SECOND_STEP: [MessageHandler(Filters.text & ~Filters.command,second_step)],},fallbacks=[CommandHandler('cancel',cancel)]
)
def start(bot,update):
bot.send_message(
chat_id=update.message.chat_id,text='2 + 2 = ?',parse_mode='markdown')
return FIRST_STEP
def cancel(bot,text='2 + 2 = ?')
return ConversationHandler.END
def first_step(bot,update):
if update.message.text != '4':
bot.send_message(
chat_id=update.message.chat_id,text='Sorry try again to enter a valid input.')
bot.send_message(
chat_id=update.message.chat_id,text='2 + 2 = ?')
return FIRST_STEP
else:
bot.send_message(
chat_id=update.message.chat_id,text='The answer is right,you are in the next step')
return SECOND_STEP
def second_step(bot,text='Correct answer',parse_mode='markdown')
return ConversationHandler.END
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。