Restructure dynamic command module loading
This commit is contained in:
@@ -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] });
|
||||
|
||||
|
||||
@@ -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();
|
||||
|
||||
46
src/utilities/commandModules.js
Normal file
46
src/utilities/commandModules.js
Normal 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);
|
||||
}
|
||||
Reference in New Issue
Block a user