I’m working on a delete command for my Discord bot but keep getting this error. The bot should remove multiple messages when I use the purge function. Here’s what I have so far:
bot.js
client.on("ready", () => {
console.log("Bot is now online!")
const arguments = msg.content.slice(botPrefix.length).split(/ +/);
const cmd = arguments.shift().toLowerCase();
if(!msg.content.startsWith(botPrefix) || msg.author.bot) return;
if(cmd === "purge"){
client.commands.get('purge').execute(msg, arguments);
}
});
purge.js
module.exports = {
name: "purge",
description: "Delete messages",
async execute(msg, arguments) {
if(!arguments[0]) return msg.reply("Please specify number of messages to delete");
if(isNaN(arguments[0])) return msg.reply("Please enter a valid number");
if(arguments[0] > 100) return msg.reply("Maximum 100 messages allowed");
if(arguments[0] < 1) return msg.reply("Must delete at least 1 message");
await msg.channel.messages.fetch({limit: arguments[0]}).then(msgs =>{
msg.channel.bulkDelete(msgs);
})
}
}
The error says ‘message is not defined’ but I’m not sure what I’m missing. Any help would be great since I’m still learning JavaScript.
Your bot.js structure is the problem. You’re putting message handling logic in the ready event, which only runs once when your bot starts. That’s why msg isn’t defined. Move your message handling to a separate messageCreate event handler instead. Also heads up - your purge command won’t work on messages older than 14 days because Discord’s bulkDelete method can’t remove them. Add a .catch() after your bulkDelete call to handle errors when this happens.
Your event handler’s messed up - you’ve got the message event code inside the ready event. Move that msg stuff to a separate messageCreate event listener. That’s why msg isn’t defined.
You’re trying to access msg in the ready event, but it should be in messageCreate. The ready event only fires when your bot starts up - not when messages come in. Here’s how to fix it:
client.on('messageCreate', (msg) => {
const arguments = msg.content.slice(botPrefix.length).split(/ +/);
const cmd = arguments.shift().toLowerCase();
if(!msg.content.startsWith(botPrefix) || msg.author.bot) return;
if(cmd === "purge"){
client.commands.get('purge').execute(msg, arguments);
}
});
Keep the ready event just for the console.log. Also, add error handling to your purge command since bulkDelete fails on messages older than 14 days.