【问题标题】:Multi-folder command handler多文件夹命令处理程序
【发布时间】:2022-01-14 23:00:06
【问题描述】:

我正在尝试使我的命令处理程序允许在文件夹中包含文件。例如,我有一个名为 ./commands/moderation 的文件夹,或者一个名为 ./commands/fun 的文件夹,等等。我该怎么做?

我的代码看起来像这样,但它只处理我的 ./commands 文件夹中的 JavaScript 文件。

for (const file of commandFiles) {
    const command = require(`./commands/${file}`)
    client.commands.set(command.name, command)
}

// ...

if (!client.commands.has(command)) return;
try {
    client.commands.get(command).execute(message, args);
}
// ...

【问题讨论】:

    标签: javascript node.js discord discord.js bots


    【解决方案1】:

    目前,您的 commandFiles 仅包含您的 ./commands 文件夹中的文件。要创建如下所示的文件夹结构,您还需要读取 ./commands 中的文件夹内容。

    - commands
      - fun
        - game-1.js
        - game-2.js
      - moderation
        - kick.js
        - snipe.js
    

    因此,首先,您使用readdirSync 读取commands 文件夹的内容,并且对于每个返回的文件夹,您还需要获取扩展名为js 的文件。查看下面的代码:

    const client = new Discord.Client();
    client.commands = new Discord.Collection();
    
    const commandFolders = fs.readdirSync('./commands');
    
    for (const folder of commandFolders) {
      const commandFiles = fs
        .readdirSync(`./commands/${folder}`)
        .filter((file) => file.endsWith('.js'));
    
      for (const file of commandFiles) {
        const command = require(`./commands/${folder}/${file}`);
        client.commands.set(command.name, command);
      }
    }
    // ...
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2019-07-19
      • 2019-09-23
      • 1970-01-01
      • 2022-06-25
      • 2021-11-24
      • 1970-01-01
      • 2011-06-28
      相关资源
      最近更新 更多