简体   繁体   中英

Discord.js Bot disregards prefix and will respond to anything infront

I've had this bot working for a while now and for some reason, the bot will now respond to any prefix infront of it, rather than the set prefix.

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

In your code, you're not checking if the message begins with your prefix. So, your code is executed for every message, and if the command is after a substring the same length of PREFIX , it'll trigger the command.

Corrected code:

// 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;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM