refactor: centralize prefix resolution into CommandHandler

Replace all scattered prefix lookups across the codebase with a single
source of truth: CommandHandler.getPrefix(guildId).
This commit is contained in:
NoLogicAlan committed 2026-05-31 15:02:18 +03:00
1 parent 23d0dbc522
commit ba479e4c04
25 files changed
+155 -159

No files matched your search

+1 -1
View File
@@ -412,7 +412,7 @@ export class CommandHandler extends EventEmitter {
_cmdCooldowns = new Map();
_cmdCooldownMs = 1500;
constructor(handler, prefix = "!") {
constructor(handler, prefix = "%") {
super();
this.messages = handler;
this.client = handler.client;
+4 -4
View File
@@ -1111,7 +1111,7 @@ export class GatewayHandler {
/**
* Rejoin a voice channel after an unexpected disconnect.
* Used by the %247 auto mode to automatically reconnect.
* Used by the $prefix247 auto mode to automatically reconnect.
*
* Includes deduplication (prevents concurrent rejoin for the same channel)
* and retry with exponential backoff for transient failures like track
@@ -1332,9 +1332,9 @@ export class GatewayHandler {
/**
* Rejoin all 24/7 channels after boot with staggered delays.
*
* Both %247 auto and %247 on channels are rejoined because:
* %247 auto: always stays in voice (disconnect + reboot)
* %247 on: only on reboot, not on disconnect
* Both $prefix247 auto and $prefix247 on channels are rejoined because:
* $prefix247 auto: always stays in voice (disconnect + reboot)
* $prefix247 on: only on reboot, not on disconnect
*
* Channels are rejoined one at a time with a delay between each to
* avoid overwhelming the LiveKit server with concurrent track publications.
+6 -6
View File
@@ -5,7 +5,7 @@
* - Auth flow (desktop API: get token → user authorizes → get session)
* - Now-playing notification (track.scrobble with timestamp=0)
* - Full scrobble after threshold (50% of track or 4 min, whichever is less)
* - Fetch loved / top / recent tracks for %play lastfm loved/top/recent
* - Fetch loved / top / recent tracks for $prefixplay lastfm loved/top/recent
* - Per-user session key storage in MySQL table `lastfm_users`
*
* Last.fm API docs: https:
@@ -496,7 +496,7 @@ export class LastFmManager {
}
/**
* Get track info (play count, tags, etc.) for the %np embed.
* Get track info (play count, tags, etc.) for the $prefixnp embed.
*/
async getTrackInfo(artist, track, userId = null) {
if (!this.enabled) return null;
@@ -571,7 +571,7 @@ export class LastFmManager {
/**
* Search Last.fm for a freeform track query and return the best match.
* Useful for `%play lastfm: kendrick lamar luther` where artist/title
* Useful for `$prefixplay lastfm: kendrick lamar luther` where artist/title
* boundaries are ambiguous.
*
* @param {string} query
@@ -1400,7 +1400,7 @@ export class LastFmManager {
const playlists = await this.getPlaylists(userId);
const idx = +playlistId - 1;
if (idx < 0 || idx >= playlists.length) {
throw new Error(`Playlist #${playlistId} not found. You have ${playlists.length} playlist(s). Use \`%lastfm playlists\` to see them.`);
throw new Error(`Playlist #${playlistId} not found. You have ${playlists.length} playlist(s). Use the lastfm playlists command to see them.`);
}
playlistUrl = playlists[idx].url;
} else if (String(playlistId).startsWith("http")) {
@@ -1476,7 +1476,7 @@ export class LastFmManager {
}
/**
* Get the user's top albums (for %lastfm play albums).
* Get the user's top albums (for $prefixlastfm play albums).
* @param {string} userId
* @param {string} [period="overall"] - overall | 7day | 1month | 3month | 6month | 12month
* @param {number} [limit=20]
@@ -1567,7 +1567,7 @@ export class LastFmManager {
tracks = tracks.filter(t => !t.now);
break;
case "playlist":
if (!options.playlistId) throw new Error("Playlist ID required. Use `%lastfm playlists` to see your playlists, then `%lastfm play playlist <number>`.");
if (!options.playlistId) throw new Error("Playlist ID required. Use the lastfm playlists command to see your playlists, then use the lastfm play playlist command with a number.");
tracks = await this.getPlaylistTracks(userId, options.playlistId, limit);
break;
case "albums":
+7 -24
View File
@@ -362,6 +362,7 @@ export default class Player extends EventEmitter {
this.config = opts.config ?? {};
this.settings = opts.settings ?? null;
this.settingsMgr = opts.settingsMgr ?? null;
this._getPrefix = opts.getPrefix ?? null;
this._observedVoiceUsers = opts.observedVoiceUsers ?? null;
this._voiceCache = opts.voiceCache ?? null;
this.locale = opts.locale ?? null;
@@ -414,9 +415,9 @@ export default class Player extends EventEmitter {
* Get the 24/7 mode for this player's channel.
* Returns "auto", "on", or "off".
*
* %247 auto: bot stays in voice always (never leaves, auto-rejoins on disconnect + reboot)
* %247 on: bot stays in voice always (never leaves due to inactivity, rejoins on reboot)
* %247 off: bot leaves when inactive
* $prefix247 auto: bot stays in voice always (never leaves, auto-rejoins on disconnect + reboot)
* $prefix247 on: bot stays in voice always (never leaves due to inactivity, rejoins on reboot)
* $prefix247 off: bot leaves when inactive
*/
_get247Mode() {
if (!this._guildId) return "off";
@@ -1389,13 +1390,7 @@ export default class Player extends EventEmitter {
this._queueEndedSent = true;
this.emit("queueEnd");
if (!this._autoplay) {
const prefix = (() => {
try {
return this.settingsMgr?.getServer?.(this._guildId)?.get?.("prefix")
?? this.settings?.get?.("prefix")
?? "%";
} catch (_) { return "%"; }
})();
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true });
}
}
@@ -1432,13 +1427,7 @@ export default class Player extends EventEmitter {
this._queueEndedSent = true;
this.emit("queueEnd");
if (!this._autoplay) {
const prefix = (() => {
try {
return this.settingsMgr?.getServer?.(this._guildId)?.get?.("prefix")
?? this.settings?.get?.("prefix")
?? "%";
} catch (_) { return "%"; }
})();
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true });
}
}
@@ -2131,13 +2120,7 @@ export default class Player extends EventEmitter {
if (!this._wasRadio && !this._queueEndedSent && !this._autoplay) {
this._queueEndedSent = true;
const prefix = (() => {
try {
return this.settingsMgr?.getServer?.(this._guildId)?.get?.("prefix")
?? this.settings?.get?.("prefix")
?? "%";
} catch (_) { return "%"; }
})();
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true });
}
this._wasRadio = false;
+7 -12
View File
@@ -624,11 +624,7 @@ export class PlayerManager {
});
}
const prefix = (() => {
try {
return this.settings.getServer(guildId)?.get("prefix") ?? "%";
} catch (_) { return "%"; }
})();
const prefix = this.commands.getPrefix(guildId);
message.reply(mkEmbed(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix })));
return null;
}
@@ -830,6 +826,7 @@ export class PlayerManager {
moonlink: this.playerConfig?.moonlink ?? null,
revoice: this.playerConfig?.revoice ?? null,
settingsMgr: this.settings,
getPrefix: (guildId) => this.commands.getPrefix(guildId),
observedVoiceUsers: this.observedVoiceUsers ?? null,
voiceCache: this.voiceCache ?? null,
locale: this.locale ?? null,
@@ -889,17 +886,15 @@ export class PlayerManager {
if (homeChannelId !== activeChannelId) this.playerMap.delete(homeChannelId);
player.destroy();
const prefix = (() => {
try { return this.settings.getServer(guildId)?.get("prefix") ?? "%"; } catch (_) { return "%"; }
})();
const prefix = this.commands.getPrefix(guildId);
let desc;
if (mode247 === "on") {
desc = this.locale?.translate(guildId, "responses.join.autoLeave247On", { channel: `<#${activeChannelId}>` })
?? `Left channel <#${activeChannelId}> because of inactivity.\nI'll rejoin automatically when the bot restarts (%247 on mode).`;
desc = this.locale?.translate(guildId, "responses.join.autoLeave247On", { channel: `<#${activeChannelId}>`, prefix })
?? `Left channel <#${activeChannelId}> because of inactivity.\nI'll rejoin automatically when the bot restarts (${prefix}247 on mode).`;
} else if (mode247 === "auto") {
desc = this.locale?.translate(guildId, "responses.join.autoLeave247Auto", { channel: `<#${activeChannelId}>` })
?? `Left channel <#${activeChannelId}> — reconnecting automatically (%247 auto mode)...`;
desc = this.locale?.translate(guildId, "responses.join.autoLeave247Auto", { channel: `<#${activeChannelId}>`, prefix })
?? `Left channel <#${activeChannelId}> — reconnecting automatically (${prefix}247 auto mode)...`;
} else {
desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive247", { channel: `<#${activeChannelId}>`, prefix })
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
+34
View File
@@ -25,6 +25,8 @@ export class Locale {
this.defaultLocale = "en";
/** settingsMgr reference — set after construction via bind() */
this.settingsMgr = null;
/** getPrefix callback — set by CommandHandler so prefix logic lives in one place */
this._getPrefixFn = null;
/** Maximum guild locale cache size */
this._maxResolvedCache = 5000;
}
@@ -131,6 +133,33 @@ export class Locale {
}
}
/**
* Set the prefix resolver callback. Called once by CommandHandler at startup
* so that all prefix resolution goes through CommandHandler.getPrefix().
* @param {(guildId: string) => string} fn
*/
setPrefixResolver(fn) {
this._getPrefixFn = fn;
}
/**
* Get the per-guild prefix. Delegates to CommandHandler.getPrefix() when
* available, otherwise falls back to a direct settings lookup.
* @param {string} guildId
* @returns {string}
*/
_getPrefix(guildId) {
if (this._getPrefixFn) return this._getPrefixFn(guildId);
try {
const serverSettings = this.settingsMgr?.getServer?.(guildId);
if (serverSettings) {
const prefix = serverSettings.get("prefix");
if (prefix) return prefix;
}
} catch (_) {}
return "%";
}
/**
* Look up a dotted key in a nested object.
* @param {Object} obj
@@ -175,6 +204,11 @@ export class Locale {
);
}
if (value.includes("$prefix")) {
const prefix = this._getPrefix(guildId);
value = value.replace(/\$prefix/gi, prefix);
}
return value;
}
}