Discord Bot throws undefined variable error when trying to delete messages containing *DD

I’m working on a Discord bot that should delete messages containing a specific pattern, but I’m running into issues with an undefined variable.

client.on('messageCreate', (msg) => {
  const content = msg.content.toLowerCase();
  if (content.includes('*dd')) {
    if (status === null) {
      setTimeout(() => {
        msg.delete();
      }, 2000);
    }
  }
});

The bot starts without any issues, but when someone types a message with *DD, it throws an error saying “status is not defined”. The message deletion isn’t working at all. I think there might be a problem with how I’m checking the variable or the way I’m handling the message deletion. Can someone help me figure out what’s wrong with this code?

Your main problem is that status variable - it’s not declared anywhere, so you’ll get a ReferenceError every time. You need to define it before using it in the if statement. I’m also wondering why you’re checking if status === null before deleting the message. If you’re trying to do some cooldown or state management, there might be better ways to handle it. For simple message deletion based on pattern matching, just skip the status check and delete the message after the timeout. One more thing - msg.delete() can fail if someone else already deleted the message or your bot doesn’t have permissions, so wrap it in a try-catch block.

The error arises from the fact that the status variable isn’t declared in your code. To resolve the issue, initialize it before the condition check. I encountered a similar problem while developing my moderation bot. Simply add let status = null; either above your event listener or at the start of your script. Additionally, ensure your bot has the necessary permissions to delete messages; if not, the msg.delete() function will fail.

yo, u gotta declare the status variable, that’s why you’re getting that error. just add let status = null; at the start of ur code and everything should work fine!