【问题标题】:Command Handler with Sub-Categorized folders带有子分类文件夹的命令处理程序
【发布时间】:2019-09-23 09:46:17
【问题描述】:

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

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.js discord.js


    【解决方案1】:

    我会使用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)
    

    您可以在this repl 找到一个工作演示(带字符串)。

    【讨论】:

    • 在这个编码中,我会把这个let ops = { active: active }放在哪里?我的队列系统需要它
    • 你可以像之前一样放在commands['command-name'].run(...)之前
    • 关于这个问题的旁注:我看到你留下了一些未回答的问题(如thisthisthis):你能接受答案以关闭它们或发布并接受一个新的答案,解释你做了什么来解决它?
    • 我会把commands['command-name'].run(...)放在哪里?在每个命令内还是在 require-all 下?
    • 好吧,从头开始,我让它检测我的命令以及使用我的权限系统,但是,当我运行命令时,它在频道中没有响应,也没有在控制台中抛出任何错误。有什么建议吗?我很乐意发布我的 message.jsapp.js 的 pastebin 链接
    猜你喜欢
    • 2021-12-13
    • 2019-07-19
    • 2022-01-14
    • 1970-01-01
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多