Node.js Discord bot conditional message deletion not working properly

I’m trying to create a Discord bot that automatically removes messages after 2 minutes, but I want it to skip messages that contain a specific pattern like #SAVE. My current code isn’t working and I’m getting errors.

Here’s my attempt at checking for the pattern:

const Discord = require('discord.js');
const client = new Discord.Client();

client.on('message', (msg) => {
  const messageText = msg.content.toLowerCase();
  if(messageText.includes('#save')) {
    if (flag === true) {
      setTimeout(() => {
        msg.delete();
      }, 120000);
    }
  }
});

This is my basic message deletion code that works:

client.on('message', (msg) => {
  setTimeout(() => {
    msg.delete();
  }, 120000);
});

But when I try to add the conditional check, I get a ReferenceError: flag is not defined error. How can I properly implement this so messages with #SAVE don’t get deleted while others do?

Your code’s backwards - you’re checking for #save then deleting anyway. Plus that undefined flag variable is throwing the reference error.

You want to delete messages that DON’T have the save pattern. Here’s the fix:

client.on('message', (msg) => {
  const messageText = msg.content.toLowerCase();
  if (!messageText.includes('#save')) {
    setTimeout(() => {
      msg.delete().catch(err => console.log('Message already deleted or error:', err));
    }, 120000);
  }
});

See the ! operator? That flips the condition. I threw in error handling too since messages might get manually deleted before the timeout hits. Also add if (msg.author.bot) return; at the start so your bot doesn’t try deleting its own messages or system stuff.

yeah, you’ve got the logic backwards like finn mentioned. plus that flag variable doesn’t exist - that’s your reference error right there. here’s a cleaner approach:

client.on('message', (msg) => {
  if (!msg.content.toLowerCase().includes('#save')) {
    setTimeout(() => msg.delete(), 120000);
  }
});

if the message doesn’t have #save, it gets deleted after 2 mins. way simpler.

Your conditional logic is backwards and you’re using an undefined flag variable. You want to delete messages that DON’T have the save pattern, not the ones that do.

client.on('message', (msg) => {
  // Skip bot messages to avoid permission errors
  if (msg.author.bot) return;
  
  // Only delete if message doesn't contain #save
  if (!msg.content.toLowerCase().includes('#save')) {
    setTimeout(() => {
      msg.delete().catch(console.error);
    }, 120000);
  }
});

Add the bot check - trying to delete system messages or other bot messages can cause permission issues. The error handling stops crashes when messages get manually deleted before the timeout hits.