John Silver
John Silver

Reputation: 23

Auto deleting messages in a specific channel

I have a suggestion channel, and i made it so users are only allowed to post links in it, with the ability for the bot to react on what they post. I have done the auto react on links, but i could not make the bot deletes what is not a link. So i want everything else that is not a link to be deleted.

bot.on('message', message => { 
  // whenever a message is sent
  if (bot.id === '514484773171757061') {
    return;
  }

  if (message.channel.id === "508606903740268545" ){

    if (message.content.includes('playrust.io/')) {
      message.react('✅').then( () =>{
      message.react('❌')});
    } else if (message.delete()) {
      message.channel.sendMessage('Message has been Deleted ' + message.author)
    }
  }
});

It is kind working but not very well. It deletes the message that is not a link million times and sends million notifications :/ I guess the problem is with else if part

Upvotes: 0

Views: 1669

Answers (2)

PLASMA chicken
PLASMA chicken

Reputation: 2785

client.id is not a thing so it needs to be

if (message.author.bot) return;

Then instead of

else if (message.delete()) {
      message.channel.send('Message has been Deleted ' + message.author)
    }

Use

else {
      message.delete(5000)
      message.channel.send('Message has been Deleted ' + message.author)
    }

Wich result in:

bot.on('message', message => { 
  // whenever a message is sent
  if (message.author.bot) return;


  if (message.channel.id === "508606903740268545" ){

    if (message.content.includes('playrust.io/')) {
      message.react('✅').then( () =>{
      message.react('❌')});
    } else {
message.delete(5000)
      message.channel.send('Message has been Deleted ' + message.author)
    }
  }
});

Upvotes: 0

T. Dirks
T. Dirks

Reputation: 3676

I think the problem is that you are creating a sort of infinite loop. In your code you first check if the message send is in a specific channel, after which you check if it contains a link or not. If it doesn't you send a message to that same channel saying 'I didn't find a link'.

When you send this, your bot gets triggered again because a new message has been send. It checks whether it's in a specific channel and if it contains a link, which it doesn't, and thus the cycle repeats.

It can be fixed with one simple statement, which also happends to be very good practice when creating bots. To fix it, you need to include some code which checks if a message has been send by a bot or not. Look at the example below:

bot.on('message', message => { 
  // Ignore messages from all bots
  if (message.author.bot) return;

  /* All your other code here */

Upvotes: 1

Related Questions