简体   繁体   English

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

[英]Discord.js dynamic command handler not working

So I followed the dynamic command handler guide on the discord.js guide site , and it turns out every time I try to let it execute a command, it says that the execute function is undefined, no matter how I tried to fix it.所以我遵循了discord.js 指南站点上动态命令处理程序指南,结果每次我尝试让它执行命令时,它都说执行函数未定义,无论我如何尝试修复它。 To make sure that my code is supposed to be working, I downloaded the example code they had on the guide and ran it, which also didn't work for some reason.为了确保我的代码可以正常工作,我下载了他们在指南中的示例代码并运行了它,但由于某种原因也无法正常工作。 My discord.js and node.js are all up to date.我的 discord.js 和 node.js 都是最新的。

Since I do not know your current files/code, I can provide an example.由于我不知道您当前的文件/代码,我可以提供一个示例。
Also, in this example, I will be assuming that you have named your bot variable client .此外,在本例中,我将假设您已将 bot 变量命名为client

  • First, make sure you have a folder named commands .首先,确保您有一个名为commands的文件夹。

  • On the top of your bot code ( index.js or whatever it's called), add this line: const fs = require("fs");在您的机器人代码( index.js或任何名称)的顶部,添加以下行: const fs = require("fs");

  • In your bot code, after the bot definition ( var client = new Discord.Client() ), add these lines:在您的机器人代码中,在机器人定义( var client = new Discord.Client() )之后,添加以下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);
}
  • And on your message event listener (assuming that you already have made some commands in the folder), replace your command if statement(s) with this:在您的消息事件侦听器上(假设您已经在文件夹中创建了一些命令),将您的命令 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);
  • Creating commands will be the process of creating JavaScript files in your commands folder.创建命令将是在命令文件夹中创建 JavaScript 文件的过程。 So in your commands folder, create a file (filename will be like "commandname.js" or something) and the content will be:因此,在您的命令文件夹中,创建一个文件(文件名类似于“commandname.js”或其他内容),内容将是:
module.exports = {
  name: "commandname",
  description: "Command description here.",
  execute(message, args) {
    // Now you can do your command logic here
  }
}

I hope this helped!我希望这有帮助! If it isn't clear, feel free to downvote.如果不清楚,请随意投票。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM