多个回调查询处理程序?

问题描述 投票:8回答:2

使用python-telegram-bot包装器可以使用多个回调查询处理程序吗?

我想拥有多个独特的处理程序,但据我所知,只能有一个。这意味着我必须根据我在启动消息文本上显示的内联键盘。

有什么我想念的吗?

python-telegram-bot
2个回答
8
投票

您可以使用ConversationHandler包装器。检查代码如下:

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

TELEGRAM_HTTP_API_TOKEN = 'PASTE_TELEGRAM_HTTP_API_TOKEN'

FIRST, SECOND = range(2)

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
    keyboard = [
        [InlineKeyboardButton(u"Next", callback_data=str(SECOND))]
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    bot.edit_message_text(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        text=u"First CallbackQueryHandler, Press next"
    )

    reply_markup = InlineKeyboardMarkup(keyboard)

    bot.edit_message_reply_markup(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        reply_markup=reply_markup
    )
    return SECOND

def second(bot, update):
    query = update.callback_query
    bot.edit_message_text(
        chat_id=query.message.chat_id,
        message_id=query.message.message_id,
        text=u"Second CallbackQueryHandler"
    )
    return

updater = Updater(TELEGRAM_HTTP_API_TOKEN)

conv_handler = ConversationHandler(
    entry_points=[CommandHandler('start', start)],
    states={
        FIRST: [CallbackQueryHandler(first)],
        SECOND: [CallbackQueryHandler(second)]
    },
    fallbacks=[CommandHandler('start', start)]
)

updater.dispatcher.add_handler(conv_handler)

updater.start_polling()

updater.idle()

0
投票

您可以使用CallbackQueryHandler pattern参数。用于测试telegram.CallbackQuery.data的正则表达式模式。

def motd(bot, update):
    motd_keyboard = [[InlineKeyboardButton('I agree',
        callback_data='motd_callback_button')]]
    motd_markup = InlineKeyboardMarkup(motd_keyboard)
    update.message.reply_text('Message of the day',
        reply_markup=motd_markup)

def motd_callback_button(bot, update):
    pass

def main():
    dp = DjangoTelegramBot.dispatcher
    dp.add_handler(CallbackQueryHandler(motd_callback_button, 
        pattern='^motd_callback_button$'))
© www.soinside.com 2019 - 2024. All rights reserved.