PyTelegramBotApi中@callback_query_handler无法触发回调求助
问题
我正在使用PyTelegramBotApi开发首个Telegram机器人,但遇到异常问题:点击任何内联按钮后均无回调响应,无任何反应。按文档要求使用了callback_query_handler装饰器,但始终无法触发回调,process_callback_query函数从未被调用。相关代码如下:
import telebot from loguru import logger from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup from config_data.config import BOT_TOKEN from response_templates.response_templates import BOT_RESPONSE_TEMPLATES bot = telebot.TeleBot(BOT_TOKEN, parse_mode=None) website_choice_keyboard = InlineKeyboardMarkup(row_width=2) website_choice_buttons = [InlineKeyboardButton("Yes", callback_data="cb_yes"), InlineKeyboardButton("No", callback_data="cb_no")] website_choice_keyboard.add(*website_choice_buttons) logger.add('logs/main_log.log', format="{time:MMMM D, YYYY > HH:mm:ss} | {level} | {message} | {extra}", level="DEBUG", rotation="60 MB", retention="7 days") @bot.message_handler(commands=['help',]) def process_help_command(message): bot.send_message(message.chat.id, BOT_RESPONSE_TEMPLATES['/help'], reply_markup=None) @bot.message_handler(commands=['start',]) def process_start_command(message): bot.send_message(message.chat.id, BOT_RESPONSE_TEMPLATES['/start'], reply_markup=website_choice_keyboard) @bot.callback_query_handler(func=lambda call: call.data) def process_callback_query(callback): print("BUTTON PRESSED") if callback.message: bot.send_message(callback.message.chat_id, f"YOU PRESSED A BUTTON") bot.infinity_polling()
解决方案
- 必须确认回调请求
Telegram要求机器人收到回调查询后,必须调用bot.answer_callback_query(callback.id)来确认请求,否则Telegram会重复发送请求,甚至阻塞后续回调。补上这行代码即可:
@bot.callback_query_handler(func=lambda call: call.data) def process_callback_query(callback): print("BUTTON PRESSED") # 添加这行确认回调 bot.answer_callback_query(callback.id) if callback.message: bot.send_message(callback.message.chat_id, f"YOU PRESSED A BUTTON")
- 调整回调处理器的匹配逻辑
你的func=lambda call: call.data在极端情况下可能不生效,比如call.data为空时会返回False。可以改成匹配所有回调,或者明确指定目标回调数据:
# 匹配所有回调查询 @bot.callback_query_handler(func=lambda call: True) # 或者只匹配你的按钮回调数据 @bot.callback_query_handler(func=lambda call: call.data in ["cb_yes", "cb_no"])
- 检查轮询更新权限
确保infinity_polling没有禁用回调更新,显式指定允许的更新类型更稳妥:
bot.infinity_polling(allowed_updates=['message', 'callback_query'])
- 添加日志排查
利用loguru在回调函数里加日志输出,确认是否真的未触发:
@bot.callback_query_handler(func=lambda call: call.data) def process_callback_query(callback): logger.debug("回调触发,数据:{}", callback.data) print("BUTTON PRESSED") bot.answer_callback_query(callback.id) if callback.message: bot.send_message(callback.message.chat_id, f"YOU PRESSED A BUTTON")
内容的提问来源于stack exchange,提问作者Jafes
相关产品推荐
相关产品推荐

