如何重复函数和处理程序,直到用户对电报机器人给出有效回复?

How to repeat a function and handler untill the user gives a valid reply to telegram bot?

我刚刚开始学习使用 telegram-bot-api-python 模块构建电报机器人。我创建了三个函数,一个 /start 命令函数来开始对话,这个函数要求用户 phone 号码并将其发送到其他处理程序或名为 reply_with_number 的函数,用户的回复将使用if else 语句,如果用户回复有效,那么他将被发送到另一个名为 ask_link 的处理程序或函数,这是最后一个,他将回复我 link.一切都很好,但是当用户输入一些字符串,如“thisstring”而不是 phone 数字时,函数 reply_with_number 应该保持 运行 或继续要求有效 phone 号码,直到他键入有效的号码。但是我的只是离开 reply_with_number 和 运行 下一个 ask_link 处理程序而没有等待回复。如何解决这个问题? 我的代码:

import time
from telegram import MessageEntity,Bot
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler
from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove

updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher

def start(update, context):
    username = update.message.from_user.first_name
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text=f"Hello {username}, Welcome to my bot!")
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text='May i know your phone no ?')

def reply_with_number(update, context):
        if update.message.text and len(update.message.text) <= 13:
            try:
                if update.message.text[0:3] == '+91':
                    phone_number = int(update.message.text[3:])
                elif update.message.text[0:2] == '91':
                    phone_number = int(update.message.text[2:])
                elif update.message.text[0] == '0':
                    phone_number = int(update.message.text[1:])
                else:
                    phone_number = int(update.message.text)
                    context.bot.send_message(chat_id=update.effective_chat.id,
                                             text='Looks good!',
                                             reply_markup=reply_markup)
            except Exception as e:
                update.message.reply_text('Please enter phone number not strings!')

def ask_link(update, context):
    link = update.message.text
    neat_url = strip(link)
    if neat_url != None:
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text='Link looks good')
    elif neat_url == None:
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text='Its invalid!')


start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

reply_handler = MessageHandler(Filters.contact | Filters.text, reply_with_number)
dispatcher.add_handler(reply_handler)

ask_for_link = MessageHandler(Filters.text, ask_link)
dispatcher.add_handler(ask_for_link)

updater.start_polling()

问题截图:

对于这种情况,您应该使用 ConversationHandler,只是 return 用户重试的正确消息和正确的 return 以便机器人知道用户仍在会话处理程序上的相同步骤,示例:

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, update):
    bot.send_message(
        chat_id=update.message.chat_id, 
        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, update):
    bot.send_message(
        chat_id=update.message.chat_id, 
        text='Correct answer', 
        parse_mode='markdown')
    return ConversationHandler.END

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