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

I’m working on a Discord bot and trying to create a purge command that deletes multiple messages at once. However, I keep getting a ReferenceError saying that ‘message is not defined’. I’m still learning JavaScript so any help would be great.

Main bot file:

client.on('ready', () => {
  console.log('Bot is now online and ready!')
  
  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 command file:

module.exports = {
  name: 'purge',
  description: 'Delete multiple messages',
  async execute(msg, arguments) {
    if (!arguments[0]) return msg.reply('Please specify the 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 can be deleted at once');
    if (arguments[0] < 1) return msg.reply('Please delete at least 1 message');
    
    await msg.channel.messages.fetch({ limit: arguments[0] }).then(msgs => {
      msg.channel.bulkDelete(msgs);
    })
  }
}

The error occurs when I try to use the purge command. What am I doing wrong here?

You’re trying to access msg in the ready event, but it doesn’t exist there. The ready event only fires once when your bot starts up - it doesn’t get any message data. Move all your command handling logic to a messageCreate event handler instead. Keep only the console.log in the ready event. Set up a separate messageCreate listener where you can actually access the message object and parse commands.

yea, msg is undefined in ‘ready’ event - that’s where ur messin up. just move the command check to ‘messageCreate’ and u should be good!

You’re putting commands inside the ready event listener, but that event doesn’t get any message parameter. The ready event only fires once when your bot starts up - it can’t access message data. Move all your command parsing logic to a separate messageCreate event listener (or message if you’re using an older discord.js version). Keep only the console.log statement in your ready event. Also check your discord.js version - newer versions use messageCreate, older ones use message.