Discord.js:用户ID拦截特定命令失效及消息重复发送问题
问题分析与修复方案
问题1:被封禁用户发送命令仍会触发响应
你的代码中,当封禁用户发送hi时,仅添加了⛔反应,但未终止后续代码执行(若存在其他命令逻辑会被触发)。另外如果bannedid是多个用户ID的集合,当前===的判断方式只能匹配单个ID,无法覆盖多封禁场景。
问题2:消息发送两次
你在else if代码块内部定义himessage函数,每次触发hi命令时都会重新创建这个函数,易引发意外的重复调用;同时若message事件被多次注册,也会导致重复响应。
修复后的代码
// 将函数移到事件监听外部,避免重复定义 function himessage(message) { const messages = ['hi uwu', 'owo', 'no', 'stinky', 'amongus', 'The FitnessGram PACER Test is a multistage aerobic capacity test that progressively gets more difficult as it continues. The test is used to measure a students aerobic capacity as part of the FitnessGram assessment. Students run back and forth as many times as they can, each lap signaled by a beep sound. The test get progressively faster as it continues until the student reaches their max lap score. The PACER Test score is combined in the FitnessGram software with scores for muscular strength, endurance, flexibility and body composition to determine whether a student is in the Healthy Fitness Zone™ or the Needs Improvement Zone™.']; const cheese = Math.floor(Math.random() * messages.length); message.channel.send(messages[cheese]); } client.on('message', async message => { // 处理封禁用户:若为封禁ID,添加反应后直接终止后续逻辑 // 多封禁ID场景可改为数组:const bannedIds = ['id1', 'id2']; 用bannedIds.includes(message.author.id)判断 if (message.author.id === bannedid) { if (message.content === 'hi') { await message.react('⛔'); } // 终止后续代码执行,避免触发正常命令逻辑 return; } // 非封禁用户的命令处理 if (message.content === 'hi') { himessage(message); } });
关键修复点
- 终止封禁用户后续逻辑:在封禁用户的处理块末尾添加
return,确保不会执行后面的正常命令响应代码。 - 函数定义外置:将
himessage函数移到message事件监听外部,避免每次触发命令都重新创建函数,消除重复调用隐患。 - 适配多封禁场景:若需要封禁多个用户,将
bannedid改为数组,使用includes方法判断用户ID是否在封禁列表中。
内容的提问来源于stack exchange,提问作者rat
相关产品推荐
相关产品推荐

