node-telegram-bot-api中callback_query事件无法触发求助
Telegram机器人无法捕获callback_query事件的问题
问题描述
用NodeJS开发Telegram机器人,依赖node-telegram-bot-api v0.66.0版本,点击内置键盘(inline keyboard)按钮后,机器人完全捕获不到callback_query回调事件。
模块版本
"node-telegram-bot-api": "^0.66.0"
完整代码示例
import TelegramBot from "node-telegram-bot-api"; import { config } from "dotenv"; config() const API_KEY_BOT = process.env.TOKEN; const bot = new TelegramBot(API_KEY_BOT, { polling: true }) const gameOption = { reply_markup: { inline_keyboard: [ [{text: '7', callback_data:'7'},{text: '8', callback_data:'8'},{text: '9', callback_data:'9'}], [{text: '4', callback_data:'4'},{text: '5', callback_data:'5'},{text: '6', callback_data:'6'}], [{text: '1', callback_data:'1'},{text: '2', callback_data:'2'},{text: '3', callback_data:'3'}], [{text: '0', callback_data:'0'}] ] } } function start() { const chats ={} bot.setMyCommands([ { command: '/start', description: 'Running a bot' }, { command: '/game', description: 'Game' } ]) bot.on('message', async msg => { const text = msg.text; const chatId = msg.chat.id; if (text === '/start') { return await bot.sendMessage(chatId, `You wrote to me ${text}`) } if (text === '/game') { await bot.sendMessage(chatId, 'Now I will guess a number from 0-9') const randomNumber = Math.floor(Math.random()*10); chats[chatId] = randomNumber; console.log(gameOption); return await bot.sendMessage(chatId,"Guess", gameOption) } return await bot.sendMessage(chatId, 'I dont understand you') }) bot.on('callback_query', function onCallbackQuery(callbackQuery) { console.log(callbackQuery); }); } start()
解决方法
1. 必须确认回调请求
Telegram要求机器人收到callback_query后,必须调用answerCallbackQuery接口进行确认,否则后续回调可能无法触发,甚至会被平台限制请求。修改回调处理函数:
bot.on('callback_query', async (callbackQuery) => { const { id } = callbackQuery; // 调用该方法完成回调确认 await bot.answerCallbackQuery(id); console.log(callbackQuery); });
2. 明确指定监听的更新类型
在初始化bot时,显式配置allowed_updates参数,确保机器人只接收需要的更新类型,避免遗漏callback_query:
const bot = new TelegramBot(API_KEY_BOT, { polling: { allowed_updates: ['message', 'callback_query'] } });
3. 检查作用域问题
你代码里的chats对象定义在start函数内部,如果后续需要在回调里访问这个对象,会出现作用域问题。建议把它移到全局作用域:
const chats = {}; // 移到全局 function start() { // ... 原有代码 }
4. 更新依赖版本
尝试把node-telegram-bot-api更新到最新稳定版,修复旧版本可能存在的bug:
npm update node-telegram-bot-api
内容的提问来源于stack exchange,提问作者Рафаэль Шарафутдинов
相关产品推荐
相关产品推荐

