在用户对电报机器人进行有效答复之前,如何重复执行功能和处理程序?

问题描述

我刚开始学习使用telegram-bot-api-python模块构建Telegram bot。我做了三个功能,其中一个是/start命令功能,可以开始通话,该功能要求用户提供电话号码,并将其发送给其他名为reply_with_number的处理程序或函数,在其中使用{{1}可以验证用户的回复} if语句,如果用户答复有效,则将其发送到另一个称为else的处理程序或函数,这是最后一个处理程序或函数,他将通过链接答复我。一切都很好,但是当用户输入诸如“ ask_link”之类的字符串而不是电话号码时,功能thisstring应该继续运行或继续询问有效的电话号码,直到他键入有效的电话号码为止。但是我只是离开了reply_with_number而运行了下一个reply_with_number处理程序,而不必等待回复。如何解决这个问题? 我的代码:

ask_link

问题的屏幕截图:

enter image description here

解决方法

在这种情况下,您应该使用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

参考文档: https://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.conversationhandler.html?highlight=ConversationHandler

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...