首页 > 解决方案 > Discord.js Bot 忽略前缀并且会响应前面的任何内容

问题描述

我已经让这个机器人工作了一段时间,出于某种原因,机器人现在将响应它前面的任何前缀,而不是设置的前缀。

const PREFIX = '$';
bot.on('message', message => {
    let argus = message.content.substring(PREFIX.length).split(" ");
    switch (argus[0]) {
        case 'yeet':
            message.channel.send("yeet")
        break;       
    }
});

标签: javascriptdiscorddiscord.js

解决方案


在您的代码中,您没有检查消息是否以您的前缀开头。因此,您的代码会针对每条消息执行,如果该命令位于相同长度的子字符串之后PREFIX,它将触发该命令。

更正的代码:

// Example prefix.
const PREFIX = '!';

bot.on('message', message => {
  // Ignore the message if it's from a bot or doesn't start with the prefix.
  if (message.author.bot || !message.content.startsWith(PREFIX)) return;

  // Take off the prefix and split the message into arguments by any number of spaces.
  const args = message.content.slice(PREFIX.length).split(/ +/g);

  // Switching the case of the command allows case iNsEnSiTiViTy.
  switch(args[0].toLowerCase()) {
    case 'yeet':
      message.channel.send('yeet')
        // Make sure to handle any rejected promises.
        .catch(console.error);

      break;
  }
});

推荐阅读