Home > Software design >  Why my discord bot spams messages by adding the following code?
Why my discord bot spams messages by adding the following code?

Time:02-14

I am coding a basic moderation bot for Discord in discord.js. But by adding the following code for replying "Hello!" everytime someone sends message from the list, the bot spams a lot of "Hello!" messages in the channel.

client.on("message", async message =>{
  if (message.content == "Hi" || message.content == "hi" || message.content == "hello" || message.content == "Hello" || message.content == "hi!" || message.content == "Hi!" || message.content == "Hello!" || message.content == "hello!")
  {
    message.channel.send(`Hello!`)
  }
});

Can someone explain why does this happen and provide a solution to it? I tried to search on the web but was not able to phrase the question properly, so I got no answers.

P.S.: I am still learning JavaScript and I am coding this in replit.com, if that matters!

CodePudding user response:

As esqew pointed out in their comment, your bot is stuck in an event loop of replying to its own message. An easy way to deal with this problem would be to ignore messages from either all bots, or just the bot's own messages, as demonstrated below.

client.on("message", async message => {
    // Method A: Ignore all Bots
    if(message.author.bot) return;

    // Method B: Ignore self only
    if(message.author.id == client.user.id) return;

    // Insert rest of event code here, etc...
});

See User.bot (Discord.js Docs)

  • Related