JS编写Discord机器人命令时后续代码提示不可达是什么原因?
问题根因
你代码中的run函数第一行就执行了return message.channel.send(what is your hiring status?),JavaScript中函数执行到return语句会直接终止运行,后续所有代码都不会被执行,这就是你收到代码不可达提示的直接原因。
另外就算你删掉这行的return,原有逻辑也不符合预期:你直接读取的message.content是用户触发status命令的那条消息的内容,不是用户后续回复的招聘状态内容。
修正方案
使用Discord.js的消息收集器实现「先提问、等用户回复后输出状态」的需求,修正后代码如下:
module.exports = { name: "status", category: "status check", description: "Checks the status of the pm manager.", aliases: [], usage: "status", userperms: ["ADMINISTRATOR"], botperms: [], run: async (client, message, args) => { // 先发送询问消息,不要加return await message.channel.send(`what is your hiring status?`); // 创建消息收集器,只收集触发命令的用户的消息,超时时间30秒 const filter = msg => msg.author.id === message.author.id; const collector = message.channel.createMessageCollector({ filter, time: 30000 }); collector.on('collect', async (answerMsg) => { // 收到用户回复后发送状态 await message.channel.send(`Status of ${message.author}: Hiring status: ${answerMsg.content}`); // 停止收集 collector.stop('gotAnswer'); }); collector.on('end', (collected, reason) => { if (reason !== 'gotAnswer') { message.channel.send('超时未收到你的回复,已取消状态录入。'); } }); }, };
改动说明
- 移除了发送询问消息前的
return,保证后续代码可以正常执行 - 新增消息收集器逻辑,监听用户的后续回复,不会直接读取命令消息的内容
- 新增超时处理逻辑,避免收集器无限等待
内容的提问来源于stack exchange,提问作者Chubbydux
相关产品推荐
相关产品推荐

