【问题标题】:Discord.js Bot disregards prefix and will respond to anything infrontDiscord.js Bot 忽略前缀并且会响应前面的任何内容
【发布时间】:2019-06-16 01:35:07
【问题描述】:

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

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

【问题讨论】:

  • 您甚至从不检查前缀,您只是将其长度作为子字符串。假设 PREFIX = "!" 然后 PREFIX.length = 1"?".length = 1 所以两者的行为相同。

标签: javascript discord discord.js


【解决方案1】:

在您的代码中,您没有检查消息是否以您的前缀开头。因此,您的代码会针对每条消息执行,如果该命令位于与 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;
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-14
    • 2011-02-06
    • 2018-01-03
    • 1970-01-01
    • 2013-06-15
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多