首页 > 解决方案 > CallbackQueryHandler 或 ConversationHandler 用于从机器人类发送的消息

问题描述

使用python-telegram-bot,我有一个运行与其他示例非常相似的设置的机器人。另一方面,我有并行进程,允许我定期向与机器人交互的用户发送消息。并行进程使用以下方式与用户通信:

bot = Bot(token=TELEGRAM_TOKEN)
def get_button_options():
    keyboard = [[ InlineKeyboardButton("reply", callback_data='reply),]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    return reply_markup
bot.send_message(chat_id=self.telegram_id, text=text, reply_markup=get_button_options())

问题是,即使我能够向用户发送消息,上面的代码也不允许用户与机器人交互(我的意思是,一旦用户按下按钮,机器人就不会执行任何回调)。这是因为我在机器人中需要CallbackQueryHandlerConversationHandler 。

但是对于ConversationHandler我似乎没有找到任何合适的 entry_point,因为它是从并行进程发送的消息。另一方面,在主机器人中使用以下CallbackQueryHandler(取自示例)似乎没有任何效果:

def button(update: Update, _: CallbackContext) -> None:
    query = update.callback_query

    # CallbackQueries need to be answered, even if no notification to the user is needed
    # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
    query.answer()

    query.edit_message_text(text=f"Selected option: {query.data}")

在主函数中,我添加了处理程序使用updater.dispatcher.add_handler(CallbackQueryHandler(button))

关于如何解决这个问题的任何想法?

标签: telegram-botpython-telegram-bot

解决方案


As said by @CallMeStag, the solution is the following:

ConversationHandler(
    entry_points=[CallbackQueryHandler(button)])

the correct entry point is a CallbackQueryHandler, so then it captures the selected button


推荐阅读