首页 > 解决方案 > 如果未找到命令,则回复消息

问题描述

我试图让我的机器人检查每条消息,如果一个是命令,检查命令是否正确,如果不是,回复“无效的命令,键入 z!help 以获取命令列表”。

是)我有的:

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")
    }
  }
})

但我明白了

ReferenceError: commandName is not defined

任何帮助表示赞赏!

标签: node.jsdiscorddiscord.js

解决方案


您能否提供更多信息,例如错误出现在哪一行以及这个 commandName 最初定义在哪里?

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")
            }
        });
    }
  })

可能这里的代码不起作用,所以,这是另一个想法:

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")
            }
        });
    }
  })

推荐阅读