You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.js打乱字命令BUG求助:大写字母致机器人崩溃

解决Discord机器人Scramble命令崩溃问题

我来帮你搞定这个崩溃问题!咱们先理清楚根源:当用户输入首字母大写的Apple时,你的消息匹配逻辑是用m.content.includes(givenword)——这里givenword是大写开头的Apple,但用户大概率会回复小写的apple,导致消息收集器30秒内收不到任何符合条件的消息。这时候collected.first()会返回undefined,你再去访问它的author属性,自然就抛出“无法获取undefined的author属性”的错误了。

另外还有个潜在隐患:就算用户输入的是小写单词,如果30秒内没人答对,同样会触发崩溃。所以咱们需要从两个核心点修复:

修复步骤

1. 统一大小写实现模糊匹配

把目标词和用户后续的回复都转换成相同大小写(比如全小写),这样不管用户输入Apple、APPLE还是apple,都能正确匹配到正确答案。

2. 处理无正确回复的边界情况

在收集器的end事件里,先判断是否收集到了有效消息,如果没有,就发送“无人答对”的提示,而不是直接访问collected.first().author。

修改后的完整代码

module.exports = { 
  name: 'scramble', 
  execute(message, args) { 
    const Discord = require('discord.js') 
    let givenword = args.slice(0).join(" ").toLowerCase(); // 统一转成小写,消除大小写差异
    function scramble(givenword) { 
      var word = givenword.split("") 
      n = word.length 
      for(var i = n - 1; i > 0; i--) { 
        var j = Math.floor(Math.random() * (i+1)); 
        var tmp = word[i]; 
        word[i] = word[j] 
        word[j] = tmp; 
      } 
      return word.join("") 
    } 
    scrambledword = scramble(givenword) 
    const embed = new Discord.MessageEmbed() 
      .setTitle('Scramble time!') 
      .setColor("RANDOM") 
      .setDescription("The word is: " + scrambledword) 
      .setFooter('You have 30 seconds to try and guess it, the first person to answer correctly ') 
    message.channel.send({embed}); 
    message.delete() 
    // 修改filter:把用户消息也转小写,同时排除机器人自己的消息
    const filter = m => !m.author.bot && m.content.toLowerCase().includes(givenword); 
    const collector = message.channel.createMessageCollector(filter, { time: 30000 }); 
    collector.on('collect', m => { 
      console.log(`Collected ${m.content}`); 
    }); 
    collector.on('end', collected => { 
      // 先判断是否有收集到有效消息
      if (collected.size === 0) {
        message.channel.send(`Time's up! Nobody got the correct answer. The answer was ${givenword}`);
      } else {
        message.channel.send(`${collected.first().author} got the correct answer first! The answer was ${givenword}`);
      }
      console.log(`Collected ${collected.size} items`); 
    }); 
  } 
}

额外优化建议

  • 可以给scramble函数加个判断:如果打乱后的单词和原词完全一致,就重新打乱,避免短单词出现“打乱后和原词一样”的尴尬情况。
  • 代码里的Discord模块建议移到文件顶部导入,而不是在execute函数里重复导入,这样更符合代码规范。

内容的提问来源于stack exchange,提问作者Gaxyhs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:33:00