Discord bot throwing error: message not recognized

Help needed with my Discord bot

I’m new to JavaScript and trying to set up a command to clear messages in my Discord bot. But I’m getting this error:

ReferenceError: message is not defined

It happens when I try to use the !clear command. Here’s a snippet from my code:

const chatArgs = userInput.slice(cmdPrefix.length).split(/\s+/);

My main file (bot.js) looks something like this:

bot.on('ready', () => {
  console.log('Bot is online!');

  // Code causing the error
  const chatArgs = userInput.slice(cmdPrefix.length).split(/\s+/);
  const cmd = chatArgs.shift().toLowerCase();

  if (!userInput.startsWith(cmdPrefix) || bot.isBot) return;
  if (cmd === 'clean') {
    bot.commands.get('clean').run(userInput, chatArgs);
  }
});

And my clean.js file:

module.exports = {
  name: 'clean',
  description: 'Remove messages',
  async run(userInput, chatArgs) {
    // Command logic here
  }
};

Can anyone help me figure out what’s wrong? Thanks!

The issue seems to stem from using ‘userInput’ without proper context. In Discord.js, you typically work with a ‘message’ object. Try refactoring your code to use the ‘message’ event:

bot.on(‘message’, message => {
if (!message.content.startsWith(cmdPrefix) || message.author.bot) return;

const args = message.content.slice(cmdPrefix.length).split(/ +/);
const command = args.shift().toLowerCase();

if (command === ‘clean’) {
bot.commands.get(‘clean’).run(message, args);
}
});

This approach should resolve your reference error and provide the necessary context for your commands. Remember to adjust your command files accordingly to accept ‘message’ as the first parameter.

I’ve encountered similar issues when working on Discord bots. The problem seems to be in how the message event is handled. Instead of relying on ‘userInput’, try using the actual ‘message’ object from the event listener. For instance, you can modify your code like this:

bot.on(‘message’, message => {
if (!message.content.startsWith(cmdPrefix) || message.author.bot) return;

const args = message.content.slice(cmdPrefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();

if (command === ‘clean’) {
bot.commands.get(‘clean’).execute(message, args);
}
});

Ensure your command files are updated to use ‘execute’ and accept the ‘message’ object as the first parameter. This adjustment should resolve the reference error and get your bot working correctly.

hey mate, looks like ur missing the ‘message’ variable. try adding it as a parameter in ur event listener:

bot.on(‘message’, message => {
const userInput = message.content;
// rest of ur code here
});

that should fix the error. gl with ur bot!