CallbackQueryHandler 未在 python-telegram-bot 中调用

问题描述 投票:0回答:0

我在使用 python-telegram-bot 制作电报机器人时正在使用 InlineKeyboard。 问题是查询处理函数 button() 在单击内联键盘中的任何按钮时都没有被调用。

这是代码

from telegram import *
from telegram.ext import *

print('bot executed')
token = <BOT_TOKEN>


async def send_message_in_channel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    global new_data
    await context.bot.send_message(chat_id=<CHANNEL_USERNAME>, text="new_data")


async def message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await context.bot.delete_message(update.effective_chat.id, message_id=update.message.id)


async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    query = update.callback_query
    await query.answer()
    print('button reached')
    if query.data == 'True':
        print("choose yes")
        await send_message_in_channel(update, context)
    elif query.data == 'False':
        print("choose no")

async def option(new_data) -> None:
    bot = Bot(token=token)
    options = [
        [
            InlineKeyboardButton('Yes, Post It', callback_data="True"),
            InlineKeyboardButton('No, Don\'t Post', callback_data="False")
        ],
    ]

    reply_markup = InlineKeyboardMarkup(options)
    await bot.send_message(chat_id=<MY_OWN_CHAT_ID>, text=new_data, reply_markup=reply_markup, disable_web_page_preview=True)


if __name__ == '__main__':
    new_data = ''
    
    application = ApplicationBuilder().token(token).build()
    application.add_handler(CallbackQueryHandler(button))
    application.add_handler(MessageHandler(
        filters.TEXT & (~filters.COMMAND), message))
    application.run_polling()

从外部函数调用 option() 函数,文本作为参数“new_data”。

我在从机器人本身调用选项时没有遇到这个问题,比如使用 CommandHandler('start', option) 并将 new_data 替换为 'update, context'。但这不是我想要的。由于从外部调用 option() ,我没有任何上下文或更新对象。

我还尝试将 button() 的上下文从 ContextTypes.DEFAULT_TYPE 更改为 CallbackContext,但没有成功。

python telegram python-telegram-bot
© www.soinside.com 2019 - 2024. All rights reserved.