Discord.JS 命令处理程序子文件夹
Discord.JS Command Handler Sub-Folders
我目前有一个 Discord.JS 命令处理程序,可以加载命令文件夹中的所有命令。但是,由于所有命令,它现在变得有点混乱,因此我一直在尝试实现子文件夹。这将清理命令文件夹中的文件,将它们组织到文件夹组中。
我目前有这段代码可以在同一文件夹中加载命令。
但我对如何进入命令目录中的每个文件夹并加载命令感到困惑。
如果有人能帮助我,那将不胜感激。
const allCommands = fs.readdirSync('./commands');
for (const command of allCommands) {
try {
const loadedCommand = require(`./commands/${command}`);
commands.set(loadedCommand.name, loadedCommand);
for(const alias of loadedCommand.aliases || [])
commands.set(alias, { ...loadedCommand, alias: true });
logger.info(`Loaded command ${loadedCommand.name} (${command})`);
} catch (error) {
logger.error(`Failed to load command ${command}. **Please report the following error:**`);
logger.error(error);
}
}
老实说,我不建议以这种方式导入。如果您将每个命令导入一个单独的 javascript 文件然后从那里导出每个命令,您可能会更幸运,它应该使您的控制器级别代码更容易阅读
将路径作为参数移动到它自己的函数中。
每次找到一个文件夹,用文件夹路径调用函数。
(function readdir(path='./commands') {
const allCommands = fs.readdirSync(path);
for (const command of allCommands) {
if(fs.statSync(`${path}/${command}`).isDirectory()) {
readdir(`${path}/${command}`);
continue;
}
try {
const loadedCommand = require(`${path}/${command}`);
commands.set(loadedCommand.name, loadedCommand);
for(const alias of loadedCommand.aliases || [])
commands.set(alias, { ...loadedCommand, alias: true });
logger.info(`Loaded command ${loadedCommand.name} (${path}/${command})`);
} catch (error) {
logger.error(`Failed to load command ${path}/${command}. **Please report the following error:**`);
logger.error(error);
}
}
})();
我目前有一个 Discord.JS 命令处理程序,可以加载命令文件夹中的所有命令。但是,由于所有命令,它现在变得有点混乱,因此我一直在尝试实现子文件夹。这将清理命令文件夹中的文件,将它们组织到文件夹组中。
我目前有这段代码可以在同一文件夹中加载命令。
但我对如何进入命令目录中的每个文件夹并加载命令感到困惑。 如果有人能帮助我,那将不胜感激。
const allCommands = fs.readdirSync('./commands');
for (const command of allCommands) {
try {
const loadedCommand = require(`./commands/${command}`);
commands.set(loadedCommand.name, loadedCommand);
for(const alias of loadedCommand.aliases || [])
commands.set(alias, { ...loadedCommand, alias: true });
logger.info(`Loaded command ${loadedCommand.name} (${command})`);
} catch (error) {
logger.error(`Failed to load command ${command}. **Please report the following error:**`);
logger.error(error);
}
}
老实说,我不建议以这种方式导入。如果您将每个命令导入一个单独的 javascript 文件然后从那里导出每个命令,您可能会更幸运,它应该使您的控制器级别代码更容易阅读
将路径作为参数移动到它自己的函数中。 每次找到一个文件夹,用文件夹路径调用函数。
(function readdir(path='./commands') {
const allCommands = fs.readdirSync(path);
for (const command of allCommands) {
if(fs.statSync(`${path}/${command}`).isDirectory()) {
readdir(`${path}/${command}`);
continue;
}
try {
const loadedCommand = require(`${path}/${command}`);
commands.set(loadedCommand.name, loadedCommand);
for(const alias of loadedCommand.aliases || [])
commands.set(alias, { ...loadedCommand, alias: true });
logger.info(`Loaded command ${loadedCommand.name} (${path}/${command})`);
} catch (error) {
logger.error(`Failed to load command ${path}/${command}. **Please report the following error:**`);
logger.error(error);
}
}
})();