Telegram Bot中check函数未等待用户响应的问题排查
Telegram Bot 校验函数等待用户输入失效问题解决办法
你的问题出在bot.once("message")的使用方式上——这个方法不会返回Promise,所以await根本没法等待用户输入完成,代码会直接跳过输入监听,继续执行后续的数据库创建逻辑,导致name和age还没赋值就被存入数据库,自然没法实现等待用户输入的效果。
解决核心是把bot.once包装成Promise,让await能正确等待用户输入事件触发。下面是修改后的完整代码:
async function check(chat_id) { const firstText = "Hi there! Before you start using the bot, you need to enter the following details: name, age"; const res = await Subscription.findOne({ chatId: chat_id }); if (!res) { let name; let age; await bot.sendMessage(chat_id, firstText); await bot.sendMessage(chat_id, "Name?"); // 包装bot.once为Promise,等待用户输入姓名 name = await new Promise((resolve) => { bot.once("message", (message) => { resolve(message.text.trim().toLowerCase()); }); }); await bot.sendMessage(chat_id, "Age?"); // 同样包装,等待用户输入年龄 age = await new Promise((resolve) => { bot.once("message", (message) => { resolve(message.text.trim().toLowerCase()); }); }); try { await Subscription.create({ chatId: chat_id, name: name, age: age, }); await bot.sendMessage( chat_id, "Thanks for providing your details. You are now registered!" ); } catch (error) { console.error("Error inserting data:", error.message); await bot.sendMessage(chat_id, "Error occurred. Please try again later."); } } else return; }
关键修改点
- 用
new Promise包裹bot.once,当用户发送消息时调用resolve返回输入内容,这样await就能等待用户输入完成后再继续执行。 - 直接将Promise的返回值赋值给
name和age,避免了原代码中变量未及时赋值的问题。
如果你的Bot是多用户场景,建议在监听消息时加上chat_id的判断,防止接收其他用户的消息干扰流程,示例如下:
name = await new Promise((resolve) => { const listener = (message) => { if (message.chat.id === chat_id) { bot.off("message", listener); // 移除监听 resolve(message.text.trim().toLowerCase()); } }; bot.on("message", listener); });
内容的提问来源于stack exchange,提问作者Nishant Taliwal
相关产品推荐
相关产品推荐

