Discord bot throwing 'message is not defined' error when implementing clear command

I’m working on a purge command for my Discord bot and keep getting this error. When I try to run the command, it says the message variable is not defined. I think there’s something wrong with how I’m handling the message object but I can’t figure out what.

My main bot file:

bot.on("ready", () => {
console.log("BOT IS NOW ONLINE")

const parameters = msg.content.slice(cmdPrefix.length).split(/ +/);
const cmd = parameters.shift().toLowerCase();

if(!msg.content.startsWith(cmdPrefix) || msg.author.bot) return;
if(cmd === "purge"){
    bot.commands.get('purge').execute(msg, parameters);
}
});

My purge command file:

module.exports = {
name: "purge",
description: "Delete messages",
async execute(msg, parameters) {
    if(!parameters[0]) return msg.reply("Please specify number of messages to delete");
    if(isNaN(parameters[0])) return msg.reply("Please enter a valid number");
    
    if(parameters[0] > 100) return msg.reply("Maximum 100 messages allowed");
    if(parameters[0] < 1) return msg.reply("Must delete at least 1 message");
    
    await msg.channel.messages.fetch({limit: parameters[0]}).then(msgs =>{
        msg.channel.bulkDelete(msgs);
    })
}
}

I’m still learning JavaScript so any help would be great. Thanks!

yep, you got it! msg isn’t defined in the ready event. try moving your command handling to the message event - that’s where you’ll have access to msg. good luck with your bot!

The issue is where you’re trying to access the msg variable. You can only use msg inside the message event handler, not in the ready event. The ready event fires once when your bot starts up - it doesn’t have any message data. Move your command handling into a message event listener instead. Keep the ready event for initialization stuff only.

You’ve got your events mixed up. The ready event fires once when your bot connects - there’s no message to work with at that point. You need a separate message event handler where msg actually exists. Move your command parsing into bot.on('message', (msg) => { ... }) instead. I made this same mistake when I started and wasted hours figuring it out. Keep ready for startup stuff like logging that your bot’s online.