首页 > 解决方案 > Discord.js 动态命令处理程序不起作用

问题描述

所以我遵循了discord.js 指南站点上的动态命令处理程序指南,结果每次我尝试让它执行命令时,它都会说执行函数是未定义的,无论我如何尝试修复它。为了确保我的代码应该可以正常工作,我下载了他们在指南上的示例代码并运行了它,但由于某种原因它也无法正常工作。我的 discord.js 和 node.js 都是最新的。

标签: javascriptnode.jsdiscord.js

解决方案


由于我不知道您当前的文件/代码,我可以提供一个示例。
此外,在本例中,我将假设您已将您的机器人变量命名为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);
  • 创建命令将是在命令文件夹中创建 JavaScript 文件的过程。因此,在您的命令文件夹中,创建一个文件(文件名将类似于“commandname.js”或其他内容),内容将是:
module.exports = {
  name: "commandname",
  description: "Command description here.",
  execute(message, args) {
    // Now you can do your command logic here
  }
}

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


推荐阅读