在没有命令的情况下触发 ConversationHandler?

时间:2021-06-30 17:55:31

标签: python telegram-bot python-telegram-bot

我已经被我未来的电报机器人的这个功能困住了 3 个月:(

我想针对我的情况使用 ConversationHandler。该代码当前向用户发送一条消息以解决数学问题。然后用户应该输入结果。一切正常!

只有当用户在 Telegram Bot 中直接使用 /start 命令运行 ConversationHandler 时才会触发它。

现在我确实添加了一个 InlineKeyboardButton。当用户点击按钮时,InlineKeyboardButton 会向 button() 函数提供回调数据。这里也一切正常。现在我的问题:

有没有办法直接从 ConversationHandler 函数运行 button()? (查看代码中的注释,看看它应该在哪里运行)

没有按钮的代码:

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

按钮代码片段:

def button(update, context):
    """
    callback method handling button press
    """
    bot: Bot = context.bot
    # getting the callback query
   
    query: CallbackQuery = update.callback_query

    # CallbackQueries need to be answered, even if no notification to the user is needed
   
    query.answer()
    
    #Get choosed button
    choosed_button = query.data
    if(choosed_button == 'math_btn'):

        query.edit_message_text(text='✅You selected the Math Button✅')
        # HERE the ConversationHandler should get triggered!
        #
        #... More code is under here. But not relevant!

顺便说一句:我使用 python-telegram-bot 库!

ConversationHandler 的参考文档

0 个答案:

没有答案