具有共享和独立命令的动态命令处理程序

问题描述 投票:0回答:1

我正在为多个通道设置命令处理程序(抽搐)。目前,我将所有命令划分为用户特定的文件夹和通用的文件夹。通过使用map()访问它们。我希望每个用户/通道只能访问其文件夹和通用文件夹。映射键是.js文件中的名称。

那么什么是最好的方法呢?香港专业教育学院试图映射到通用文件夹和登录时与用户名匹配的文件夹。但是我不知道一种更改client.commands.set(key,value)中的“命令”的方法,因此它将是client。(nameChannel).set(key,value)。这样,我就可以将默认的和用户特定的文件夹分配给地图。

也fs.dirReadSync列出了文件夹和子文件夹中的所有.js。我如何一次访问所有需求?通配符似乎不起作用,所以我需要像下面显示的那样列出它们吗?我希望以后可以添加更多内容,并且如果可能的话不要一一进行硬编码。

//hardcode example.
var moduleA = require( "./module-a.js" );
var moduleB = require( "../../module-b.js" );
var moduleC = require( "/my-library/module-c.js" );

下面的代码片段仍在执行。我想实现的目标,

-排除从其他通道调用特定于通道的命令。-知道是否/标准或推荐的方法是什么。-如何在一个require中将readDir中的所有.js同步为require。]。


client.commands = new Map();
 //add commands property/method to client instance. A map to iterate over.
 const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
 //reads file system and filter .js files only. returns an array of those items.
 for (const file of commandFiles) {
     const command = require(`./commands/${file}`); //this only grabs the results in commands itself can't use wildcards..
     //sets a new item in the collection.
     //Key of map is command name.
     client.commands.set(command.name, command);
}

//input validation etc here
//check command

     try {
         client.commands.get(commandFromMessage).execute(channel, commandFromMessage, argument);
     } catch (error) {
         console.error(error);
     }

文件夹树的垃圾箱https://pastebin.com/XNJt98Ha

javascript node.js node-modules irc
1个回答
0
投票

您可以将字符串名称设置为常规对象中的键。

const channelSpecificCommands = new Map();
const channelFolder= fs.readdirSync(`./commands/{${channelSpecificDir}`);

for(const file in channelFolder) {
    const commandFromFile = require(`./commands/{${channelSpecificDir}/${file}`)
    channelSpecificCommands.set(commandFromFile.name, commandFromFile);
}

client[channelSpecificDir] = channelSpecificCommands;

关于第二个问题-为此,您应该使用.json文件而不是.js。您可以使用JSON.parse(fs.readFileSync('myjsonfile.json, 'utf8'))加载json文件来获取数据,而不会出现动态模块解析所带来的任何问题。

© www.soinside.com 2019 - 2024. All rights reserved.