Zariaa_
Zariaa_

Reputation: 116

If command isn't found reply with message

I am trying to make my bot check every message, if one is a command, check if the command is right, if it isn't, reply with "Invalid comand, type z!help for a list of commands".

What I have:

fs.readdir("./commands/", (err, files) => {
  if (err) return console.error(err);
  files.forEach(file => {
    if (!file.endsWith(".js")) return;
    let props = require(`./commands/${file}`);
    let commandName = file.split(".")[0];
    console.log(`Attempting to load command ${commandName}`);
    client.commands.set(commandName, props);
  });
});

client.on('message', message => {
  if (message.content.startsWith("z!")){
    if (message.content !== commandName){
      message.reply("Invalid command")
    }
  }
})

But I get

ReferenceError: commandName is not defined

Any help is appreciated!

Upvotes: 0

Views: 80

Answers (1)

R1D3R175
R1D3R175

Reputation: 170

Could you provide more info like at what line does the error appear and where is this commandName firstly defined?

fs.readdir("./commands/", (err, files) => {
    if (err) return console.error(err);
    files.forEach(file => {
      if (!file.endsWith(".js")) return;
      let props = require(`./commands/${file}`);
      let commandName = file.split(".")[0];
      console.log(`Attempting to load command ${commandName}`);
      client.commands.set(commandName, props);
    });
  });
  
  client.on('message', (message, files) => {
    if (message.content.startsWith("z!")){
        files.forEach(file => {
            if (message.content !== file.split(".")[0]){
                message.reply("Invalid command")
            }
        });
    }
  })

Probably the code here won't work, so, here's another idea:

let globalFile;

function passFile(file) { // Generally speaking, that's a bad idea.
    globalFile = file
    return file
}

fs.readdir("./commands/", (err, files) => {
    if (err) return console.error(err);
    files.forEach(file => {
      if (!file.endsWith(".js")) return;
      let props = require(`./commands/${file}`);
      let commandName = passFile(file.split(".")[0]);
      console.log(`Attempting to load command ${commandName}`);
      client.commands.set(commandName, props);
    });
  });
  
  client.on('message', message => {
    if (message.content.startsWith("z!")){
        files.forEach(file => {
            if (message.content !== globalFile){ // Check if globalFile is something
                message.reply("Invalid command")
            }
        });
    }
  })

Upvotes: 1

Related Questions