使用JavaScript开发Telegram Bot:reply_markup键盘按钮交互问题
实现Telegram普通Keyboard按钮的交互逻辑
普通Keyboard和Inline Keyboard的核心区别是:点击普通按钮后,按钮上的文本会作为普通消息发送给机器人,所以不需要监听callback_query,直接在已有的text事件处理器里处理即可。
具体实现步骤:
- 在
/start命令中替换为你定义的testButton(普通键盘) - 在
text事件的判断逻辑里,新增对按钮文本的处理分支
修改后的完整代码:
const mainMenuButton = { reply_markup: JSON.stringify({ inline_keyboard: [ [{text: 'Bot information', callback_data: 'info'}], [{text: 'Exchange Rates', callback_data: 'currencies'}] ] }) } // 你的普通键盘定义 const testButton = { reply_markup:{ keyboard: [ ['Bot information'], ['Exchange Rates'] ], resize_keyboard: true } } let startBot = () => { bot.setMyCommands([ { command: '/start', description: 'Initial greeting' } ]); bot.on('text', msg => { let text = msg.text; let chatId = msg.chat.id; if (text === '/start') { // 启动时发送普通键盘 return bot.sendMessage(chatId, `Hello, ${msg.from.first_name}, how can I help you?`, testButton); } // 处理普通键盘的按钮点击(本质是接收文本消息) else if (text === 'Bot information') { return bot.sendMessage(chatId, "This is my first project", testButton); } else if (text === 'Exchange Rates') { return bot.sendMessage(chatId, "Here are the latest exchange rates...", testButton); } }); bot.on('callback_query', async (msg) => { console.log(msg); let data = msg.data; let chatId = msg.message.chat.id; if (data === 'info') { return bot.sendMessage(chatId, "This is my first project", mainMenuButton); } }) }
额外提示:
- 如果需要在某些场景下隐藏普通键盘,可以使用
reply_markup: { remove_keyboard: true }作为参数发送消息 - 普通键盘的按钮文本建议统一管理(比如用常量),避免后期修改时遗漏判断分支
内容的提问来源于stack exchange,提问作者Jhony
相关产品推荐
相关产品推荐

