ReferenceError with my Discord bot when trying to preserve certain messages in Node.js

I am developing a Discord bot that deletes messages after a certain time, but I need it to keep messages containing a specific phrase like *DD.

const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('message', function(message) {
  const content = message.content.toUpperCase();
  if(content.includes('*DD')) {
    if (condition === null) {
      setTimeout(function() {
        bot.deleteMessage(message);
      }, 120000);
    }
  }
});

This is my attempt to ensure messages with *DD are not deleted.

bot.on('message', function(message) {
  setTimeout(function() {
    bot.deleteMessage(message);
  }, 120000);
});

The code above removes messages after two minutes. I’m trying to adjust it so messages that contain *DD aren’t deleted.

ReferenceError: condition is not defined
    at Client.<anonymous> (C:bot.js:115:13)
    at emitOne (events.js:101:20)
    at Client.emit (events.js:188:7)

I receive this error when *DD is sent in the Discord chat. Any help would be appreciated.

The ReferenceError occurs because you’re referencing a variable condition that doesn’t exist in your code. To ensure messages containing *DD aren’t deleted, you should reverse your logic. Set up the deletion timer for all messages, but skip it when the message has *DD. Modify your code as follows:

bot.on('message', function(message) {
  const content = message.content.toUpperCase();
  if (!content.includes('*DD')) {
    setTimeout(function() {
      message.delete();
    }, 120000);
  }
});

Additionally, bot.deleteMessage() has been deprecated; use message.delete() instead to correctly handle the deletion of messages.

Looking at your error, the main issue is that you’ve declared a variable called condition without actually defining it anywhere in your code. When the JavaScript engine tries to evaluate if (condition === null), it throws a ReferenceError because condition doesn’t exist. You can simply remove that entire condition check since it’s not serving any purpose. Your logic should be straightforward - only delete messages that don’t contain the *DD phrase. Also worth noting that you’re mixing up your message deletion approach. The bot.deleteMessage() method you’re using is from an older version of discord.js and might not work properly with newer versions. Consider updating to use message.delete() for better compatibility and reliability.

yeah your condition var isnt declared anywhere, hence the referenceerror. also, you shouldnt use bot.deleteMessage(), instead go for message.delete(). just check if the message doesnt have *DD before setting the timeout, way simpler!