I’m working on a Discord bot that automatically removes messages after a delay, but I want certain messages to be exempt from deletion. Specifically, I need messages containing *SAVE to not get deleted.
The problem is I keep getting a ReferenceError saying exemptFlag is not defined whenever someone types *SAVE in the chat. How can I properly implement this conditional logic to prevent deletion of specific messages?
You’re getting that error because exemptFlag isn’t declared anywhere. Your code’s way more complicated than it needs to be. Just merge both handlers and use early returns:
client.on('message', msg => {
const text = msg.content.toLowerCase();
// Skip deletion if message contains *save
if(text.includes('*save')) {
return;
}
// Delete all other messages after 3 minutes
setTimeout(() => {
msg.delete();
}, 180000);
});
BTW, client.deleteMessage() is deprecated - use msg.delete() instead. This fixes your undefined variable problem and keeps things simple.
you forgot to declare the exemptFlag var. just ditch that whole if statement - if the message has ‘*save’ then don’t set any timeout. restructure it so ‘*save’ msgs skip deletion completely instead of checking undefined vars.
The problem is you’re trying to use exemptFlag without declaring it first. But your logic’s backwards anyway - you’re setting a deletion timeout inside the condition that’s supposed to prevent deletion. You want to only set the timeout when the message doesn’t contain ‘*save’. Here’s a cleaner approach:
client.on('message', msg => {
const text = msg.content.toLowerCase();
if (!text.includes('*save')) {
setTimeout(() => {
msg.delete().catch(console.error);
}, 180000);
}
});
This way messages with ‘*save’ never get a deletion timer, while everything else gets deleted after 3 minutes. Added error handling since messages might already be deleted by users or other bots.