Remix — the complete rewrite

Upgrades the bot from fluxerjs 2.2 to 3.0 and restructures everything
into a layered architecture (~28K lines):

Dependencies:
- @fluxerjs/core, util, voice: ^2.2.0 -> ^3.0.0 (typed events,
  PartialMessage payloads, camelCase API)
- @fluxerjs/sharding ^3.0.0 added — built-in sharding mode
  (shard.mjs, one process per shard)
- @discordjs/opus dropped — opusscript + prism-media cover encoding

Architecture:
- commands: every command split into submodules (player, lastfm,
  settings, debug) with a shared CommandBuilder/Loader/Handler core
- ui: embeds, paginators, help command, permission checks
- voice: gateway event routing, rejoin/247 boot recovery, state resolver
- music: player split into Queue/Search/Playback/Display mixins,
  stream pipeline + WebM/Opus muxer (no FFmpeg needed)
- dashboard: Redis pub/sub, RPC handlers, serializers
- db: MySQL manager + per-guild settings
- services: LastFm manager split into focused mixins
- utils: sharding, 24/7 helpers, API client

Runtime fixes over v2:
- Redis v5 reconnect: capped numeric backoff (0.5s ramp to 15s),
  never exhausts, auto-recovers when the server comes back
- Redis main/subscriber clients connect in parallel; clean shutdown
- Logger storm guard: identical error/warn lines deduped in a 60s window
- self-deaf fix on voice join
- config example uses redis://127.0.0.1 (avoids IPv6 ENETUNREACH)

Housekeeping: dead code removed (Tuna.mjs + follow-redirects dep),
.gitignore added (config.json, .env, node_modules, runtime state).
This commit is contained in:
NoLogicAlan committed 2026-09-09 02:04:33 +03:00
1 parent 0f085a6ae4
commit 253d11cd57
150 files changed
+19935 -16894

No files matched your search

+166
View File
@@ -0,0 +1,166 @@
/**
* @module src/commands/CommandBuilder
* @description Fluent builder for command definitions (name, description,
* options, subcommands, aliases, requirements) plus the permission
* requirement model.
*/
import { Utils } from "../utils/Utils.mjs";
import { Option } from "./Option.mjs";
/**
* @class CommandRequirement
* @description Permission and owner-only gating for a command.
*/
export class CommandRequirement {
/** @type {boolean} Whether the command is restricted to bot owners. */
ownerOnly = false;
/** Create a new CommandRequirement with no permissions. */
constructor() {
this.permissions = [];
this.permissionError = "You don't have the needed permissions to run this command!";
return this;
}
/** @param {boolean} bool @returns {CommandRequirement} */
setOwnerOnly(bool) { this.ownerOnly = bool; return this; }
/** @param {string} p @returns {CommandRequirement} */
addPermission(p) { this.permissions.push(p); return this; }
/** @param {...string} p @returns {CommandRequirement} */
addPermissions(...p) { this.permissions.push(...p); return this; }
/**
* @returns {string[]} The permission list (with an owner note appended when
* the requirement is owner-only).
*/
getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; }
/** @param {string} e @returns {CommandRequirement} */
setPermissionError(e) { this.permissionError = e; return this; }
}
/**
* @class CommandBuilder
* @description Fluent builder for constructing command definitions with name,
* description, options, subcommands, aliases, requirements and examples.
*/
export class CommandBuilder {
/** Create a new CommandBuilder with default empty state. */
constructor() {
this.name = null;
this.description = null;
this.id = null;
this.aliases = [];
this.subcommands = [];
this.options = [];
this.requirements = [];
this.category = "default";
this.examples = [];
this.uid = Utils.uid();
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
this.parent = null;
}
/** Set the command name and register it as the primary alias. @param {string} n @returns {CommandBuilder} */
setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; }
/** Set the command description. @param {string} d @returns {CommandBuilder} */
setDescription(d) { this.description = d; return this; }
/** Set the command ID. @param {string} id @returns {CommandBuilder} */
setId(id) { this.id = id; return this; }
/** @returns {string} Full command path including parent chain (e.g. "music play"). */
get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; }
/**
* Add a permission/owner-only requirement via a callback.
* @param {Function} config - Callback receiving a fresh {@link CommandRequirement}.
* @returns {CommandBuilder}
*/
setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; }
/**
* Add a subcommand builder via a callback.
* @param {Function} config - Callback receiving a fresh {@link CommandBuilder}.
* @returns {CommandBuilder}
*/
addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; }
/**
* Add a string option.
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
*/
addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; }
/**
* Add a number option.
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
*/
addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; }
/**
* Add a boolean option.
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
*/
addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; }
/**
* Add a channel option.
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
*/
addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; }
/**
* Add a voice-channel option.
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
*/
addVoiceChannelOption(config, flag = false) { this.options.push(config(Option.create("voiceChannel", flag))); return this; }
/**
* Add a user option.
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
*/
addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; }
/**
* Add a text (remaining-args) option. Only one is allowed per command.
* @param {Function} config
* @returns {CommandBuilder}
* @throws {Error} If a text option already exists.
*/
addTextOption(config) {
if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option.");
this.options.push(config(new Option("text")));
return this;
}
/**
* Add a choice (enum-like) option.
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
*/
addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; }
/**
* Add an alias (case-insensitive, duplicates ignored).
* @param {string} alias
* @returns {CommandBuilder}
*/
addAlias(alias) {
if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this;
this.aliases.push(alias.toLowerCase());
return this;
}
/**
* Add multiple aliases.
* @param {...string} aliases
* @returns {CommandBuilder}
*/
addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; }
/** Set the command category (used by help grouping). @param {string} cat @returns {CommandBuilder} */
setCategory(cat) { this.category = cat; return this; }
/**
* Add usage examples.
* @param {...string} examples
* @returns {CommandBuilder}
*/
addExamples(...examples) { this.examples.push(...examples); return this; }
}
+569
View File
@@ -0,0 +1,569 @@
/**
* @module src/commands/CommandHandler
* @description The command dispatcher: parses incoming messages, matches
* commands and aliases, validates options/flags, enforces permissions and
* per-user cooldowns, and emits "run" events consumed by the CommandLoader.
*/
import { EventEmitter } from "node:events";
import { PermissionFlags } from "@fluxerjs/core";
import { logger } from "../core/Logger.mjs";
import { Utils } from "../utils/Utils.mjs";
import { Message, REQUIRED_BOT_PERMISSIONS } from "../ui/index.mjs";
import { Option, Flag } from "./Option.mjs";
import { HelpHandler } from "./HelpHandler.mjs";
import { PrefixManager } from "./PrefixManager.mjs";
/** @type {string[]} Option types whose quoted values may span multiple tokens. */
const QUOTABLE_TYPES = ["string", "text", "channel", "voiceChannel"];
/**
* @class CommandHandler
* @description Main command dispatcher.
* @extends {EventEmitter}
*
* Events:
* - `"command"` — emitted with `{ command, message }` when a command starts.
* - `"run"` — emitted with the fully parsed run payload (see processCommand).
*/
export class CommandHandler extends EventEmitter {
/** @type {Function|null} Custom handler when the bot is pinged. */
onPing = null;
/** @type {boolean} Whether the bot responds to pings as a prefix. */
pingPrefix = true;
/** @type {string[]} Bot owner user IDs. */
owners = [];
/** @type {import('../ui/MessageHandler.mjs').MessageHandler} */
messages;
client;
/** @type {PrefixManager} */
prefixes;
/** @type {HelpHandler} */
helpHandler;
/** @type {string[]} All registered command aliases. */
commandNames = [];
/** @type {import('./CommandBuilder.mjs').CommandBuilder[]} Registered commands. */
commands = [];
/** @type {object|null} Locale manager. */
locale = null;
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`";
textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string.";
/** @private @type {Map<string, number>} Per-user last command timestamps for cooldown enforcement. */
_cmdCooldowns = new Map();
/** @private @type {number} Cooldown duration in ms between commands per non-owner user. */
_cmdCooldownMs = 1500;
/**
* @param {import('../ui/MessageHandler.mjs').MessageHandler} handler
* @param {string} [prefix="%"]
*/
constructor(handler, prefix = "%") {
super();
this.messages = handler;
this.client = handler.client;
this.prefix = prefix;
this.helpHandler = new HelpHandler(this);
this.helpCommand = "help";
this.replyHandler = (message, msg) => {
msg.reply(this.format(message, msg.channel.channel.guildId));
};
this.messages.onMessage(this.messageHandler.bind(this));
}
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
getPrefix(guildId) { return this.prefixes.getPrefix(guildId); }
/** Enable or disable ping-as-prefix. @param {boolean} bool */
setPingPrefix(bool) { this.pingPrefix = bool; }
/** @param {PrefixManager} manager */
setPrefixManager(manager) { this.prefixes = manager; }
/** @param {HelpHandler} handler */
setHelpHandler(handler) { this.helpHandler = handler; }
/** @param {object} locale */
setLocale(locale) { this.locale = locale; }
/**
* Translate a locale key.
* @param {string} guildId
* @param {string} key
* @param {object} [replacements={}]
* @returns {string}
*/
t(guildId, key, replacements = {}) {
if (!this.locale) return key;
return this.locale.translate(guildId, key, replacements);
}
/**
* Replace $prefix and $helpCmd placeholders in text.
* @param {string} text
* @param {string} guildId
* @returns {string}
*/
format(text, guildId) {
const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId);
return text
.replace(/\$prefix/gi, prefix)
.replace(/\$helpCmd/gi, this.helpCommand);
}
/**
* Remove a command from the registry.
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
*/
removeCommand(command) {
command.aliases.forEach(a => {
const idx = this.commandNames.indexOf(a);
if (idx !== -1) this.commandNames.splice(idx, 1);
});
const idx = this.commands.findIndex(c => c.uid === command.uid);
if (idx !== -1) this.commands.splice(idx, 1);
}
/**
* @private Handle an incoming message and route it to command processing.
* Handles bare pings, prefix detection, cooldowns and the built-in help.
* @param {Message} msg
*/
messageHandler(msg) {
if (!msg || !msg.content) return;
const trimmed = msg.content.trim();
if (/^<@!?\d+>$/.test(trimmed)) {
const botId = this.client.user?.id;
if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) {
return this.onPing?.(msg);
}
return;
}
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const prefix = this.getPrefix(guildId);
const ping = `<@${this.client.user?.id}>`;
const pingBang = `<@!${this.client.user?.id}>`;
if (!(msg.content.startsWith(prefix) || msg.content.startsWith(ping) || msg.content.startsWith(pingBang))) return;
if (this._isCoolingDown(msg)) return;
this._enforceCooldown(msg);
const len = msg.content.startsWith(prefix) ? prefix.length : (msg.content.startsWith(pingBang) ? pingBang.length : ping.length);
const args = msg.content.slice(len).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
if (!args[0]) return;
if (args[0] === this.helpCommand) {
return this._handleHelpInvocation(args, guildId, msg);
}
if (!this.commandNames.includes(args[0].toLowerCase())) {
this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix$helpCmd", guildId) }), msg);
return;
}
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
}
/**
* @private Apply the per-user cooldown gate: records the timestamp for the
* invoking user and prunes the cooldown map when it grows too large.
* Owners are exempt.
* @param {Message} msg
*/
_enforceCooldown(msg) {
const userId = msg.message?.author?.id ?? msg.author?.id;
if (!userId || this.owners.includes(userId)) return;
const now = Date.now();
this._cmdCooldowns.set(userId, now);
if (this._cmdCooldowns.size > 500) {
const cutoff = now - this._cmdCooldownMs * 2;
for (const [uid, ts] of this._cmdCooldowns) {
if (ts < cutoff) this._cmdCooldowns.delete(uid);
}
}
}
/**
* @private Cooldown gate — returns true when the user invoked a command too
* recently and the message should be dropped (owners are exempt).
* @param {Message} msg
* @returns {boolean}
*/
_isCoolingDown(msg) {
const userId = msg.message?.author?.id ?? msg.author?.id;
if (!userId || this.owners.includes(userId)) return false;
const now = Date.now();
const last = this._cmdCooldowns.get(userId) ?? 0;
return (now - last) < this._cmdCooldownMs;
}
/**
* @private Built-in `%help` invocation handling (bare / page / command / subcommand path).
* @param {string[]} args
* @param {string} guildId
* @param {Message} msg
*/
_handleHelpInvocation(args, guildId, msg) {
if (!args[1]) {
const res = this.helpHandler.help(msg);
return (typeof res === "string") ? this.replyHandler(res, msg) : undefined;
}
if (args.length > 1 && Utils.isNumber(args[1])) {
const pageNumber = parseInt(args[1]);
if (pageNumber < 1 || pageNumber > this.helpHandler.pageNumber()) {
return this.replyHandler(this.t(guildId, "cmdHandler.page.invalid", { number: pageNumber }), msg);
}
return this.replyHandler(this.helpHandler.getHelpPage(pageNumber - 1, msg), msg);
}
if (args.length <= 2) {
let idx = this.commands.findIndex(e => e.aliases.some(al => al.toLowerCase() === args[1].toLowerCase()));
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + args[1], guildId) }), msg);
return this.replyHandler(this.helpHandler.getCommandHelp(this.commands[idx], msg), msg);
}
let currCmd = null;
let prefix2 = "";
for (let i = 0; i < args.slice(1).length; i++) {
let a = args.slice(1)[i];
let curr = (currCmd) ? currCmd.subcommands : this.commands;
let idx = curr.findIndex(e => e.aliases.some(al => al.toLowerCase() === a.toLowerCase()));
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + prefix2 + a, guildId) }), msg);
currCmd = curr[idx];
prefix2 += a + " ";
}
return this.replyHandler(this.helpHandler.getCommandHelp(currCmd, msg), msg);
}
/**
* Parse and execute a command with its options.
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
* @param {string[]} args
* @param {Message} msg
* @param {string|boolean} [previous=false] - The command path so far (for error messages).
* @param {boolean} [external=false] - When true, errors are returned instead of replied.
* @returns {object|undefined} The command run payload.
*/
processCommand(cmd, args, msg, previous = false, external = false) {
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
if (!external) {
const channel = msg.channel?.channel ?? msg.channel;
if (channel?.guild) {
const botPermResult = this.messages.checkAllBotPermissions(channel);
if (botPermResult.criticalMissing.length > 0) {
const permEmbed = this.messages.buildPermissionEmbed(botPermResult.missing, channel.guildId);
try {
msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false });
} catch (_) {
try {
const names = botPermResult.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
msg.message?.reply?.("I'm missing critical permissions: **" + names.join("**, **") + "**. Ask an admin to fix this.", { ping: false });
} catch (__) { logger.warn("[CommandHandler] Fallback perm reply failed"); }
}
return;
}
}
}
if (cmd.requirements.length > 0 && !external) {
if (!this.assertRequirements(cmd, msg)) return;
}
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
if (!external) this.emit("command", { command: cmd, message: msg });
if (cmd.subcommands.length !== 0) {
const idx = cmd.subcommands.findIndex(el => {
if (!args[1]) return false;
return el.name.toLowerCase() === args[1].toLowerCase();
});
if (idx === -1) {
const list = cmd.subcommands.map(s => s.name).join(" | ");
const subGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const e = this.t(subGuildId, "cmdBuilder.subcommand.invalid").replace(/\$previousCmd/gi, previous).replace(/\$cmdList/gi, list);
return (!external) ? this.replyHandler(e, msg) : e;
}
return this.processCommand(cmd.subcommands[idx], args.slice(1), msg, previous + this.format(" " + cmd.subcommands[idx].name), external);
}
// `error === true` → internal invocation: the error reply was already
// sent by _parseOptions and, exactly like the original monolith, the
// command must NOT run (no "run" emission). A string is the external-
// mode error, returned to the caller as before.
const { opts, error } = this._parseOptions(cmd, args, msg, previous, external);
if (error) return (error === true) ? undefined : error;
const commandRunData = {
command: cmd,
commandId: cmd.id,
options: opts,
message: msg,
get: function (oName) { return this.options.find(o => o.name === oName); },
getById: function (id) { return this.options.find(o => o.id === id); }
};
if (!external) this.emit("run", commandRunData);
return commandRunData;
}
/**
* @private Parse positional options, flags, quoted values and text options.
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
* @param {string[]} args
* @param {Message} msg
* @param {string} previous
* @param {boolean} external
* @returns {{opts: Array, error: *}} Parsed options or a handled error:
* `null` on success; `true` when an internal (non-external) invocation
* already sent its error reply and the caller must stop (the original
* monolith exited processCommand directly at these points); the error
* string for external invocations at the option/flag validation sites
* (textWrap sites always reply, matching the original's always-reply quirk).
*/
_parseOptions(cmd, args, msg, previous, external) {
const opts = [];
const texts = [];
/**
* Collect quoted arguments spanning multiple tokens.
* @param {number} index
* @param {string} currVal
* @param {string[]} as
* @returns {{args: string[], index: number}|null}
*/
const collectArguments = (index, currVal, as) => {
const lastChar = currVal.charAt(currVal.length - 1);
if (lastChar === '"') return { args: as, index };
const a = args[++index];
if (!a) return null;
as.push(a);
return collectArguments(index, a, as);
};
const options = cmd.options.slice().sort((a, b) => {
const aText = (a.type === "text") ? 1 : 2;
const bText = (b.type === "text") ? 1 : 2;
return aText - bText;
});
const usedOptions = [];
let usedArgumentCount = 0;
for (let i = 0, argIndex = 1; i < options.length; i++) {
const o = options[i];
if (o?.type === "text") { texts.push(o); continue; }
if ((args[argIndex] || "").startsWith("-")) {
const flagName = args[argIndex].slice(1);
const op = cmd.options.find(e => e.aliases.includes(flagName));
if (!op) {
const flagGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const error = this.t(flagGuildId, "cmdHandler.invalidFlag").replace(/\$previousCmd/gi, previous).replace(/\$invalidFlag/gi, "-" + flagName);
return { opts, error: (!external) ? (this.replyHandler(error, msg) ?? true) : error };
}
previous += " " + args[argIndex];
let value = args[++argIndex];
if ((value || "").startsWith('"') && (QUOTABLE_TYPES.includes(op.type))) {
const data = collectArguments(argIndex, value, [value]);
if (!data) {
const twGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
return { opts, error: (this.replyHandler(this._textWrapErrorMsg(twGuildId, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg) ?? true) };
}
argIndex += data.index - argIndex;
const _joined = data.args.join(" ");
value = _joined.slice(1, _joined.length - 1);
}
argIndex++;
i--;
const valid = op.validateInput(value, this.client, msg.message);
if (!valid && (op.required || !op.empty(value))) {
const errGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const e = this._optionTypeError(errGuildId, op, value, previous);
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
}
usedArgumentCount += 2;
previous += " " + value;
opts.push({ value: op.formatInput(value, this.client, msg.message), name: op.name, id: op.id, uid: op.uid });
usedOptions.push(op.uid);
continue;
}
if (!o) continue;
if (o instanceof Flag) continue;
if (opts.findIndex(op => op.uid === o.uid) !== -1) continue;
let value = args[argIndex];
if ((args[argIndex] || "").startsWith('"') && (QUOTABLE_TYPES.includes(o.type))) {
const data = collectArguments(argIndex, args[argIndex], [args[argIndex]]);
if (!data) {
const twGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
return { opts, error: (this.replyHandler(this._textWrapErrorMsg(twGuildId2, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg) ?? true) };
}
argIndex += data.index - argIndex;
value = data.args.join(" ");
value = value.slice(1, value.length - 1);
}
let valid = o.validateInput(value, this.client, msg.message);
if (!valid && o.dynamicDefault) {
value = o.dynamicDefault(this.client, msg);
valid = o.validateInput(value, this.client, msg.message);
}
if (!valid && (o.required || !o.empty(value))) {
const errGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const e = this._optionTypeError(errGuildId2, o, value, previous);
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
}
if (o.empty(value)) value = o.defaultValue;
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
usedOptions.push(o.uid);
previous += " " + value;
argIndex++;
usedArgumentCount++;
}
if (texts.length > 0) {
let o = texts[0];
let text = args.slice(usedArgumentCount + 1).join(" ");
if (o.required && !o.validateInput(text, this.client, msg.message)) {
const textErrGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
let e = this._optionTypeError(textErrGuildId, o, text, previous);
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
}
const quote = (['"', "'"].includes(text.charAt(0))) ? text.charAt(0) : null;
if (quote && text.charAt(text.length - 1) === quote) text = text.slice(1, text.length - 1);
opts.push({ name: o.name, value: text, id: o.id, uid: o.uid });
usedOptions.push(o.uid);
}
options.filter(o => !usedOptions.includes(o.uid)).forEach(o => {
if (!o.defaultValue) return;
opts.push({ name: o.name, value: o.defaultValue, id: o.id, uid: o.uid });
});
return { opts, error: null };
}
/**
* Check whether the message author meets all command requirements
* (owner-only, guild permissions). When member data must be fetched over
* REST, re-invokes processCommand asynchronously once resolved.
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
* @param {Message} msg
* @returns {boolean}
*/
assertRequirements(cmd, msg) {
const authorId = msg.message?.author?.id;
const isOwner = this.owners.includes(authorId);
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
for (let i = 0; i < cmd.requirements.length; i++) {
let req = cmd.requirements[i];
if (req.ownerOnly && !isOwner) return false;
if (req.permissions.length > 0 && !isOwner) {
const guild = msg.message?.guild ?? null;
if (!guild) {
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
return false;
}
const member = guild.members.get(authorId) ?? null;
if (member?.permissions) {
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
if (missing.length > 0) {
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
return false;
}
} else {
const fetchPromise = typeof guild.fetchMember === "function"
? guild.fetchMember(authorId)
: typeof guild.members?.fetch === "function"
? guild.members.fetch(authorId)
: Promise.reject(new Error("No member fetch API available"));
fetchPromise.then(member => {
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
if (missing.length > 0) {
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
} else {
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
const prefix2 = this.getPrefix(guildId2);
const rawContent = msg.message.content;
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
this.processCommand(cmd, args, msg, false, true);
}
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
return false;
}
}
}
return true;
}
/**
* Validate an input for a given option type.
* @param {string} type
* @param {*} i
* @param {object} m
* @returns {boolean}
*/
validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); }
/**
* Format an input for a given option type.
* @param {string} type
* @param {*} i
* @param {object} m
* @returns {*}
*/
formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); }
/**
* @private Build a type-error message for an option.
* @param {string} guildId
* @param {Option} option
* @param {*} value
* @param {string} previous
* @returns {string}
*/
_optionTypeError(guildId, option, value, previous) {
if (option.tError) {
return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
}
const localeKey = option.type === 'choice' ? 'cmdBuilder.option.invalidChoice'
: (option.type === 'channel' || option.type === 'voiceChannel') ? 'cmdBuilder.option.invalidChannel'
: 'cmdBuilder.option.invalidType';
const choiceStr = option.type === 'choice'
? (option.choices.length > Option.THRESHOLD ? Option.formatChoicesCompact(option.choices) : option.choices.map(c => '- ' + c).join('\n'))
: '';
return this.t(guildId, localeKey, {
$currValue: value,
$optionName: option.name,
$type: option.type,
$choices: choiceStr
}).replace(/\$previousCmd/gi, previous);
}
/**
* @private Build a text-wrap error message.
* @param {string} guildId
* @param {string} value
* @param {string} quote
* @returns {string}
*/
_textWrapErrorMsg(guildId, value, quote) {
return this.t(guildId, 'cmdHandler.textWrapError', { $value: value, $quote: quote });
}
/**
* Register a command builder and sort the command list alphabetically.
* @param {import('./CommandBuilder.mjs').CommandBuilder} builder
* @returns {import('./CommandBuilder.mjs').CommandBuilder[]}
*/
addCommand(builder) {
this.commandNames.push(...builder.aliases);
this.commands.push(builder);
this.commands.sort((a, b) => {
let A = a.name.toUpperCase();
let B = b.name.toUpperCase();
return (A < B) ? -1 : (A > B) ? 1 : 0;
});
return this.commands;
}
}
+123
View File
@@ -0,0 +1,123 @@
/**
* @module src/commands/CommandLoader
* @description Dynamically loads command modules from a directory, registers
* their builders, and binds run handlers with error capture + error-id replies.
*/
import { pathToFileURL } from "node:url";
import path from "node:path";
import * as fs from "node:fs";
import { logger } from "../core/Logger.mjs";
import { Utils } from "../utils/Utils.mjs";
/**
* @class CommandLoader
* @description Loads command files from a directory, registers builders with
* the CommandHandler, and dispatches "run" events to the matching run function.
*
* Command module shape (both shapes are accepted):
* - `export const command` (builder or builder-factory), `export const run`
* - default export object with the same keys
* - optional `exportDef: { name, object }` registers a global on the context
*/
export class CommandLoader {
/** @type {import('./CommandHandler.mjs').CommandHandler} */
commands;
/** @type {Map<string, string>} Command UID → file path. */
commandFiles = new Map();
/** @type {Map<string, Function>} Command UID → run function. */
runnables = new Map();
/** @type {object} Shared context (the bot instance). */
context;
/**
* @param {import('./CommandHandler.mjs').CommandHandler} commands
* @param {object} context - Bot context object (gets loader/runnables refs attached).
*/
constructor(commands, context) {
this.commands = commands;
this.context = context;
this.context.loader ??= this;
this.context.commandFiles = this.commandFiles;
this.context.runnables = this.runnables;
this.commands.on("run", (data) => {
if (!this.runnables.has(data.command.uid)) return;
const runFc = this.runnables.get(data.command.uid);
const sendErrorReply = (id) => {
Promise.resolve(data.message.reply("An error occurred. Error id: `#" + id + "`"))
.catch(err => logger.warn("[CommandHandler] Failed to send error-reply; error id #" + id + ":", err?.message));
};
try {
const result = runFc.call(this.context, data.message, data);
if (result && typeof result.catch === "function") {
result.catch(e => {
const id = Utils.uid();
logger.error("Error running command; error id #" + id, e);
sendErrorReply(id);
});
}
} catch (e) {
const id = Utils.uid();
logger.error("Error running command; error id #" + id, e);
sendErrorReply(id);
}
});
}
/**
* Normalize a module export to `{ command, run, exportDef }`.
* @param {object} cData
* @returns {object}
*/
canonData(cData) {
if (cData.command !== undefined) {
return {
command: cData.command,
run: cData.run,
exportDef: cData.exportDef ?? cData.export ?? null
};
}
const d = cData.default ?? cData;
return {
command: d.command,
run: d.run,
exportDef: d.exportDef ?? d.export ?? null
};
}
/**
* @async Load all command files from a directory.
* @param {string} dir
* @returns {Promise<undefined[]>}
*/
loadFromDir(dir) {
const files = fs.readdirSync(dir)
.filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs")));
return Promise.all(files.map(async commandFile => {
const file = path.join(dir, commandFile);
const cData = this.canonData(await import(pathToFileURL(file).href));
const builder = (typeof cData.command === "function")
? cData.command.call(this.context)
: cData.command;
if (!builder) return logger.warn("No builder returned. Skipping '" + commandFile + "'");
if (cData.exportDef)
this.context[cData.exportDef.name] = cData.exportDef.object;
this.commands.addCommand(builder);
this.commandFiles.set(builder.uid, file);
if (!cData.run) return;
this.runnables.set(builder.uid, cData.run);
builder.subcommands.forEach(sub => {
this.runnables.set(sub.uid, cData.run);
});
}));
}
}
+203
View File
@@ -0,0 +1,203 @@
/**
* @module src/commands/HelpHandler
* @description Text-based help generation: paginated command lists, per-command
* usage/aliases/options rendering. Used as the default help renderer behind
* `%help <n>` (the rich tabbed help lives in src/ui/HelpCommand.mjs).
*/
import { PageBuilder } from "../ui/Paginators.mjs";
import { Option, Flag } from "./Option.mjs";
/**
* @class HelpHandler
* @description Generates paginated help text for commands.
*/
export class HelpHandler {
/** @type {import('./CommandHandler.mjs').CommandHandler} */
commands;
/** @type {number} Commands per help page. */
commandsPerPage = 5;
/**
* Default pagination handler that builds paginated help pages.
* @param {object} msg - Message wrapper with message data.
* @param {HelpHandler} helpHandler
* @param {Array} cmds
* @returns {string|null}
*/
paginationHandler = (msg, helpHandler, cmds) => {
const guildId = msg.message.guildId;
let form = this.commands.t(guildId, "cmdHandler.help.pageStructure");
const contents = cmds.map((cmd, i) => {
return (i + 1) + ". **" + cmd.name + "**: " + (cmd.description || "").split("\n")[0];
});
const pages = new PageBuilder(contents)
.setForm(helpHandler.commands.format(form, msg.message.guildId))
.setMaxLines(helpHandler.commandsPerPage);
helpHandler.commands.messages.initPagination(pages, msg);
return null;
}
/** @type {Function|null} Custom help handler function override. */
customHelpHandler = null;
/** @param {import('./CommandHandler.mjs').CommandHandler} commands */
constructor(commands) { this.commands = commands; }
/**
* @param {string} string
* @returns {string} Capitalised first letter.
*/
static capitalise(string) {
if (string.length < 1) return string;
if (string.length === 1) return string.toUpperCase();
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* @param {Array} [cmds]
* @returns {Array} Non-owner-only commands.
*/
userCommands(cmds) {
return (cmds || this.commands.commands).filter(c =>
c.requirements.findIndex(r => r.ownerOnly) === -1
);
}
/** @returns {number} Total number of help pages. */
pageNumber() {
return Math.ceil(this.commands.commands.length / this.commandsPerPage);
}
/**
* Entry point for help rendering.
* @param {object} message
* @returns {string|null}
*/
help(message) {
if (this.customHelpHandler) return this.customHelpHandler(message);
if (this.paginationHandler) return this.genHelp(null, message, true);
return this.getHelpPage(0, message);
}
/**
* @param {number} n - 0-based page index.
* @param {object} msg
* @param {Array} [cmds=null]
* @returns {string}
*/
getHelpPage(n, msg, cmds = null) {
if (!cmds) cmds = this.commands.commands;
if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds);
let offset = this.commandsPerPage * n;
const commands = cmds.slice(offset, offset + this.commandsPerPage);
let max = Math.ceil(cmds.length / this.commandsPerPage);
return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands);
}
/**
* @param {object|null} page
* @param {object} msg
* @param {boolean} [paginate=false]
* @param {Array} [cmds=null]
* @returns {string}
*/
genHelp(page, msg, paginate = false, cmds = null) {
cmds = this.userCommands(cmds);
if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds);
const guildId = msg.message.guildId;
let p = (page) ? ` (page ${page.curr}/${page.max})` : "";
const indexOffset = (page) ? page.offset : 0;
let content = this.commands.t(guildId, "cmdHandler.help.availableCommands", { $page: p }) + "\n\n";
if (page && page.curr !== 1) content += (indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
cmds.forEach((cmd, i) => { content += (i + 1 + indexOffset) + ". **" + cmd.name + "**: " + cmd.description + "\n"; });
if (page && page.curr !== page.max) content += (cmds.length + indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.runHelp"), guildId);
if (page) content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.pageTip"), guildId);
return this.commands.format(content, guildId);
}
/**
* Get the description of a command.
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
* @returns {string}
*/
commandDescription(command) { return command.description; }
/**
* Build a usage string for a command including options and flags.
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
* @param {object} msg
* @returns {string}
*/
commandUsage(cmd, msg) {
if (cmd.subcommands.length > 0) {
return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]";
}
let options = this.commands.format("$prefix" + cmd.command, msg.message.guildId);
cmd.options.forEach(o => {
if (o.type === "text") return;
if (o instanceof Flag)
return options += (o.type === "choice") ? "-" + o.aliases[0] + " <" + Option.formatChoicesUsage(o.choices) + ">" : " -" + o.aliases[0] + " '" + o.type + "'";
options += (o.type === "choice") ? " <" + Option.formatChoicesUsage(o.choices) + ">" : " '" + o.name + ": " + o.type + "'";
});
let o = cmd.options.find(e => e.type === "text");
if (o) options += "'" + o.name + ": " + o.type + "'";
return options.trim();
}
/**
* Generate detailed help text for a single command.
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
* @param {object} msg
* @returns {string}
*/
getCommandHelp(command, msg) {
const guildId = msg.message.guildId;
let content = `${HelpHandler.capitalise(command.name)}\n`;
content += this.commandDescription(command, msg) + "\n\n";
content += this.commands.t(guildId, "cmdHandler.help.usage") + "\n💻 `" + this.commandUsage(command, msg) + "`\n\n";
if (command.examples.length > 0)
content += this.commands.t(guildId, "cmdHandler.help.examples") + "\n- `" + command.examples.map(e => this.commands.format(e, guildId)).join("`\n- `") + "`\n\n";
if (command.aliases.length > 1) {
content += this.commands.t(guildId, "cmdHandler.help.aliases") + "\n";
command.aliases.forEach(alias => { content += "- " + alias + "\n"; });
content += "\n";
}
if (command.subcommands.length > 0) {
content += this.commands.t(guildId, "cmdHandler.help.subcommands") + "\n";
command.subcommands.forEach(s => {
const optCount = s.options.length > 0 ? "; (`" + this.commands.t(guildId, "cmdHandler.help.optionCount", { $count: s.options.length }) + "`)" : "";
content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + optCount + "\n";
});
content += "\n";
} else if (command.options.length > 0) {
content += this.commands.t(guildId, "cmdHandler.help.arguments") + "\n";
command.options.forEach(o => {
const optional = ((o.required) ? "" : "?");
const flag = (o instanceof Flag) ? "-" : "";
if (o.type === "choice") {
const choiceDisplay = Option.formatChoicesInline(o.choices);
const aliasDisplay = o.aliases.filter(a => a !== null).join('`, `');
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + ";\n - " + this.commands.t(guildId, "cmdHandler.help.allowedValues") + choiceDisplay + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + aliasDisplay + "`\n";
} else {
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + o.aliases.join("`, `") + "`\n";
}
content += "\n";
});
content += "\n";
}
if (command.requirements.length > 0) {
content += this.commands.t(guildId, "cmdHandler.help.requirements") + "\n";
command.requirements.forEach(r => {
content += "- " + r.getPermissions().map(e => this.commands.t(guildId, "cmdHandler.help.permission", { $permission: e })).join("\n- ");
});
}
return content.trim();
}
}
+279
View File
@@ -0,0 +1,279 @@
/**
* @module src/commands/Option
* @description Command option model — typed inputs (string, number, boolean,
* channel, user, choice, text) with validation, formatting and flag support.
*/
import { Utils } from "../utils/Utils.mjs";
/**
* @class Option
* @description Represents a single command option with validation and
* user-friendly error formatting. Options are positional; Flags (dashed
* `-name` arguments) share the same base class.
*/
export class Option {
/** @type {number} Maximum choices before switching to compact format. */
static THRESHOLD = 10;
/** @type {number} Number of choice columns per line in compact format. */
static COLS_PER_LINE = 5;
/**
* Format choice values in a compact multi-column layout.
* @param {string[]} choices
* @param {number} [perLine=Option.COLS_PER_LINE]
* @returns {string}
*/
static formatChoicesCompact(choices, perLine = Option.COLS_PER_LINE) {
const lines = [];
for (let i = 0; i < choices.length; i += perLine) {
lines.push(choices.slice(i, i + perLine).map(c => '`' + c + '`').join(' · '));
}
return lines.join('\n');
}
/**
* Format choice values inline, switching to compact layout above the threshold.
* @param {string[]} choices
* @returns {string}
*/
static formatChoicesInline(choices) {
if (choices.length <= Option.THRESHOLD) {
return '`' + choices.join('`, `') + '`';
}
return Option.formatChoicesCompact(choices, 6);
}
/**
* Format choice values for a usage string, truncating with "…" if over max.
* @param {string[]} choices
* @param {number} [max=6]
* @returns {string}
*/
static formatChoicesUsage(choices, max = 6) {
if (choices.length <= max) return choices.join(' | ');
return choices.slice(0, max).join(' | ') + ' | ...';
}
/** @type {RegExp} Matches a channel mention like `<#123456>`. */
channelRegex = /^<#(?<id>\d+)>/;
/** @type {RegExp} Matches a user mention like `<@123>` or `<@!123>`. */
userRegex = /^<@!?(?<id>\d+)>/;
/** @type {RegExp} Matches a leading numeric ID. */
idRegex = /^(?<id>\d+)/;
/** @type {Function|null} Dynamic default value resolver. */
dynamicDefault;
/**
* @param {string} [type="string"] One of: string, number, boolean, channel,
* voiceChannel, user, choice, text.
*/
constructor(type = "string") {
this.name = null;
this.description = null;
this.required = false;
this.id = null;
this.uid = Utils.uid();
this.type = type;
this.tError = null;
this.aliases = [null];
this.choices = [];
this.translations = {};
this.defaultValue = null;
this.dynamicDefault = null;
}
/**
* Factory to create an Option or Flag instance.
* @param {string} type
* @param {boolean} [flag=false]
* @returns {Option|Flag}
*/
static create(type, flag = false) {
return (!flag) ? new Option(type) : new Flag(type);
}
/** @param {string} n @returns {Option} */
setName(n) { this.name = n; this.aliases[0] = n; return this; }
/** @param {string} d @returns {Option} */
setDescription(d) { this.description = d; return this; }
/** @param {boolean} r @returns {Option} */
setRequired(r) { this.required = r; return this; }
/** @param {string} id @returns {Option} */
setId(id) { this.id = id; return this; }
/** @param {string} t @returns {Option} */
setType(t) { this.type = t; return this; }
/**
* Add flag aliases (e.g. "v" for "-v").
* @param {...string} a
* @returns {Option}
*/
addFlagAliases(...a) { this.aliases.push(...a); return this; }
/**
* Add a single valid choice value (choice options only).
* @param {string} c
* @returns {Option}
* @throws {Error} If option type is not "choice".
*/
addChoice(c) {
if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!");
this.choices.push(c);
return this;
}
/**
* Add multiple valid choice values (choice options only).
* @param {...string} cs
* @returns {Option}
* @throws {Error} If option type is not "choice".
*/
addChoices(...cs) {
if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!");
cs.forEach(c => this.addChoice(c));
return this;
}
/**
* Set the default value used when the option is omitted.
* @param {*} value
* @returns {Option}
*/
setDefault(value) { this.defaultValue = value; return this; }
/**
* Set a dynamic default resolver function (called with (client, msg)).
* @param {Function} callback
* @returns {Option}
*/
setDynamicDefault(callback) { this.dynamicDefault = callback; return this; }
/**
* Check whether a value is considered empty/omitted.
* @param {*} i
* @returns {boolean}
*/
empty(i) {
if (i === undefined || i === null) return true;
return (!i && !(String(i).includes("0")));
}
/**
* Validate an input value for this option type.
* @param {*} i
* @param {object} client
* @param {object} msg
* @param {string} [type]
* @returns {boolean}
*/
validateInput(i, client, msg, type) {
switch (type || this.type) {
case "text":
case "string":
return !!i;
case "number":
return !isNaN(i) && !isNaN(parseFloat(i));
case "boolean":
return i === "0" || i === "1" || i?.toLowerCase() === "true" || i?.toLowerCase() === "false";
case "choice":
return this.choices.includes(i);
case "user":
return this.userRegex.test(i) || this.idRegex.test(i);
case "channel":
if (i === undefined) return false;
return this.channelRegex.test(i) || this.idRegex.test(i) || client.channels.some(c => c.name === i);
case "voiceChannel": {
if (!i) return false;
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
const voiceTypes = [2, 13];
const byName = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
const cObj = results
? client.channels.get(results.groups["id"])
: (byName ?? null);
return cObj ? voiceTypes.includes(cObj.type) : false;
}
}
}
/**
* Format/parse an input value into its canonical form (IDs for mentions,
* numbers for numeric options, booleans for bools).
* @param {*} i
* @param {object} client
* @param {object} msg
* @param {string} [type]
* @returns {*}
*/
formatInput(i, client, msg, type) {
switch (type || this.type) {
case "text":
case "string":
return i;
case "number":
return parseFloat(i);
case "boolean":
return i?.toLowerCase() === "true" || i === "1";
case "choice":
return i;
case "user": {
const rs = this.userRegex.exec(i) ?? this.idRegex.exec(i);
return rs?.groups["id"] ?? null;
}
case "channel": {
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
const channel = client.channels.find(c => c.name === i);
return results ? results.groups["id"] : (channel ? channel.id : null);
}
case "voiceChannel": {
const r = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
const guildId = msg?.channel?.guildId ?? msg?.guildId;
if (guildId === "eval") return r ? r.groups["id"] : (i || null);
const voiceTypes = [2, 13];
const c = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
return r ? r.groups["id"] : (c ? c.id : null);
}
}
}
/**
* Generate a type-error message template for this option.
* @returns {string}
*/
get typeError() {
if (this.tError) return this.tError;
switch (this.type) {
case "choice": {
const choiceStr = this.choices.length > Option.THRESHOLD
? Option.formatChoicesCompact(this.choices)
: this.choices.map(c => '- ' + c).join('\n');
return "Invalid value '$currValue'. The option `" + this.name + "` has to be one of the following: \n" + choiceStr + "\nSchematic: `$previousCmd <" + this.type + ">`";
}
case "voiceChannel":
case "channel":
return "Invalid value '$currValue'. The option `" + this.name + "` has to be a channel mention, id, or name.\nSchematic: `$previousCmd <" + this.type + ">`";
default:
return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`";
}
}
/** @param {string} e */
set typeError(e) { this.tError = e; }
}
/**
* @class Flag
* @description A dashed (`-name`) option. Flags cannot be of type "text".
* @extends Option
*/
export class Flag extends Option {
/**
* @param {string} [type="string"]
* @throws {Error} If type is "text".
*/
constructor(type = "string") {
if (type === "text") throw new Error("Flags can't be of type 'text'!");
super(type);
}
}
+35
View File
@@ -0,0 +1,35 @@
/**
* @module src/commands/PrefixManager
* @description Per-guild command prefix resolution (guild setting → config → "%").
*/
/**
* @class PrefixManager
* @description Manages per-guild command prefixes, falling back to the
* configured prefix and finally to "%".
*/
export class PrefixManager {
/** @type {import('../db/Settings.mjs').RemoteSettingsManager} */
settings;
/** @type {string|null} */
configPrefix;
/**
* @param {import('../db/Settings.mjs').RemoteSettingsManager} settings
* @param {string|null} [configPrefix=null]
*/
constructor(settings, configPrefix = null) {
this.settings = settings;
this.configPrefix = configPrefix;
}
/**
* Get the command prefix for a guild.
* @param {string} guildId
* @returns {string}
*/
getPrefix(guildId) {
const serverPrefix = this.settings.getServer(guildId).get("prefix");
return serverPrefix ?? this.configPrefix ?? "%";
}
}
+14
View File
@@ -0,0 +1,14 @@
/**
* @module src/commands
* @description Public surface of the command framework layer.
*
* Import map from the old layout:
* - `src/CommandHandler.mjs` → this module
*/
export { CommandBuilder, CommandRequirement } from "./CommandBuilder.mjs";
export { Option, Flag } from "./Option.mjs";
export { PrefixManager } from "./PrefixManager.mjs";
export { HelpHandler } from "./HelpHandler.mjs";
export { CommandHandler } from "./CommandHandler.mjs";
export { CommandLoader } from "./CommandLoader.mjs";