You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:03:02