【问题标题】:Discord.js dynamic command handler not workingDiscord.js 动态命令处理程序不起作用
【发布时间】:2020-09-21 20:59:38
【问题描述】:

所以我跟着dynamic command handler guide on the discord.js guide site,结果每次我试图让它执行一个命令,它说执行函数是未定义的,无论我如何尝试修复它。 为了确保我的代码应该可以正常工作,我下载了他们在指南上的示例代码并运行了它,但由于某种原因它也无法正常工作。我的 discord.js 和 node. js都是最新的。

【问题讨论】:

  • 欢迎来到 SO。请显示部分代码。 bot on message, command file execute command handle from dir at bot start
  • @Cipher 我没有代码,但我会找到我稍后在 Github 上为你测试的那个
  • 我现在没有代码,但这是我稍后测试过的代码,它也不起作用(github)
  • 你使用的discord.js是什么版本的?
  • 能否也添加回溯/错误日志?

标签: javascript node.js discord.js


【解决方案1】:

由于我不知道您当前的文件/代码,我可以提供一个示例。
此外,在本例中,我将假设您已将机器人变量命名为 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
  }
}

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

【讨论】:

  • 看你的问题,很可能是你没有把命令文件放到commands文件夹里。
猜你喜欢
  • 2020-08-12
  • 2021-11-04
  • 2021-11-02
  • 2020-06-09
  • 2021-08-01
  • 1970-01-01
  • 2020-06-17
  • 2021-07-23
  • 2020-12-08
相关资源
最近更新 更多