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

使用node-telegram-bot-api时,点击内联按钮无callback_query更新

解决node-telegram-bot-api无法接收callback_query的问题

核心问题分析

你的代码存在两个关键问题:

  • WebHook模式未处理callback_query类型更新:handleUpdate函数仅判断req.body.message,但用户点击内联键盘时,Telegram推送的是callback_query类型更新,既不会触发现有逻辑,也未传递给bot实例处理。
  • 内联键盘构造错误:sendMessage的reply_markup被手动JSON序列化,而node-telegram-bot-api支持直接传入对象,序列化后的字符串会导致Telegram无法识别回调配置,进而无法触发事件。

修复方案

1. 修正内联键盘构造代码

修改sendTypesKeyboard函数,移除JSON.stringify,同时确保callback_data为字符串类型(Telegram强制要求):

const sendTypesKeyboard = async (chatId) => {
    const types = await typeDbHandler.getAll();
    const options = {
        reply_markup: {
            inline_keyboard: types.map((type) => 
                [{"text": type.name, "callback_data": type.id.toString()}]
            )
        }
    }
    bot.sendMessage(chatId, "Choose the type", options);
}

2. WebHook模式下处理全部更新类型

更新BotController的handleUpdate方法,将所有更新传递给bot实例处理,同时保留原有消息逻辑:

class BotController {
    async handleUpdate(req, res, next){
        console.log(req.body);

        // 把更新传递给bot实例,触发对应的事件监听器
        bot.processUpdate(req.body);

        if (req.body.message?.text === "/getTypes"){
            await sendTypesKeyboard(req.body.message.chat.id);
        }
        return res.json({message: "update handled"});
    }    
}

3. Polling模式验证

Polling模式下,确保bot实例的事件监听器正常挂载,同时内联键盘的构造已按上述方式修正,此时点击内联键盘应能触发callback_query事件,控制台会打印对应query数据。

额外检查项

  • 确认bot token有效且无权限限制
  • 检查BotFather配置,确保bot允许接收内联键盘回调
  • WebHook模式下,保证服务器可被Telegram访问,且使用有效SSL证书(Telegram强制要求WebHook使用HTTPS)

内容的提问来源于stack exchange,提问作者user25496422

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:27:06