首页 > 解决方案 > 带有子分类文件夹的命令处理程序

问题描述

这是我当前使用的命令处理程序,它按预期工作。

try {
  let ops = {
    active: active
  }

  let commandFile = require(`./commands/${cmd}.js`)
  commandFile.run(client, message, args, ops);
} catch (e) {
  console.log(e);
}

但正如您所看到的,它只是读入命令文件夹并.js从那里提取文件。
我想要做的是为了我自己的“强迫症”目的对命令进行子分类,这样我就可以更好地跟踪它们。
这个命令处理程序有什么办法吗?

另外,我已经尝试过discord.js-commando,但我个人并不喜欢它使用的命令结构。

标签: node.jsdiscord.js

解决方案


我会使用这个require-all包。

假设您有如下文件结构:

commands:
  folder1:
    file1.js
  folder2:
    subfolder:
      file2.js

您可以使用require-all来完全要求所有这些文件:

const required = require('require-all')({
  dirname: __dirname + '/commands', // Path to the 'commands' directory
  filter: /(.+)\.js$/, // RegExp that matches the file names
  excludeDirs: /^\.(git|svn)|samples$/, // Directories to exclude
  recursive: true // Allow for recursive (subfolders) research
});

上面的required变量将如下所示:

// /*export*/ represents the exported object from the module
{
  folder1: { file1: /*export*/ },
  folder2: { 
    subfolder: { file2: /*export*/ } 
  }
}

为了获得您需要使用递归函数扫描该对象的所有命令:

const commands = {};

(function searchIn(obj = {}) {
  for (let key in obj) {
    const potentialCommand = obj[key];

    // If it's a command save it in the commands object
    if (potentialCommand.run) commands[key] = potentialCommand;
    // If it's a directory, search recursively in that too
    else searchIn(potentialCommand);
  }
})(required);

当您要执行命令时,只需调用:

commands['command-name'].run(client, message, args, ops)

你可以在这个repl中找到一个工作演示(带字符串) 。


推荐阅读