Discord.js动态命令处理程序不起作用

时间:2020-02-17 05:37:06

标签: javascript node.js discord.js

所以我遵循了dynamic command handler guide on the discord.js guide site,结果是每次我尝试让它执行命令时,结果都表明执行函数是未定义的,无论我如何尝试修复它。 为确保我的代码正常运行,我下载了指南中的示例代码并运行它,由于某些原因,该代码也无法正常工作。我的discord.js和节点。 js都是最新的。

1 个答案:

答案 0 :(得分:2)

由于我不知道您当前的文件/代码,因此我可以举一个例子。
另外,在此示例中,我将假设您已将机器人变量命名为client

  • 首先,请确保您有一个名为commands的文件夹。

  • 在您的漫游器代码(index.js或它所称的名称)的顶部,添加以下行: const fs = require("fs");

  • 在您的机器人代码中,在机器人定义(var client = new Discord.Client())之后,添加以下行:

client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for(let file of commandFiles) {
  let command = require('./commands/' + file);
  client.commands.set(command.name, command);
}
  • 然后在您的消息事件监听器上(假设您已经在文件夹中执行了一些命令),将if语句替换为以下命令:
// you can use other expressions to check if the command is there
// the commandname in the client.commands.get is the filename without .js
if(message.content.startsWith("commandname")) client.commands.get("commandname").execute(message, args);
  • 创建命令将是在commands文件夹中创建JavaScript文件的过程。因此,在您的commands文件夹中,创建一个文件(文件名类似于“ commandname.js”之类的东西),内容将为:
module.exports = {
  name: "commandname",
  description: "Command description here.",
  execute(message, args) {
    // Now you can do your command logic here
  }
}

我希望这对您有所帮助!如果不清楚,请随时投票。