【问题标题】:How to handle callbackquery in python telegram bot如何在python电报机器人中处理回调查询
【发布时间】:2018-02-21 10:07:06
【问题描述】:

在我的代码中,我遇到了回调查询处理程序的问题,当我点击 /start 命令时,会出现“下一步”按钮,当我点击该按钮时,它会给我回复“hi”,直到这里输出是正确的。然后当我点击另一个命令“/help”然后出现“help”按钮时,当我点击那个帮助按钮然后它给我之前的回复是“hi”,其中输出应该是“help

 from telegram import InlineKeyboardButton, InlineKeyboardMarkup
 from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, ConversationHandler

 TELEGRAM_HTTP_API_TOKEN = 'token'

 FIRST, SECOND, HELP = range(3)

 def start(bot, update):
        keyboard = [
            [InlineKeyboardButton(u"Next", callback_data=str(FIRST))]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        update.message.reply_text(
            u"Start handler, Press next",
            reply_markup=reply_markup
        )
        return FIRST

 def first(bot, update):
        query = update.callback_query
        #reply_markup = InlineKeyboardMarkup(keyboard)
        bot.send_message(chat_id=query.message.chat_id,
                         text='hi')

 def help(bot,update):
        keyboard = [
            [InlineKeyboardButton(u"HELP", callback_data=str(HELP))]
        ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        update.message.reply_text(
            u"Help handler, Press button",
            reply_markup=reply_markup
        )

        return HELP

 def myhelp(bot,update):
        query = update.callback_query
        bot.send_message(chat_id=query.message.chat_id,
                         text='help')

 updater = Updater(TELEGRAM_HTTP_API_TOKEN)

 conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],
        states={
            FIRST: [CallbackQueryHandler(first)]
        },
        fallbacks=[CommandHandler('start', start)]
    )
 conv_handler1=ConversationHandler(
        entry_points=[CommandHandler('help',help)],
        states={
            HELP: [CallbackQueryHandler(myhelp)]
        },
        fallbacks=[CommandHandler('help',help)]
    )

 updater.dispatcher.add_handler(conv_handler)
 updater.dispatcher.add_handler(conv_handler1)

 updater.start_polling()

 updater.idle()

【问题讨论】:

    标签: python-3.x telegram-bot python-telegram-bot


    【解决方案1】:

    您是第一个会话处理程序仍处于状态 FIRST 因而仍在等待回调查询。 因为它是添加的第一个处理程序并且它们在同一个组中,所以第一个会响应,而第二个不会。 您可以查看CallbackQueryHandlerpattern 参数来解决您的问题。

    【讨论】:

    • 哪种类型的 pattern 参数将解决我的问题 callbackqueryhandler 任何参考链接都将有助于解决这个问题
    【解决方案2】:

    使用return ConversationHandler.END 结束对话似乎也可以,因为它会结束第一个对话。 请参考此处的示例:https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/conversationbot.py

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2023-01-30
      • 2020-10-28
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 2017-01-08
      相关资源
      最近更新 更多