nhandler
Version:
The easy to use, all-in-one command, event and component handler.
198 lines (197 loc) • 9.03 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandHandler = void 0;
const fs_1 = require("fs");
const path = __importStar(require("path"));
const v10_1 = require("discord-api-types/v10");
const discord_js_1 = require("discord.js");
const ExecutionError_1 = require("../errors/ExecutionError");
const BaseHandler_1 = require("./BaseHandler");
class CommandHandler extends BaseHandler_1.BaseHandler {
constructor() {
super(...arguments);
this.commands = [];
}
commandExists(name) {
return this.commands.some((command) => command.name === name);
}
register(...commands) {
for (const command of commands) {
if (this.commandExists(command.name))
throw new Error(`Cannot register command with duplicate name: '${command.name}'.`);
this.debugLog(`Registered command ${command.name}.`);
command.client = this.client;
BaseHandler_1.commandsToRegister.push(CommandHandler.commandMapper(command));
this.commands.push(command);
this.emit("commandRegistered", command);
}
return this;
}
/**
* registerFromDir automatically loads files & creates class instances in the directory specified.
* If recurse is true, it will also load commands from subdirectories.
* Auto-load commands need to have a __default__ export. Otherwise they will be ignored.
* @param dir The directory to load files from.
* @param recurse Whether to load files from subdirectories.
* */
registerFromDir(dir, recurse = true) {
if (!this.client)
throw new Error("Client not set.");
this.debugLog("Loading commands from directory " + dir + ".");
const filesInDirectory = (0, fs_1.readdirSync)(dir);
for (const file of filesInDirectory) {
const absolutePath = path.join(dir, file);
if (recurse && (0, fs_1.statSync)(absolutePath).isDirectory()) {
this.registerFromDir(absolutePath);
}
else if (file.endsWith(".js") || file.endsWith(".ts")) {
delete require.cache[require.resolve(absolutePath)];
const defaultExport = require(absolutePath).default;
if (!defaultExport) {
this.debugLog(`File ${absolutePath} does not default-export a class. Ignoring.`);
continue;
}
const instance = new defaultExport(this.client);
if (!CommandHandler.isInstanceOfCommand(instance)) {
this.debugLog(`File ${absolutePath} does not correctly implement Command.`);
continue;
}
this.register(instance);
}
}
return this;
}
checkConditionals(event, command) {
if (command.guildId && event.guildId !== command.guildId) {
return new ExecutionError_1.ExecutionError("This command is not available in this guild.");
}
if (command.allowDm === false && event.guildId === null) {
return new ExecutionError_1.ExecutionError("This command is not available in DMs.");
}
if (command.allowedGuilds && !command.allowedGuilds.includes(event.guildId)) {
return new ExecutionError_1.ExecutionError("This command is not available in this guild.");
}
if (command.allowedUsers && !command.allowedUsers.includes(event.user.id)) {
return new ExecutionError_1.ExecutionError("You are not allowed to use this command.");
}
return undefined;
}
runCommand(event, metadata = {}) {
if (!(event instanceof discord_js_1.ChatInputCommandInteraction)) {
throw new Error("runCommand() only accepts ChatInputCommandInteraction. Use runContextMenuCommand() instead.");
}
const command = this.commands.find((command) => command.name === event.commandName);
if (!command)
return this.debugLog(`runCommand(): Command ${event.commandName} not found.`);
this.debugLog(`Running command ${command.name}.`);
/* Check preconditions, like allowedGuilds, allowedUsers etc. */
const error = this.checkConditionals(event, command);
if (error) {
this.callErrorIfPresent(command, event, error);
return;
}
if (!command.run || typeof command.run !== "function") {
return this.debugLog(`runCommand(): Command ${event.commandName} has no run() method implemented.`);
}
const promise = command.run(event, metadata);
if (!(typeof promise === "object" && promise instanceof Promise)) {
throw new Error("Command run method must return a promise.");
}
promise.catch((execError) => {
if (!(execError instanceof ExecutionError_1.ExecutionError)) {
throw execError;
}
this.callErrorIfPresent(command, event, execError);
});
}
runAutocomplete(event, metadata = {}) {
const command = this.commands.find((command) => command.name === event.commandName);
if (!command)
return this.debugLog(`runAutocomplete(): Command ${event.commandName} not found.`);
this.debugLog(`Running autocomplete for ${command.name}.`);
if (!command.autocomplete || typeof command.autocomplete !== "function") {
return this.debugLog(`runAutocomplete(): Command ${event.commandName} has no autocomplete() method implemented.`);
}
command.autocomplete(event, metadata);
}
callErrorIfPresent(command, event, error) {
if (!command.error || typeof command.error !== "function") {
return this.debugLog(`Command ${event.commandName} has no error() method implemented.`);
}
command.error(event, error);
}
static isOptionInstanceOfSubcommand(object) {
return object.options !== undefined;
}
static isInstanceOfCommand(object) {
return object.name !== undefined && object.run !== undefined && object.description !== undefined;
}
static commandMapper(command) {
return {
type: v10_1.ApplicationCommandType.ChatInput,
name: command.name,
guildId: command.guildId,
nameLocalizations: command.nameLocalizations,
dmPermission: command.allowDm,
defaultMemberPermissions: command.defaultMemberPermissions ?? null,
description: command.description,
descriptionLocalizations: command.descriptionLocalizations,
integration_types: command.integrationTypes ?? [0],
contexts: command.contexts ?? [0],
options: command.options?.map(CommandHandler.optionsMapper),
};
}
static optionsMapper(option) {
if (CommandHandler.isOptionInstanceOfSubcommand(option)) {
// Format subcommand or subcommand group
return {
type: option.type,
name: option.name,
description: option.description,
descriptionLocalizations: option.descriptionLocalizations,
options: option.options,
};
}
// Format argument option
return {
name: option.name,
nameLocalizations: option.nameLocalizations,
description: option.description,
descriptionLocalizations: option.descriptionLocalizations,
type: option.type,
required: option.required,
autocomplete: option.autocomplete,
choices: option.choices?.map((choice) => {
return {
name: choice.name,
nameLocalizations: choice.nameLocalizations,
value: choice.value,
};
}),
};
}
}
exports.CommandHandler = CommandHandler;
;