Restructure dynamic command module loading

This commit is contained in:
2024-09-03 20:24:56 +00:00
parent 06ae61f8be
commit aeb6b1590b
3 changed files with 2 additions and 2 deletions

View File

@@ -1,5 +1,5 @@
import { Client, Collection, Events, GatewayIntentBits } from 'discord.js';
import { loadCommandModules } from '../lib/utilities/commandModules.js';
import { loadCommandModules } from './utilities/commandModules.js';
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

View File

@@ -1,5 +1,5 @@
import { REST, Routes } from 'discord.js';
import { loadCommandModules } from '../lib/utilities/commandModules.js';
import { loadCommandModules } from './utilities/commandModules.js';
// Register all slash commands, globally across all Guilds.
const commandModules = await loadCommandModules();

View File

@@ -0,0 +1,46 @@
import path from 'path';
import { glob } from 'glob';
import { ApplicationCommand } from 'discord.js';
/**
* Get all command modules from the commands directory.
* @returns {Promise<string[]>} The file paths of all command modules.
*/
async function getCommandModulePaths() {
return await glob(path.join(process.cwd(), 'src/commands/**/*.js'));
}
/**
* Load a single command module.
* @param {string} modulePath The path to the command module.
* @returns {Promise<ApplicationCommand>} The loaded command module.
*/
async function loadCommandModule(modulePath) {
try {
const module = await import(path.resolve(modulePath));
const commandModule = module.default;
if (!commandModule.data || !commandModule.execute) {
console.warn(`Invalid command module at ${modulePath}`);
return;
}
console.info(`Loaded command module: ${commandModule.data.name}`);
return commandModule;
} catch (error) {
console.error(`Error loading module at ${modulePath}.`, error);
}
}
/**
* Load all command modules.
* @returns {Promise<ApplicationCommand[]>} The loaded command modules.
*/
export async function loadCommandModules() {
const commandModulePaths = await getCommandModulePaths();
const commandModules = await Promise.all(
commandModulePaths.map(loadCommandModule)
);
return commandModules.filter((module) => module);
}