首页 > 解决方案 > 我无法在 Discord.js 中添加多个前缀

问题描述

当前前缀是“#”。

module.exports = async function(msg) {
    let args = msg.content.split(' ');
    let command = args.shift();
    if (command.charAt(0) === '#') {
      command = command.substring(1);
      commandName[command](msg, args);
    }
};

当我尝试为其添加一组前缀时,它似乎不起作用。

const prefix = [ '#', 'br', 'bread', '<@767558534074204191>', '<@!767558534074204191>', ];

module.exports = async function(msg) {
  let tokens = msg.content.split(' ');
  let command = tokens.shift();
  if (command.charAt(0) === prefix) {
    command = command.substring(1);
    commandName[command](msg, tokens);
  }
};

如何为此添加更多前缀,以便我可以有多个前缀?就像提到的机器人一样作为前缀之一。

标签: javascriptnode.jsdiscord.js

解决方案


线条

const prefix = [ '#', 'br', 'bread', '<@767558534074204191>', '<@!767558534074204191>' ];

  if (command.charAt(0) === prefix) {
     ... do stuff
  }
};

您定义了一个包含 5 个值的数组,然后您尝试查看字符串命令的第一个字符是否等于该数组。这永远不会评估为真,因为函数.charAt(0)将只返回该字符串的第一个字符。

您要做的是根据命令检查数组的每个值。我们可以在遍历数组时对字符串使用startsWith()函数。

就像是:

const prefix = [ '#', 'br', 'bread', '<@767558534074204191>', '<@!767558534074204191>' ];
  
  // see if a value in the prefix array is at the beginning of the command.
  for(let x = 0; x < prefix.length; x++) {
      if (command.startsWith(prefix[x])) { 
          ...do whatever you were intending to here
          break // break out of the loop by using the break keyword.         
      }
  }
  })
};

推荐阅读