Telebot的@bot.callback_query_handler回调处理器无响应问题求助
Telebot的@bot.callback_query_handler回调处理器无响应问题求助
我遇到了一个麻烦的问题,想请大家帮忙排查下:我的Telegram机器人能正常发送内联键盘,但点击按钮后完全没有回调响应——连日志都没任何输出。不过如果给InlineKeyboardButton传入URL的话,功能是正常的。
以下是我的代码片段:
@bot.message_handler() def add_city(message): if user_status[message.chat.id] == Statuses.AddCity: logger.info("User adding the city") request = { "name": message.text } response = requests.post(f'{api_url}/api/users/{message.chat.id}/add-city', json=request, headers=headers) if response.status_code == 200: logger.info("User got city. Waiting for confirmation") data = response.json() user_status[message.chat.id] = Statuses.ConfirmCity markup = InlineKeyboardMarkup() markup.add(InlineKeyboardButton("Confirm", callback_data="Confirm")) markup.add(InlineKeyboardButton("Deny", callback_data="Deny")) bot.send_message(message.chat.id, f'{data.get("name")}') bot.send_message(message.chat.id, f'Підтверди що це саме те місто, яке ти хотів додати:', reply_markup=markup) else: logger.info("Bad Request") bot.send_message(message.chat.id, f'Виникла помилка при додаванні міста :(') @bot.callback_query_handler(func=lambda call: call.data in ("Confirm", "Deny")) def handle_city_confirmation(call): logger.info(call) if user_status[call.message.chat.id] == Statuses.ConfirmCity: if call.data.split(' ')[0] == "Confirm": bot.send_message(call.message.chat.id, 'success') else: bot.send_message(call.message.chat.id, "deny") else: bot.send_message(call.message.chat.id, "fail")
可能的排查方向和解决方案:
检查Polling更新监听配置:如果你用
bot.polling()启动机器人,默认可能没监听callback_query类型的更新。试试把启动代码改成这样:bot.polling(none_stop=True, allowed_updates=['message', 'callback_query'])明确指定要监听的更新类型,确保回调请求能被机器人正常接收。
确认Handler的加载顺序:保证
@bot.callback_query_handler是在bot.polling()之前定义的,如果handler注册在polling启动之后,会导致无法生效。测试极简版回调处理器:先写一个无过滤条件的回调处理器测试,验证基础功能是否正常:
@bot.callback_query_handler(func=lambda call: True) def test_callback(call): logger.info("回调已触发!") bot.answer_callback_query(call.id, text="测试响应")如果这个都没触发,说明是机器人的更新监听逻辑有问题;如果能触发,再回到原handler排查过滤条件的问题。
排查全局拦截类Handler:检查是否有类似
@bot.message_handler(func=lambda message: True)的全局消息处理器,虽然消息和回调是不同类型的更新,但某些极端情况下可能影响回调的路由,暂时注释掉这类全局handler测试看看。
备注:内容来源于stack exchange,提问作者AndyFlight
相关产品推荐
相关产品推荐

