javascript - Discord.js 动态命令处理程序不起作用
问题描述
所以我遵循了discord.js 指南站点上的动态命令处理程序指南,结果每次我尝试让它执行命令时,它都会说执行函数是未定义的,无论我如何尝试修复它。为了确保我的代码应该可以正常工作,我下载了他们在指南上的示例代码并运行了它,但由于某种原因它也无法正常工作。我的 discord.js 和 node.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
}
}
我希望这有帮助!如果不清楚,请随时投反对票。
推荐阅读
- typescript - 在 vuejs 中实现简单的 markdown 指令,反应性问题
- c++ - C++20 宇宙飞船运算符的性能问题?
- python - 合并拆分为多行的 Python Dataframe 行
- python - Django Admin 操作不同的名称,然后是函数名称
- omnet++ - 如何在 omnet++ 中获取模型的节点?
- javascript - 如何在 React Native 的函数中查看另一个类?
- python - 评估两个数据集之间特征的保存情况
- java - Spring Boot 应用程序性能缓慢
- instagram-api - 如何检索用户的公开 Instagram 帖子?
- javascript - 我该如何解决这个算法?