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.
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?
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:
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.