nhandler
Version:
The easy to use, all-in-one command, event and component handler.
163 lines (162 loc) • 7.54 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.LegacyCommandHandler = void 0;
const fs_1 = require("fs");
const path = __importStar(require("path"));
const discord_js_1 = require("discord.js");
const ExecutionError_1 = require("../errors/ExecutionError");
const BaseHandler_1 = require("./BaseHandler");
/*
* MAKE SURE TO ADD
* IntentsBitField.Flags.GuildMessages, IntentsBitField.Flags.MessageContent
* TO THE BITFIELD LIST
* */
class LegacyCommandHandler extends BaseHandler_1.BaseHandler {
constructor(prefixes, debug) {
super(debug);
this.legacyCommands = [];
this.prefixes = [];
this.prefixes = prefixes;
}
commandExists(name) {
return this.legacyCommands.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;
this.legacyCommands.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 (!LegacyCommandHandler.isInstanceOfLegacyCommand(instance)) {
this.debugLog(`File ${absolutePath} does not correctly implement LegacyCommand.`);
continue;
}
this.register(instance);
}
}
return this;
}
checkConditionals(message, legacyCommand) {
if (legacyCommand.guildId && message.guildId !== legacyCommand.guildId) {
return new ExecutionError_1.ExecutionError("This command is not available in this guild.");
}
if (legacyCommand.allowDm === false && message.guildId === null) {
return new ExecutionError_1.ExecutionError("This command is not available in DMs.");
}
if (legacyCommand.allowedGuilds && !legacyCommand.allowedGuilds.includes(message.guildId)) {
return new ExecutionError_1.ExecutionError("This command is not available in this guild.");
}
if (legacyCommand.allowedUsers && !legacyCommand.allowedUsers.includes(message.author.id)) {
return new ExecutionError_1.ExecutionError("You are not allowed to use this command.");
}
return undefined;
}
validateArgs(args, rules) {
if (args.length < rules.filter((rule) => rule.required).length) {
return new ExecutionError_1.ExecutionError("Missing required arguments.");
}
if (!rules.some((r) => r.spread) && args.length > rules.length) {
return new ExecutionError_1.ExecutionError("Too many arguments.");
}
return undefined;
}
setPrefixes(prefixes) {
this.prefixes = prefixes;
}
runLegacyCommand(event, metadata = {}) {
if (!(event instanceof discord_js_1.Message)) {
throw new Error("runLegacyCommand() only accepts Message as its first argument.");
}
const [commandNameWithPrefix, ...args] = event.content.split(" ");
const prefix = this.prefixes.find((prefix) => commandNameWithPrefix.startsWith(prefix));
if (!prefix)
return;
const commandName = commandNameWithPrefix.slice(prefix.length);
const command = this.legacyCommands.find((command) => command.name === commandName);
if (!command)
return this.debugLog(`runLegacyCommand(): Legacy command ${commandName} not found.`);
this.debugLog(`Running legacy command ${command.name}.`);
const error = this.checkConditionals(event, command);
// const error2 = this.validateArgs(args, command.args || []);
if (error /*|| error2*/) {
this.callErrorIfPresent(command, args, event, error /* || error2*/);
return;
}
if (!command.run || typeof command.run !== "function") {
return this.debugLog(`runLegacyCommand(): Legacy command ${commandName} has no run() method implemented.`);
}
const promise = command.run(event, args, metadata);
if (!(typeof promise === "object" && promise instanceof Promise)) {
throw new Error("Legacy command run method must return a promise.");
}
promise.catch((execError) => {
if (!(execError instanceof ExecutionError_1.ExecutionError)) {
throw execError;
}
this.callErrorIfPresent(command, args, event, execError);
});
}
static isInstanceOfLegacyCommand(object) {
return object.name !== undefined && object.run !== undefined && object.description !== undefined;
}
callErrorIfPresent(command, args, event, error) {
if (!command.error || typeof command.error !== "function") {
return this.debugLog(`Command ${command.name} has no error() method implemented.`);
}
command.error(event, args, error);
}
}
exports.LegacyCommandHandler = LegacyCommandHandler;
;