开发Telegram Bot时Node.js出现重复回复问题求助
解决Telegram Bot重复发送回复的问题
嘿,我帮你找出机器人重复回复的核心原因啦!主要有两个问题在搞鬼:
问题1:正则表达式没有精确匹配
你现在用的/\Dancy/这类正则,会匹配任何包含"Dancy"的文本——包括机器人自己发送的带"Dancy"的键盘消息。比如当机器人发送"Let's choose a style..."这条带Dancy选项的消息时,你的监听器会误触发,导致额外的回复。
问题2:可能重复注册了监听器
如果这段注册bot.onText的代码被多次执行(比如放在某个会重复运行的函数、循环里,或者不小心复制了多份),同一个文本触发的监听器会被挂载多次,每次用户点击按钮就会执行多次sendMessage,自然就发两次回复了。
解决方案
1. 改用精确匹配的正则
给正则加上^(匹配文本开头)和$(匹配文本结尾),确保只匹配用户发送的完全一致的按钮文本,示例如下:
// 精确匹配"Link to Soundcloud" bot.onText(/^Link to Soundcloud$/, (msg) => { bot.sendMessage(msg.chat.id, `Alright, ${msg.from.first_name}. Let's choose a style and I'll guide You through the whole Soundcloud`, { "reply_markup": { "keyboard": [["Dancy", "Chill"], ["Sensual", "Jazz"], ["Back to choose link or file"]], "resize_keyboard": true } }); }); // 精确匹配"Dancy" bot.onText(/^Dancy$/, (msg) => { bot.sendMessage(msg.chat.id, `Dancy link is here, ${msg.from.first_name}. Enjoy! ${dancy_collection[rand_dancy_collection]}`, { "reply_markup": { "keyboard": [["More dancy"], ["Back to choose style"]], "resize_keyboard": true } }); });
把所有bot.onText的正则都改成这种精确匹配的形式,就能避免误触发。
2. 确保监听器只注册一次
检查你的代码结构:不要把这些bot.onText的注册代码放在bot.on('message')的回调里,也不要放在会被重复调用的函数中——确保它们只在程序启动时执行一次。
进阶优化(更推荐)
如果想彻底避免文本匹配的麻烦,可以改用回调键盘(InlineKeyboard),给每个按钮绑定唯一的callback_data,通过callback_query事件来处理点击,这样完全不会和文本消息冲突:
// 发送带回调数据的键盘 bot.onText(/^Link to Soundcloud$/, (msg) => { bot.sendMessage(msg.chat.id, `Alright, ${msg.from.first_name}. Let's choose a style`, { reply_markup: { inline_keyboard: [ [{ text: "Dancy", callback_data: "style_dancy" }], [{ text: "Chill", callback_data: "style_chill" }] ] } }); }); // 处理回调点击 bot.on('callback_query', (callbackQuery) => { const msg = callbackQuery.message; const data = callbackQuery.data; if (data === "style_dancy") { bot.editMessageText(`Dancy link is here, ${msg.chat.first_name}. Enjoy! ${dancy_collection[rand_dancy_collection]}`, { chat_id: msg.chat.id, message_id: msg.message_id, reply_markup: { inline_keyboard: [ [{ text: "More dancy", callback_data: "more_dancy" }], [{ text: "Back to choose style", callback_data: "back_style" }] ] } }); } // 其他回调逻辑... });
这样处理按钮点击会更精准,也不会出现误触发的情况。
内容的提问来源于stack exchange,提问作者Bereznyak
相关产品推荐
相关产品推荐

