♻️ Command Handler

This commit is contained in:
Axel Olausson Holtenäs 2022-10-24 01:51:51 +02:00
parent 5d1f8e4569
commit 048f8bade9
No known key found for this signature in database
GPG key ID: BEDBB4D61E6C8462

View file

@ -1,54 +1,34 @@
/* eslint-disable no-loops/no-loops */
import { Client } from "discord.js"; import { Client } from "discord.js";
import listDir from "../../helpers/checkDirectory"; import checkDirectory from "../../helpers/checkDirectory";
import { ICommand } from "../../interfaces/Command"; import { ICommand } from "../../interfaces/Command";
import logger from "../../middlewares/logger"; import logger from "../../middlewares/logger";
export const register = async (client: Client) => { export const register = async (client: Client) => {
// Get name of directories containing commands logger.info("🔧 Started command management");
const commandNames = await listDir("commands");
if (!commandNames) throw new Error("📦 No commands available");
const amountOfCommands = commandNames.length; const commandNames = await checkDirectory("commands");
let importedCommandAmount = 0; if (!commandNames) return logger.warn("No available commands found");
logger.info(`📦 Trying to load ${amountOfCommands} commands`);
const importCommand = async (commandName: string) => { const totalCommands = commandNames.length;
// Import command from commands let loadedCommands = 0;
const command: ICommand = await import(`../../commands/${commandName}`);
if (!command) logger.info(`🔧 Loading ${totalCommands} commands`);
throw new Error(`📦 No command found while importing "${commandName}"`);
if (!command.builder) const importCommand = async (name: string) => {
throw new Error( const command: ICommand = await import(`../../commands/${name}`);
`📦 No command builder found while importing "${commandName}"`
);
// Add command to collection
client.commands.set(command.builder.name, command); client.commands.set(command.builder.name, command);
importedCommandAmount += 1; loadedCommands++;
}; };
// Send log message when it's done loading commands for await (const commandName of commandNames) {
const doneImporting = () => {
if (importedCommandAmount !== amountOfCommands) {
return logger.warn(
`📦 Failed importing ${
amountOfCommands - importedCommandAmount
} of ${amountOfCommands} commands`
);
}
return logger.info(`📦 Managed to load all commands`);
};
// Start importing commands
commandNames.forEach(async (commandName: string, index: number) => {
await importCommand(commandName).then(() => { await importCommand(commandName).then(() => {
logger.debug(`📦 Imported the "${commandName}" command`); logger.verbose(`🔧 Loaded command "${commandName}"`);
}); });
// If done importing if (loadedCommands === totalCommands) {
if (index + 1 === amountOfCommands) { logger.info("🔧 All commands loaded");
await doneImporting();
} }
}); }
}; };