Search code examples
discorddiscord.js

.includes firing muiltple times


I am trying to test whether a message (string) sent from the user/client is containing a word and then it will pick 1 of 2 random responses and it works, however it sends the message way too many times.

client.on("messageCreate", message => {
  if(message.content.includes("dream")) {
   var msgnumber= (Math.floor((Math.random() * 2) + 1));
    console.log(msgnumber);
    if (msgnumber===1) {
         message.channel.send("did someone say dream!?");
    } else if (msgnumber===2) {
         message.channel.send("why we talkin' about dream... huh!?")
    }
  }
})

It does pick a random message if a message sent contains the keyword, one problem is it sends way too many times.

The output message


Solution

  • Your bot is activating itself. Whenever it posts a message containing "dream", it sees that message, and decides to post a reply, creating an infinite loop. Try adding the line if (msg.author.bot) return; right above where you check for if the message contains "dream". This will exit the function early and avoid the loop.