【问题标题】:If command isn't found reply with message如果找不到命令,则回复消息
【发布时间】:2021-10-22 23:35:37
【问题描述】:

我试图让我的机器人检查每条消息,如果一个是命令,检查命令是否正确,如果不是,回复“无效命令,键入 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.js discord discord.js


    【解决方案1】:

    您能否提供更多信息,例如错误出现在哪一行以及这个 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")
                }
            });
        }
      })
    

    【讨论】:

    • commandName 在上面提供的代码中定义,对于该行,如果我估计正确,它是 14。
    • 哦,对不起,我没看过!无论如何,我可以清楚地看到 commandName 没有在函数 fs.readdir 之外声明,所以 client.on 将无法访问它。您必须以某种方式返回它才能在函数外部访问。
    • 我明白了,你认为有更简单的方法吗?
    • 您也可以在 clients.on 中传递文件,以便重新创建它。让我用代码编辑我的答案。
    • 再次查看答案,刚刚更新。
    猜你喜欢
    • 2013-04-21
    • 2012-05-31
    • 2012-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2021-09-08
    • 1970-01-01
    • 2021-01-16
    相关资源
    最近更新 更多