mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
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:
1 parent
0f085a6ae4
commit
253d11cd57
150 files changed
+19935
-16894
No files matched your search
@@ -3,10 +3,10 @@
|
||||
* @description Toggle autoplay mode — keeps the music going forever:
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the autoplay command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@
|
||||
* @description Remove all songs from the playback queue.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/**
|
||||
* @type {CommandBuilder}
|
||||
|
||||
+9
-614
@@ -1,340 +1,16 @@
|
||||
/**
|
||||
* @module commands/debug
|
||||
* @description Owner-only debug command for voice diagnostics, ghost connection detection, and forced rejoin.
|
||||
* @description Owner-only debug command for voice diagnostics, ghost connection
|
||||
* detection, and forced rejoin. The implementations live in commands/debug/
|
||||
* (gateway, rejoin, voiceDiagnostic); the builder and run() dispatch stay here.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { ERROR_COLOR, WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||
|
||||
const REJOIN_DELAY_MS = 2_000;
|
||||
const INTENTIONAL_LEAVE_TTL = 30_000;
|
||||
const MAX_DESC = 4096;
|
||||
|
||||
/**
|
||||
* Get a human-readable label for a voice room's connection state.
|
||||
* @private
|
||||
* @param {object|null} room - The voice room object.
|
||||
* @returns {string} Connection state label.
|
||||
*/
|
||||
function roomStateLabel(room) {
|
||||
if (!room) return "none";
|
||||
const cs = room.connectionState;
|
||||
if (cs === 0 || cs === "CONN_DISCONNECTED") return "disconnected(0)";
|
||||
if (cs === 1 || cs === "CONN_CONNECTED") return "connected(1)";
|
||||
if (cs === 2) return room.isConnected ? "connected(2)" : "reconnecting(2)";
|
||||
if (cs === "CONN_RECONNECTING") return "reconnecting";
|
||||
if (cs === 3) return "reconnecting(3)";
|
||||
if (cs === 4) return "signal_reconnecting(4)";
|
||||
if (typeof cs === "string") return cs;
|
||||
return String(cs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a player has a ghost connection (appears in voice but WebSocket is dead).
|
||||
* @private
|
||||
* @param {object} player - The player instance.
|
||||
* @returns {boolean} True if the player has a ghost connection.
|
||||
*/
|
||||
function isGhostConnection(player) {
|
||||
const conn = player.connection;
|
||||
if (!conn) return false;
|
||||
if (player._destroyed || player.leaving || player._isJoining) return false;
|
||||
|
||||
const room = conn.room;
|
||||
if (!room) {
|
||||
return !conn._destroyed;
|
||||
}
|
||||
|
||||
if (!room.isConnected) return true;
|
||||
|
||||
const cs = room.connectionState;
|
||||
if (cs === 0 || cs === "CONN_DISCONNECTED") return true;
|
||||
if (cs === "CONN_RECONNECTING" || cs === 3 || cs === 4) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the bot's voice channel state from the Discord gateway cache.
|
||||
* @private
|
||||
* @param {object} client - The Discord client instance.
|
||||
* @param {string} guildId - The guild ID to check.
|
||||
* @returns {{ userId: string, channelId: string }|null} Bot's voice state or null.
|
||||
*/
|
||||
function getBotGatewayVoiceState(client, guildId) {
|
||||
const botId = client.user?.id;
|
||||
if (!botId || !guildId) return null;
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates) {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
|
||||
if (guildVoiceMap && typeof guildVoiceMap.get === "function") {
|
||||
const channelId = guildVoiceMap.get(botId);
|
||||
if (channelId) return { userId: botId, channelId: cleanId(channelId) };
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (VoiceManager):", e?.message); }
|
||||
|
||||
try {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
||||
if (!voiceStates) return null;
|
||||
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.entries(voiceStates).map(([uid, val]) => {
|
||||
if (typeof val === "string") return { user_id: uid, channel_id: val };
|
||||
const obj = typeof val === "object" && val !== null ? val : {};
|
||||
return { user_id: uid, channel_id: obj.channelId ?? obj.channel_id ?? null, ...obj };
|
||||
});
|
||||
|
||||
for (const state of entries) {
|
||||
const uid = state?.user_id ?? state?.userId ?? state?.id;
|
||||
if (uid === botId) {
|
||||
const chId = state?.channel_id ?? state?.channelId ?? null;
|
||||
if (chId) return { userId: botId, channelId: cleanId(chId) };
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (guild cache):", e?.message); }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the gateway voice state is stale (mismatches the player's channel).
|
||||
* @private
|
||||
* @param {object} client - The Discord client instance.
|
||||
* @param {object} player - The player instance.
|
||||
* @returns {boolean} True if the gateway presence is stale.
|
||||
*/
|
||||
function isStaleGatewayPresence(client, player) {
|
||||
const guildId = player._guildId ?? player._resolveGuildId?.();
|
||||
if (!guildId) return false;
|
||||
|
||||
const gatewayState = getBotGatewayVoiceState(client, guildId);
|
||||
if (!gatewayState) return false;
|
||||
|
||||
const playerChannel = cleanId(player._channelId ?? player._home247Channel);
|
||||
const gatewayChannel = gatewayState.channelId;
|
||||
|
||||
return !playerChannel || playerChannel !== gatewayChannel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a human-readable label for a player (guild name / #channel name).
|
||||
* @private
|
||||
* @param {object} client - The Discord client instance.
|
||||
* @param {string} channelId - The voice channel ID.
|
||||
* @param {object} player - The player instance.
|
||||
* @returns {string} Formatted label string.
|
||||
*/
|
||||
function buildPlayerLabel(client, channelId, player) {
|
||||
const channel = client.channels.get(channelId);
|
||||
const gId = player._guildId ?? channel?.guildId;
|
||||
const guild = gId ? client.guilds.get(cleanId(gId)) : null;
|
||||
return `${guild?.name ?? "unknown"} / #${channel?.name ?? channelId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Force a player to leave and rejoin, restoring queue and playback state.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} ctx - The bot (Remix) instance context.
|
||||
* @param {object} player - The player to rejoin.
|
||||
* @returns {Promise<object>} Result object with success status, room state, and details.
|
||||
*/
|
||||
async function forceRejoinPlayer(ctx, player) {
|
||||
const channelId = player._channelId ?? player._home247Channel;
|
||||
const guildId = player._guildId ?? player._resolveGuildId?.();
|
||||
if (!channelId || !guildId) return { success: false, reason: "no channel or guild id" };
|
||||
|
||||
const cleanChannelId = cleanId(channelId);
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
|
||||
const currentTrack = player.queue?.getCurrent();
|
||||
const queueTracks = player.queue?.data ? [...player.queue.data] : [];
|
||||
const wasPaused = player._paused;
|
||||
const wasAutoplay = player._autoplay;
|
||||
const wasLoop = player.queue?.loop ?? false;
|
||||
const wasSongLoop = player.queue?.songLoop ?? false;
|
||||
const savedVolume = player.preferredVolume ?? 1;
|
||||
const savedFilter = player.activeFilter ?? null;
|
||||
const savedFilterPayload = player.activeFilterPayload ?? null;
|
||||
|
||||
try {
|
||||
ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL);
|
||||
|
||||
ctx.players.playerMap.delete(cleanChannelId);
|
||||
ctx.players._unindexPlayer?.(cleanGuildId, cleanChannelId);
|
||||
|
||||
const altIds = [player._channelId, player._home247Channel]
|
||||
.filter(Boolean)
|
||||
.map(id => cleanId(id))
|
||||
.filter(id => id !== cleanChannelId);
|
||||
for (const altId of altIds) {
|
||||
ctx.players.playerMap.delete(altId);
|
||||
ctx.players._unindexPlayer?.(cleanGuildId, altId);
|
||||
}
|
||||
|
||||
const pendingScrobble = ctx.players._pendingScrobbleTimers?.get(cleanChannelId);
|
||||
if (pendingScrobble) {
|
||||
clearTimeout(pendingScrobble.timer);
|
||||
ctx.players._pendingScrobbleTimers.delete(cleanChannelId);
|
||||
}
|
||||
|
||||
ctx.players._pendingJoins?.delete?.(cleanChannelId);
|
||||
|
||||
if (player.connection) {
|
||||
try { player.connection.removeAllListeners(); } catch (e) { logger.warn("[Debug] connection listener removal:", e?.message); }
|
||||
try { await player.connection.disconnect(); } catch (e) { logger.warn("[Debug] connection disconnect:", e?.message); }
|
||||
}
|
||||
|
||||
try { await player.leave(); } catch (e) { logger.warn("[Debug] player leave:", e?.message); }
|
||||
try { player.destroy(); } catch (e) { logger.warn("[Debug] player destroy:", e?.message); }
|
||||
|
||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||
|
||||
const newPlayer = await ctx._spawnPlayer(cleanGuildId, cleanChannelId);
|
||||
|
||||
if (!newPlayer) {
|
||||
return { success: false, reason: "_spawnPlayer returned null", channelId: cleanChannelId };
|
||||
}
|
||||
|
||||
if (newPlayer.preferredVolume !== savedVolume) {
|
||||
newPlayer.setVolume(savedVolume);
|
||||
}
|
||||
|
||||
if (wasLoop) newPlayer.queue?.setLoop?.(true);
|
||||
if (wasSongLoop) newPlayer.queue?.setSongLoop?.(true);
|
||||
|
||||
if (savedFilter && savedFilterPayload) {
|
||||
newPlayer.activeFilter = savedFilter;
|
||||
newPlayer.activeFilterPayload = savedFilterPayload;
|
||||
}
|
||||
|
||||
if (currentTrack && newPlayer.queue) {
|
||||
try {
|
||||
newPlayer.queue.data = queueTracks;
|
||||
newPlayer.queue.current = null;
|
||||
await newPlayer.playNext();
|
||||
if (wasPaused) newPlayer.pause();
|
||||
} catch (e) { logger.warn("[Debug] queue restore:", e?.message); }
|
||||
}
|
||||
|
||||
if (wasAutoplay) {
|
||||
newPlayer._autoplay = true;
|
||||
newPlayer._autoplayHistory = player._autoplayHistory ?? [];
|
||||
try {
|
||||
const { attachAutoplay } = await import("./autoplay.mjs");
|
||||
attachAutoplay(newPlayer, ctx);
|
||||
} catch (e) {
|
||||
logger.warn("[Debug] autoplay re-attach failed:", e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
const newRoom = newPlayer.connection?.room;
|
||||
return {
|
||||
success: !!(newPlayer.connection && newRoom?.isConnected),
|
||||
roomConnected: newRoom?.isConnected ?? false,
|
||||
roomState: roomStateLabel(newRoom),
|
||||
resumedPlayback: !!(currentTrack && newPlayer.queue?.getCurrent()),
|
||||
channelId: cleanChannelId,
|
||||
};
|
||||
} catch (err) {
|
||||
logger.warn("[Debug] forceRejoinPlayer error:", err?.message);
|
||||
return { success: false, reason: err.message, channelId: cleanChannelId };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a batch of players for force-rejoin, updating a status message with progress.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} ctx - The bot (Remix) instance context.
|
||||
* @param {Array} entries - Array of [channelId, player] tuples.
|
||||
* @param {object} statusMsg - The message to update with progress.
|
||||
* @param {string} title - The title for the progress display.
|
||||
* @returns {Promise<object[]>} Array of rejoin results.
|
||||
*/
|
||||
async function processRejoinBatch(ctx, entries, statusMsg, title) {
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const [cid, player] = entries[i];
|
||||
const label = buildPlayerLabel(ctx.client, cid, player);
|
||||
|
||||
const progressLines = [
|
||||
`🔄 **${title}** — Processing ${i + 1}/${entries.length}`,
|
||||
`Currently rejoining: \`${label}\``,
|
||||
``,
|
||||
];
|
||||
for (let j = 0; j < results.length; j++) {
|
||||
const r = results[j];
|
||||
const icon = r.success ? "✅" : "❌";
|
||||
progressLines.push(`${icon} \`${r.label}\`${r.success ? ` — room:${r.roomState}` : ` — failed (${r.reason ?? "?"})`}`);
|
||||
}
|
||||
await statusMsg.edit({ embeds: [new EmbedBuilder().setColor(WARN_COLOR).setTitle(`Debug — ${title}`).setDescription(progressLines.join("\n").slice(0, MAX_DESC))] }).catch(() => {});
|
||||
|
||||
const result = await forceRejoinPlayer(ctx, player);
|
||||
result.label = label;
|
||||
results.push(result);
|
||||
|
||||
if (i < entries.length - 1) {
|
||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the final embed summarizing rejoin results.
|
||||
* @private
|
||||
* @param {object[]} results - Array of rejoin result objects.
|
||||
* @param {string} title - The title for the embed.
|
||||
* @param {string} noun - The noun describing the rejoin targets.
|
||||
* @returns {object} Message payload with embed.
|
||||
*/
|
||||
function buildRejoinResultEmbed(results, title, noun) {
|
||||
const resultLines = [
|
||||
`🔄 **${title} Complete**`,
|
||||
`${noun.charAt(0).toUpperCase() + noun.slice(1)} processed: **${results.length}**`,
|
||||
``,
|
||||
];
|
||||
|
||||
let rejoinedCount = 0;
|
||||
let resumedCount = 0;
|
||||
let failedCount = 0;
|
||||
|
||||
for (const r of results) {
|
||||
if (r.success) {
|
||||
rejoinedCount++;
|
||||
if (r.resumedPlayback) resumedCount++;
|
||||
resultLines.push(`✅ \`${r.label}\` — rejoined (room:${r.roomState}, playback:${r.resumedPlayback ? "resumed" : "no track"})`);
|
||||
} else {
|
||||
failedCount++;
|
||||
resultLines.push(`❌ \`${r.label}\` — failed${r.reason ? ` (${r.reason})` : ""}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (failedCount === 0) {
|
||||
resultLines.push("", `All **${rejoinedCount}** ${noun} restored.${resumedCount > 0 ? ` ${resumedCount} had playback resumed.` : ""}`);
|
||||
} else {
|
||||
resultLines.push("", `⚠️ **${failedCount}** ${noun} could not be restored.`);
|
||||
}
|
||||
|
||||
const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR;
|
||||
return { embeds: [new EmbedBuilder().setColor(finalColor).setTitle(`Debug — ${title}`).setDescription(resultLines.join("\n").slice(0, MAX_DESC))] };
|
||||
}
|
||||
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||
import { isGhostConnection } from "./debug/gateway.mjs";
|
||||
import { runBatchRejoin } from "./debug/rejoin.mjs";
|
||||
import { runVoiceDiagnostic } from "./debug/voiceDiagnostic.mjs";
|
||||
|
||||
/**
|
||||
* @type {CommandBuilder}
|
||||
@@ -351,6 +27,7 @@ export const command = new CommandBuilder()
|
||||
.addChoices("voice", "voice-rejoin", "247-rejoin")
|
||||
.setRequired(true));
|
||||
|
||||
|
||||
/**
|
||||
* Run handler for the debug command.
|
||||
* Routes to the appropriate debug subcommand based on the target option.
|
||||
@@ -385,285 +62,3 @@ export async function run(msg, data) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a batch rejoin operation on matching players.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {string} key - Identifier key for the rejoin type.
|
||||
* @param {string} title - Display title for the operation.
|
||||
* @param {string} noun - Noun describing the targets.
|
||||
* @param {Function} filter - Function to filter which players to rejoin.
|
||||
* @param {boolean} [showHintIfEmpty=false] - Whether to show a hint if no matches found.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = false) {
|
||||
const allPlayers = [...this.players.playerMap.entries()];
|
||||
const matching = allPlayers.filter(([, player]) => filter(player));
|
||||
|
||||
if (matching.length === 0) {
|
||||
const has247 = allPlayers.some(([, player]) => player._home247Channel);
|
||||
const hintLine = showHintIfEmpty && has247
|
||||
? `\n\n💡 No ghosts auto-detected, but 24/7 channels with dead WebSockets may still report as "connected".\nUse \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`
|
||||
: "";
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(SUCCESS_COLOR)
|
||||
.setTitle(`Debug — ${title}`)
|
||||
.setDescription(`No ${noun} found. All voice connections appear healthy.${hintLine}`)
|
||||
;
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
const statusLines = [
|
||||
`🔄 **${title}** — Found **${matching.length}** ${noun}`,
|
||||
`Destroying stale connections and respawning fresh players...`,
|
||||
``,
|
||||
];
|
||||
|
||||
for (let i = 0; i < matching.length; i++) {
|
||||
const [cid, player] = matching[i];
|
||||
const label = buildPlayerLabel(this.client, cid, player);
|
||||
const ghost = isGhostConnection(player) ? " 👻GHOST" : "";
|
||||
const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none";
|
||||
const connectedLabel = player.connection?.room?.isConnected ? "yes" : "no";
|
||||
statusLines.push(`${i + 1}. \`${label}\` — room:${roomLabel} isConnected:${connectedLabel}${ghost}`);
|
||||
}
|
||||
|
||||
const statusEmbed = new EmbedBuilder()
|
||||
.setColor(WARN_COLOR)
|
||||
.setTitle(`Debug — ${title}`)
|
||||
.setDescription(statusLines.join("\n").slice(0, MAX_DESC))
|
||||
;
|
||||
const statusMsg = await msg.reply({ embeds: [statusEmbed] });
|
||||
|
||||
const results = await processRejoinBatch(this, matching, statusMsg, title);
|
||||
|
||||
const finalPayload = buildRejoinResultEmbed(results, title, noun);
|
||||
await statusMsg.edit(finalPayload).catch(() => {
|
||||
msg.reply(finalPayload);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a full voice diagnostic, displaying player states and ghost connections.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function runVoiceDiagnostic(msg) {
|
||||
const servers = [...this.players.playerMap.entries()].map(([cid, s]) => {
|
||||
const channel = this.client.channels.get(cid);
|
||||
const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id;
|
||||
const guild = guildId ? this.client.guilds.get(cleanId(guildId)) : null;
|
||||
const conn = s.connection;
|
||||
const room = conn?.room;
|
||||
const ghost = isGhostConnection(s);
|
||||
const staleGateway = ghost ? isStaleGatewayPresence(this.client, s) : false;
|
||||
const gatewayVoiceState = getBotGatewayVoiceState(this.client, guildId);
|
||||
return {
|
||||
name: channel?.name ?? "unknown",
|
||||
id: channel?.id ?? cid,
|
||||
channelId: s._channelId ?? cid,
|
||||
guildId: guildId ?? "unknown",
|
||||
guildname: guild?.name ?? channel?.guild?.name ?? "unknown",
|
||||
conn: conn ? "yes" : "null",
|
||||
connDestroyed: conn?._destroyed ?? null,
|
||||
roomConnected: room?.isConnected ?? null,
|
||||
roomState: roomStateLabel(room),
|
||||
mediaPlayer: !!s._mediaPlayer && !s._mediaPlayer?.destroyed ? "alive" : (s._mediaPlayer?.destroyed ? "destroyed" : "none"),
|
||||
destroyed: s._destroyed ?? false,
|
||||
leaving: s.leaving ?? false,
|
||||
joining: s._isJoining ?? false,
|
||||
recovering: s._isRecovering ?? false,
|
||||
paused: s._paused ?? false,
|
||||
hasQueue: !!(s.queue?.getCurrent() || !s.queue?.isEmpty()),
|
||||
home247: s._home247Channel ?? null,
|
||||
ghost,
|
||||
staleGateway,
|
||||
gatewayVoiceChannel: gatewayVoiceState?.channelId ?? null,
|
||||
};
|
||||
});
|
||||
const pending = [...(this.players._pendingJoins ?? [])];
|
||||
|
||||
const ghostConnections = servers.filter(s => s.ghost);
|
||||
const livePlayers = servers.filter(s => s.conn === "yes" && !s.destroyed && !s.leaving);
|
||||
const actuallyConnected = livePlayers.filter(s => !s.ghost);
|
||||
const channels247 = servers.filter(s => s.home247);
|
||||
|
||||
const summary = {
|
||||
playerMapSize: this.players.playerMap.size,
|
||||
livePlayers: livePlayers.length,
|
||||
actuallyConnected: actuallyConnected.length,
|
||||
ghostConnections: ghostConnections.length,
|
||||
channels247: channels247.length,
|
||||
pendingJoins: pending.length,
|
||||
pendingChannels: pending,
|
||||
};
|
||||
|
||||
const pages = [];
|
||||
|
||||
const summaryLines = [
|
||||
`📊 **Summary**`,
|
||||
`Players in map: **${summary.playerMapSize}**`,
|
||||
`Live players: **${summary.livePlayers}**`,
|
||||
`Actually connected: **${summary.actuallyConnected}**`,
|
||||
`Ghost connections: **${summary.ghostConnections}**`,
|
||||
`24/7 channels: **${summary.channels247}**`,
|
||||
`Pending joins: **${summary.pendingJoins}**${summary.pendingChannels.length ? ` (\`${summary.pendingChannels.join("`, `")}\`)` : ""}`,
|
||||
];
|
||||
|
||||
if (ghostConnections.length > 0) {
|
||||
summaryLines.push("", `👻 **Ghost Connections (${ghostConnections.length}):**`, "These players *appear* in voice but their WebSocket/LiveKit room is dead:");
|
||||
summaryLines.push(`Use \`%debug voice-rejoin\` to rejoin detected ghosts, or \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`);
|
||||
for (const g of ghostConnections) {
|
||||
const gatewayInfo = g.staleGateway
|
||||
? `gateway:stale(ch:${g.gatewayVoiceChannel ?? "?"})`
|
||||
: `gateway:present(ch:${g.gatewayVoiceChannel ?? "?"})`;
|
||||
const detail = ` 👻 \`${g.guildname}\` / \`#${g.name}\` — room:${g.roomState} connected:${g.roomConnected} media:${g.mediaPlayer} ${gatewayInfo} 247:${g.home247 ?? "no"}`;
|
||||
if (summaryLines.join("\n").length + detail.length + 1 > MAX_DESC - 60) {
|
||||
summaryLines.push(` … and more ghosts (see JSON details)`);
|
||||
break;
|
||||
}
|
||||
summaryLines.push(detail);
|
||||
}
|
||||
}
|
||||
|
||||
if (channels247.length > 0 && ghostConnections.length === 0) {
|
||||
summaryLines.push("", `ℹ️ **24/7 Channels (${channels247.length}):**`, `WebSocket deaths can leave 24/7 channels as invisible ghosts (room reports healthy but transport is dead).`);
|
||||
summaryLines.push(`Use \`%debug 247-rejoin\` to force-rejoin all 24/7 channels if you suspect ghost connections.`);
|
||||
}
|
||||
|
||||
summaryLines.push("", "**Players:**");
|
||||
for (let i = 0; i < servers.length; i++) {
|
||||
const s = servers[i];
|
||||
let status;
|
||||
if (s.ghost) {
|
||||
status = "👻";
|
||||
} else if (s.conn === "yes" && !s.destroyed && !s.leaving) {
|
||||
status = "🟢";
|
||||
} else {
|
||||
status = "🔴";
|
||||
}
|
||||
const ghostTag = s.ghost ? " ⚠️GHOST" : "";
|
||||
const staleTag = s.staleGateway ? " ⚠️STALE_GW" : "";
|
||||
const tag247 = s.home247 ? " 🔄247" : "";
|
||||
const line = `${status} \`${s.guildname}\` / \`#${s.name}\` — conn:${s.conn} room:${s.roomState} connected:${s.roomConnected} media:${s.mediaPlayer}${ghostTag}${staleTag}${tag247}`;
|
||||
if (summaryLines.join("\n").length + line.length + 1 > MAX_DESC - 30) {
|
||||
summaryLines.push(`… and ${servers.length - i} more (see next pages)`);
|
||||
break;
|
||||
}
|
||||
summaryLines.push(line);
|
||||
}
|
||||
pages.push(summaryLines.join("\n"));
|
||||
|
||||
let groupJson = "";
|
||||
for (let i = 0; i < servers.length; i++) {
|
||||
const singleJson = JSON.stringify(servers[i], null, 2);
|
||||
const candidate = groupJson
|
||||
? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1)
|
||||
: singleJson;
|
||||
|
||||
const candidateLen = ("```json\n" + candidate + "\n```").length;
|
||||
|
||||
if (candidateLen > MAX_DESC && groupJson) {
|
||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||
groupJson = singleJson;
|
||||
} else if (candidateLen > MAX_DESC) {
|
||||
const budget = MAX_DESC - 12;
|
||||
pages.push(("```json\n" + singleJson.slice(0, budget) + "\n```").slice(0, MAX_DESC));
|
||||
groupJson = "";
|
||||
} else {
|
||||
groupJson = candidate;
|
||||
}
|
||||
}
|
||||
if (groupJson) {
|
||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||
}
|
||||
|
||||
if (pages.length === 1) {
|
||||
const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor();
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(embedColor)
|
||||
.setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""))
|
||||
.setDescription(pages[0].slice(0, MAX_DESC))
|
||||
;
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
const totalPages = pages.length;
|
||||
let currentPage = 0;
|
||||
|
||||
const buildPage = (pageIdx, expired = false) => {
|
||||
const isSummaryPage = pageIdx === 0;
|
||||
const pageLabel = isSummaryPage
|
||||
? "Summary"
|
||||
: `Player Detail${pages[pageIdx].split(`"name":`).length - 1 > 1 ? "s" : ""}`;
|
||||
const footerText = expired
|
||||
? this.t(msg, "responses._common.controlsExpired")
|
||||
: `${this.t(msg, "responses.debug.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`;
|
||||
|
||||
const embedColor = (isSummaryPage && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor();
|
||||
const titleSuffix = (isSummaryPage && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "";
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(embedColor)
|
||||
.setTitle(this.t(msg, "responses.debug.voiceTitle") + titleSuffix + ` — ${pageLabel}`)
|
||||
.setDescription(pages[pageIdx].slice(0, MAX_DESC))
|
||||
.setFooter({ text: footerText })
|
||||
;
|
||||
return { embeds: [embed] };
|
||||
};
|
||||
|
||||
const replyMsg = await msg.reply(buildPage(0));
|
||||
if (!replyMsg?.message) return;
|
||||
|
||||
const navEmojis = ["⬅️", "➡️", "❌"];
|
||||
for (const emoji of navEmojis) {
|
||||
await replyMsg.message.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await replyMsg.message.removeAllReactions();
|
||||
} catch (e) {
|
||||
for (const emoji of navEmojis) {
|
||||
try { await replyMsg.message.removeReaction(emoji); } catch (err) { logger.warn("[Debug] removeReaction fallback:", err?.message); }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let emojiTimeout;
|
||||
const resetTimer = () => {
|
||||
clearTimeout(emojiTimeout);
|
||||
emojiTimeout = setTimeout(async () => {
|
||||
unobserve?.();
|
||||
await clearReactions();
|
||||
await replyMsg.edit(buildPage(currentPage, true)).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||
const emoji = e?.emoji_id ?? e?.emoji?.id ?? e?.emoji;
|
||||
|
||||
if (emoji === "❌") {
|
||||
clearTimeout(emojiTimeout);
|
||||
unobserve?.();
|
||||
await replyMsg.message.delete().catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
resetTimer();
|
||||
|
||||
if (emoji === "⬅️") {
|
||||
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
||||
} else if (emoji === "➡️") {
|
||||
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
||||
});
|
||||
|
||||
resetTimer();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* @module commands/debug/consts
|
||||
* @description Shared timing and embed-size constants for the debug command
|
||||
* modules. Verbatim from the original single-file command; only `export `
|
||||
* prefixes added.
|
||||
*/
|
||||
|
||||
export const REJOIN_DELAY_MS = 2_000;
|
||||
export const INTENTIONAL_LEAVE_TTL = 30_000;
|
||||
export const MAX_DESC = 4096;
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* @module commands/debug/gateway
|
||||
* @description Gateway/voice state inspection helpers (room labels, ghost detection, bot gateway voice state, stale presence, player labels). Verbatim from the original single-file command.
|
||||
*/
|
||||
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
import { cleanId } from "../../src/ui/index.mjs";
|
||||
|
||||
/**
|
||||
* Get a human-readable label for a voice room's connection state.
|
||||
* @private
|
||||
* @param {object|null} room - The voice room object.
|
||||
* @returns {string} Connection state label.
|
||||
*/
|
||||
export function roomStateLabel(room) {
|
||||
if (!room) return "none";
|
||||
const cs = room.connectionState;
|
||||
if (cs === 0 || cs === "CONN_DISCONNECTED") return "disconnected(0)";
|
||||
if (cs === 1 || cs === "CONN_CONNECTED") return "connected(1)";
|
||||
if (cs === 2) return room.isConnected ? "connected(2)" : "reconnecting(2)";
|
||||
if (cs === "CONN_RECONNECTING") return "reconnecting";
|
||||
if (cs === 3) return "reconnecting(3)";
|
||||
if (cs === 4) return "signal_reconnecting(4)";
|
||||
if (typeof cs === "string") return cs;
|
||||
return String(cs);
|
||||
}
|
||||
/**
|
||||
* Check if a player has a ghost connection (appears in voice but WebSocket is dead).
|
||||
* @private
|
||||
* @param {object} player - The player instance.
|
||||
* @returns {boolean} True if the player has a ghost connection.
|
||||
*/
|
||||
export function isGhostConnection(player) {
|
||||
const conn = player.connection;
|
||||
if (!conn) return false;
|
||||
if (player._destroyed || player.leaving || player._isJoining) return false;
|
||||
|
||||
const room = conn.room;
|
||||
if (!room) {
|
||||
return !conn._destroyed;
|
||||
}
|
||||
|
||||
if (!room.isConnected) return true;
|
||||
|
||||
const cs = room.connectionState;
|
||||
if (cs === 0 || cs === "CONN_DISCONNECTED") return true;
|
||||
if (cs === "CONN_RECONNECTING" || cs === 3 || cs === 4) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Get the bot's voice channel state from the gateway cache.
|
||||
* @private
|
||||
* @param {object} client - The client instance.
|
||||
* @param {string} guildId - The guild ID to check.
|
||||
* @returns {{ userId: string, channelId: string }|null} Bot's voice state or null.
|
||||
*/
|
||||
export function getBotGatewayVoiceState(client, guildId) {
|
||||
const botId = client.user?.id;
|
||||
if (!botId || !guildId) return null;
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates) {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
|
||||
if (guildVoiceMap && typeof guildVoiceMap.get === "function") {
|
||||
const channelId = guildVoiceMap.get(botId);
|
||||
if (channelId) return { userId: botId, channelId: cleanId(channelId) };
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (VoiceManager):", e?.message); }
|
||||
|
||||
try {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
||||
if (!voiceStates) return null;
|
||||
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.entries(voiceStates).map(([uid, val]) => {
|
||||
if (typeof val === "string") return { user_id: uid, channel_id: val };
|
||||
const obj = typeof val === "object" && val !== null ? val : {};
|
||||
return { user_id: uid, channel_id: obj.channelId ?? obj.channel_id ?? null, ...obj };
|
||||
});
|
||||
|
||||
for (const state of entries) {
|
||||
const uid = state?.user_id ?? state?.userId ?? state?.id;
|
||||
if (uid === botId) {
|
||||
const chId = state?.channel_id ?? state?.channelId ?? null;
|
||||
if (chId) return { userId: botId, channelId: cleanId(chId) };
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (guild cache):", e?.message); }
|
||||
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Check if the gateway voice state is stale (mismatches the player's channel).
|
||||
* @private
|
||||
* @param {object} client - The client instance.
|
||||
* @param {object} player - The player instance.
|
||||
* @returns {boolean} True if the gateway presence is stale.
|
||||
*/
|
||||
export function isStaleGatewayPresence(client, player) {
|
||||
const guildId = player._guildId ?? player._resolveGuildId?.();
|
||||
if (!guildId) return false;
|
||||
|
||||
const gatewayState = getBotGatewayVoiceState(client, guildId);
|
||||
if (!gatewayState) return false;
|
||||
|
||||
const playerChannel = cleanId(player._channelId ?? player._home247Channel);
|
||||
const gatewayChannel = gatewayState.channelId;
|
||||
|
||||
return !playerChannel || playerChannel !== gatewayChannel;
|
||||
}
|
||||
/**
|
||||
* Build a human-readable label for a player (guild name / #channel name).
|
||||
* @private
|
||||
* @param {object} client - The client instance.
|
||||
* @param {string} channelId - The voice channel ID.
|
||||
* @param {object} player - The player instance.
|
||||
* @returns {string} Formatted label string.
|
||||
*/
|
||||
export function buildPlayerLabel(client, channelId, player) {
|
||||
const channel = client.channels.get(channelId);
|
||||
const gId = player._guildId ?? channel?.guildId;
|
||||
const guild = gId ? client.guilds.get(cleanId(gId)) : null;
|
||||
return `${guild?.name ?? "unknown"} / #${channel?.name ?? channelId}`;
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
/**
|
||||
* @module commands/debug/rejoin
|
||||
* @description Force-rejoin machinery for the debug command (forceRejoinPlayer, batch processing, result embed, runBatchRejoin entry). Verbatim from the original single-file command; the relative dynamic import of autoplay.mjs was adjusted for the deeper directory.
|
||||
*/
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
import { cleanId } from "../../src/ui/index.mjs";
|
||||
import { WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR } from "../../src/utils/UI.mjs";
|
||||
import { REJOIN_DELAY_MS, INTENTIONAL_LEAVE_TTL, MAX_DESC } from "./consts.mjs";
|
||||
import { roomStateLabel, isGhostConnection, buildPlayerLabel } from "./gateway.mjs";
|
||||
|
||||
/**
|
||||
* Force a player to leave and rejoin, restoring queue and playback state.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} ctx - The bot (Remix) instance context.
|
||||
* @param {object} player - The player to rejoin.
|
||||
* @returns {Promise<object>} Result object with success status, room state, and details.
|
||||
*/
|
||||
async function forceRejoinPlayer(ctx, player) {
|
||||
const channelId = player._channelId ?? player._home247Channel;
|
||||
const guildId = player._guildId ?? player._resolveGuildId?.();
|
||||
if (!channelId || !guildId) return { success: false, reason: "no channel or guild id" };
|
||||
|
||||
const cleanChannelId = cleanId(channelId);
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
|
||||
const currentTrack = player.queue?.getCurrent();
|
||||
const queueTracks = player.queue?.data ? [...player.queue.data] : [];
|
||||
const wasPaused = player._paused;
|
||||
const wasAutoplay = player._autoplay;
|
||||
const wasLoop = player.queue?.loop ?? false;
|
||||
const wasSongLoop = player.queue?.songLoop ?? false;
|
||||
const savedVolume = player.preferredVolume ?? 1;
|
||||
const savedFilter = player.activeFilter ?? null;
|
||||
const savedFilterPayload = player.activeFilterPayload ?? null;
|
||||
|
||||
try {
|
||||
ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL);
|
||||
|
||||
ctx.players.playerMap.delete(cleanChannelId);
|
||||
ctx.players._unindexPlayer?.(cleanGuildId, cleanChannelId);
|
||||
|
||||
const altIds = [player._channelId, player._home247Channel]
|
||||
.filter(Boolean)
|
||||
.map(id => cleanId(id))
|
||||
.filter(id => id !== cleanChannelId);
|
||||
for (const altId of altIds) {
|
||||
ctx.players.playerMap.delete(altId);
|
||||
ctx.players._unindexPlayer?.(cleanGuildId, altId);
|
||||
}
|
||||
|
||||
const pendingScrobble = ctx.players._pendingScrobbleTimers?.get(cleanChannelId);
|
||||
if (pendingScrobble) {
|
||||
clearTimeout(pendingScrobble.timer);
|
||||
ctx.players._pendingScrobbleTimers.delete(cleanChannelId);
|
||||
}
|
||||
|
||||
ctx.players._pendingJoins?.delete?.(cleanChannelId);
|
||||
|
||||
if (player.connection) {
|
||||
try { player.connection.removeAllListeners(); } catch (e) { logger.warn("[Debug] connection listener removal:", e?.message); }
|
||||
try { await player.connection.disconnect(); } catch (e) { logger.warn("[Debug] connection disconnect:", e?.message); }
|
||||
}
|
||||
|
||||
try { await player.leave(); } catch (e) { logger.warn("[Debug] player leave:", e?.message); }
|
||||
try { player.destroy(); } catch (e) { logger.warn("[Debug] player destroy:", e?.message); }
|
||||
|
||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||
|
||||
const newPlayer = await ctx._spawnPlayer(cleanGuildId, cleanChannelId);
|
||||
|
||||
if (!newPlayer) {
|
||||
return { success: false, reason: "_spawnPlayer returned null", channelId: cleanChannelId };
|
||||
}
|
||||
|
||||
if (newPlayer.preferredVolume !== savedVolume) {
|
||||
newPlayer.setVolume(savedVolume);
|
||||
}
|
||||
|
||||
if (wasLoop) newPlayer.queue?.setLoop?.(true);
|
||||
if (wasSongLoop) newPlayer.queue?.setSongLoop?.(true);
|
||||
|
||||
if (savedFilter && savedFilterPayload) {
|
||||
newPlayer.activeFilter = savedFilter;
|
||||
newPlayer.activeFilterPayload = savedFilterPayload;
|
||||
}
|
||||
|
||||
if (currentTrack && newPlayer.queue) {
|
||||
try {
|
||||
newPlayer.queue.data = queueTracks;
|
||||
newPlayer.queue.current = null;
|
||||
await newPlayer.playNext();
|
||||
if (wasPaused) newPlayer.pause();
|
||||
} catch (e) { logger.warn("[Debug] queue restore:", e?.message); }
|
||||
}
|
||||
|
||||
if (wasAutoplay) {
|
||||
newPlayer._autoplay = true;
|
||||
newPlayer._autoplayHistory = player._autoplayHistory ?? [];
|
||||
try {
|
||||
const { attachAutoplay } = await import("../autoplay.mjs");
|
||||
attachAutoplay(newPlayer, ctx);
|
||||
} catch (e) {
|
||||
logger.warn("[Debug] autoplay re-attach failed:", e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
const newRoom = newPlayer.connection?.room;
|
||||
return {
|
||||
success: !!(newPlayer.connection && newRoom?.isConnected),
|
||||
roomConnected: newRoom?.isConnected ?? false,
|
||||
roomState: roomStateLabel(newRoom),
|
||||
resumedPlayback: !!(currentTrack && newPlayer.queue?.getCurrent()),
|
||||
channelId: cleanChannelId,
|
||||
};
|
||||
} catch (err) {
|
||||
logger.warn("[Debug] forceRejoinPlayer error:", err?.message);
|
||||
return { success: false, reason: err.message, channelId: cleanChannelId };
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Process a batch of players for force-rejoin, updating a status message with progress.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} ctx - The bot (Remix) instance context.
|
||||
* @param {Array} entries - Array of [channelId, player] tuples.
|
||||
* @param {object} statusMsg - The message to update with progress.
|
||||
* @param {string} title - The title for the progress display.
|
||||
* @returns {Promise<object[]>} Array of rejoin results.
|
||||
*/
|
||||
async function processRejoinBatch(ctx, entries, statusMsg, title) {
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const [cid, player] = entries[i];
|
||||
const label = buildPlayerLabel(ctx.client, cid, player);
|
||||
|
||||
const progressLines = [
|
||||
`🔄 **${title}** — Processing ${i + 1}/${entries.length}`,
|
||||
`Currently rejoining: \`${label}\``,
|
||||
``,
|
||||
];
|
||||
for (let j = 0; j < results.length; j++) {
|
||||
const r = results[j];
|
||||
const icon = r.success ? "✅" : "❌";
|
||||
progressLines.push(`${icon} \`${r.label}\`${r.success ? ` — room:${r.roomState}` : ` — failed (${r.reason ?? "?"})`}`);
|
||||
}
|
||||
await statusMsg.edit({ embeds: [new EmbedBuilder().setColor(WARN_COLOR).setTitle(`Debug — ${title}`).setDescription(progressLines.join("\n").slice(0, MAX_DESC))] }).catch(() => {});
|
||||
|
||||
const result = await forceRejoinPlayer(ctx, player);
|
||||
result.label = label;
|
||||
results.push(result);
|
||||
|
||||
if (i < entries.length - 1) {
|
||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
/**
|
||||
* Build the final embed summarizing rejoin results.
|
||||
* @private
|
||||
* @param {object[]} results - Array of rejoin result objects.
|
||||
* @param {string} title - The title for the embed.
|
||||
* @param {string} noun - The noun describing the rejoin targets.
|
||||
* @returns {object} Message payload with embed.
|
||||
*/
|
||||
function buildRejoinResultEmbed(results, title, noun) {
|
||||
const resultLines = [
|
||||
`🔄 **${title} Complete**`,
|
||||
`${noun.charAt(0).toUpperCase() + noun.slice(1)} processed: **${results.length}**`,
|
||||
``,
|
||||
];
|
||||
|
||||
let rejoinedCount = 0;
|
||||
let resumedCount = 0;
|
||||
let failedCount = 0;
|
||||
|
||||
for (const r of results) {
|
||||
if (r.success) {
|
||||
rejoinedCount++;
|
||||
if (r.resumedPlayback) resumedCount++;
|
||||
resultLines.push(`✅ \`${r.label}\` — rejoined (room:${r.roomState}, playback:${r.resumedPlayback ? "resumed" : "no track"})`);
|
||||
} else {
|
||||
failedCount++;
|
||||
resultLines.push(`❌ \`${r.label}\` — failed${r.reason ? ` (${r.reason})` : ""}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (failedCount === 0) {
|
||||
resultLines.push("", `All **${rejoinedCount}** ${noun} restored.${resumedCount > 0 ? ` ${resumedCount} had playback resumed.` : ""}`);
|
||||
} else {
|
||||
resultLines.push("", `⚠️ **${failedCount}** ${noun} could not be restored.`);
|
||||
}
|
||||
|
||||
const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR;
|
||||
return { embeds: [new EmbedBuilder().setColor(finalColor).setTitle(`Debug — ${title}`).setDescription(resultLines.join("\n").slice(0, MAX_DESC))] };
|
||||
}
|
||||
/**
|
||||
* Run a batch rejoin operation on matching players.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {string} key - Identifier key for the rejoin type.
|
||||
* @param {string} title - Display title for the operation.
|
||||
* @param {string} noun - Noun describing the targets.
|
||||
* @param {Function} filter - Function to filter which players to rejoin.
|
||||
* @param {boolean} [showHintIfEmpty=false] - Whether to show a hint if no matches found.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = false) {
|
||||
const allPlayers = [...this.players.playerMap.entries()];
|
||||
const matching = allPlayers.filter(([, player]) => filter(player));
|
||||
|
||||
if (matching.length === 0) {
|
||||
const has247 = allPlayers.some(([, player]) => player._home247Channel);
|
||||
const hintLine = showHintIfEmpty && has247
|
||||
? `\n\n💡 No ghosts auto-detected, but 24/7 channels with dead WebSockets may still report as "connected".\nUse \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`
|
||||
: "";
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(SUCCESS_COLOR)
|
||||
.setTitle(`Debug — ${title}`)
|
||||
.setDescription(`No ${noun} found. All voice connections appear healthy.${hintLine}`)
|
||||
;
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
const statusLines = [
|
||||
`🔄 **${title}** — Found **${matching.length}** ${noun}`,
|
||||
`Destroying stale connections and respawning fresh players...`,
|
||||
``,
|
||||
];
|
||||
|
||||
for (let i = 0; i < matching.length; i++) {
|
||||
const [cid, player] = matching[i];
|
||||
const label = buildPlayerLabel(this.client, cid, player);
|
||||
const ghost = isGhostConnection(player) ? " 👻GHOST" : "";
|
||||
const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none";
|
||||
const connectedLabel = player.connection?.room?.isConnected ? "yes" : "no";
|
||||
statusLines.push(`${i + 1}. \`${label}\` — room:${roomLabel} isConnected:${connectedLabel}${ghost}`);
|
||||
}
|
||||
|
||||
const statusEmbed = new EmbedBuilder()
|
||||
.setColor(WARN_COLOR)
|
||||
.setTitle(`Debug — ${title}`)
|
||||
.setDescription(statusLines.join("\n").slice(0, MAX_DESC))
|
||||
;
|
||||
const statusMsg = await msg.reply({ embeds: [statusEmbed] });
|
||||
|
||||
const results = await processRejoinBatch(this, matching, statusMsg, title);
|
||||
|
||||
const finalPayload = buildRejoinResultEmbed(results, title, noun);
|
||||
await statusMsg.edit(finalPayload).catch(() => {
|
||||
msg.reply(finalPayload);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
/**
|
||||
* @module commands/debug/voiceDiagnostic
|
||||
* @description Full voice diagnostic renderer for the debug command. Verbatim from the original single-file command.
|
||||
*/
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
import { getGlobalColor, cleanId } from "../../src/ui/index.mjs";
|
||||
import { DANGER_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs";
|
||||
import { MAX_DESC } from "./consts.mjs";
|
||||
import {
|
||||
roomStateLabel, isGhostConnection, getBotGatewayVoiceState, isStaleGatewayPresence,
|
||||
} from "./gateway.mjs";
|
||||
|
||||
/**
|
||||
* Run a full voice diagnostic, displaying player states and ghost connections.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function runVoiceDiagnostic(msg) {
|
||||
const servers = [...this.players.playerMap.entries()].map(([cid, s]) => {
|
||||
const channel = this.client.channels.get(cid);
|
||||
const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id;
|
||||
const guild = guildId ? this.client.guilds.get(cleanId(guildId)) : null;
|
||||
const conn = s.connection;
|
||||
const room = conn?.room;
|
||||
const ghost = isGhostConnection(s);
|
||||
const staleGateway = ghost ? isStaleGatewayPresence(this.client, s) : false;
|
||||
const gatewayVoiceState = getBotGatewayVoiceState(this.client, guildId);
|
||||
return {
|
||||
name: channel?.name ?? "unknown",
|
||||
id: channel?.id ?? cid,
|
||||
channelId: s._channelId ?? cid,
|
||||
guildId: guildId ?? "unknown",
|
||||
guildname: guild?.name ?? channel?.guild?.name ?? "unknown",
|
||||
conn: conn ? "yes" : "null",
|
||||
connDestroyed: conn?._destroyed ?? null,
|
||||
roomConnected: room?.isConnected ?? null,
|
||||
roomState: roomStateLabel(room),
|
||||
mediaPlayer: !!s._mediaPlayer && !s._mediaPlayer?.destroyed ? "alive" : (s._mediaPlayer?.destroyed ? "destroyed" : "none"),
|
||||
destroyed: s._destroyed ?? false,
|
||||
leaving: s.leaving ?? false,
|
||||
joining: s._isJoining ?? false,
|
||||
recovering: s._isRecovering ?? false,
|
||||
paused: s._paused ?? false,
|
||||
hasQueue: !!(s.queue?.getCurrent() || !s.queue?.isEmpty()),
|
||||
home247: s._home247Channel ?? null,
|
||||
ghost,
|
||||
staleGateway,
|
||||
gatewayVoiceChannel: gatewayVoiceState?.channelId ?? null,
|
||||
};
|
||||
});
|
||||
const pending = [...(this.players._pendingJoins ?? [])];
|
||||
|
||||
const ghostConnections = servers.filter(s => s.ghost);
|
||||
const livePlayers = servers.filter(s => s.conn === "yes" && !s.destroyed && !s.leaving);
|
||||
const actuallyConnected = livePlayers.filter(s => !s.ghost);
|
||||
const channels247 = servers.filter(s => s.home247);
|
||||
|
||||
const summary = {
|
||||
playerMapSize: this.players.playerMap.size,
|
||||
livePlayers: livePlayers.length,
|
||||
actuallyConnected: actuallyConnected.length,
|
||||
ghostConnections: ghostConnections.length,
|
||||
channels247: channels247.length,
|
||||
pendingJoins: pending.length,
|
||||
pendingChannels: pending,
|
||||
};
|
||||
|
||||
const pages = [];
|
||||
|
||||
const summaryLines = [
|
||||
`📊 **Summary**`,
|
||||
`Players in map: **${summary.playerMapSize}**`,
|
||||
`Live players: **${summary.livePlayers}**`,
|
||||
`Actually connected: **${summary.actuallyConnected}**`,
|
||||
`Ghost connections: **${summary.ghostConnections}**`,
|
||||
`24/7 channels: **${summary.channels247}**`,
|
||||
`Pending joins: **${summary.pendingJoins}**${summary.pendingChannels.length ? ` (\`${summary.pendingChannels.join("`, `")}\`)` : ""}`,
|
||||
];
|
||||
|
||||
if (ghostConnections.length > 0) {
|
||||
summaryLines.push("", `👻 **Ghost Connections (${ghostConnections.length}):**`, "These players *appear* in voice but their WebSocket/LiveKit room is dead:");
|
||||
summaryLines.push(`Use \`%debug voice-rejoin\` to rejoin detected ghosts, or \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`);
|
||||
for (const g of ghostConnections) {
|
||||
const gatewayInfo = g.staleGateway
|
||||
? `gateway:stale(ch:${g.gatewayVoiceChannel ?? "?"})`
|
||||
: `gateway:present(ch:${g.gatewayVoiceChannel ?? "?"})`;
|
||||
const detail = ` 👻 \`${g.guildname}\` / \`#${g.name}\` — room:${g.roomState} connected:${g.roomConnected} media:${g.mediaPlayer} ${gatewayInfo} 247:${g.home247 ?? "no"}`;
|
||||
if (summaryLines.join("\n").length + detail.length + 1 > MAX_DESC - 60) {
|
||||
summaryLines.push(` … and more ghosts (see JSON details)`);
|
||||
break;
|
||||
}
|
||||
summaryLines.push(detail);
|
||||
}
|
||||
}
|
||||
|
||||
if (channels247.length > 0 && ghostConnections.length === 0) {
|
||||
summaryLines.push("", `ℹ️ **24/7 Channels (${channels247.length}):**`, `WebSocket deaths can leave 24/7 channels as invisible ghosts (room reports healthy but transport is dead).`);
|
||||
summaryLines.push(`Use \`%debug 247-rejoin\` to force-rejoin all 24/7 channels if you suspect ghost connections.`);
|
||||
}
|
||||
|
||||
summaryLines.push("", "**Players:**");
|
||||
for (let i = 0; i < servers.length; i++) {
|
||||
const s = servers[i];
|
||||
let status;
|
||||
if (s.ghost) {
|
||||
status = "👻";
|
||||
} else if (s.conn === "yes" && !s.destroyed && !s.leaving) {
|
||||
status = "🟢";
|
||||
} else {
|
||||
status = "🔴";
|
||||
}
|
||||
const ghostTag = s.ghost ? " ⚠️GHOST" : "";
|
||||
const staleTag = s.staleGateway ? " ⚠️STALE_GW" : "";
|
||||
const tag247 = s.home247 ? " 🔄247" : "";
|
||||
const line = `${status} \`${s.guildname}\` / \`#${s.name}\` — conn:${s.conn} room:${s.roomState} connected:${s.roomConnected} media:${s.mediaPlayer}${ghostTag}${staleTag}${tag247}`;
|
||||
if (summaryLines.join("\n").length + line.length + 1 > MAX_DESC - 30) {
|
||||
summaryLines.push(`… and ${servers.length - i} more (see next pages)`);
|
||||
break;
|
||||
}
|
||||
summaryLines.push(line);
|
||||
}
|
||||
pages.push(summaryLines.join("\n"));
|
||||
|
||||
let groupJson = "";
|
||||
for (let i = 0; i < servers.length; i++) {
|
||||
const singleJson = JSON.stringify(servers[i], null, 2);
|
||||
const candidate = groupJson
|
||||
? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1)
|
||||
: singleJson;
|
||||
|
||||
const candidateLen = ("```json\n" + candidate + "\n```").length;
|
||||
|
||||
if (candidateLen > MAX_DESC && groupJson) {
|
||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||
groupJson = singleJson;
|
||||
} else if (candidateLen > MAX_DESC) {
|
||||
const budget = MAX_DESC - 12;
|
||||
pages.push(("```json\n" + singleJson.slice(0, budget) + "\n```").slice(0, MAX_DESC));
|
||||
groupJson = "";
|
||||
} else {
|
||||
groupJson = candidate;
|
||||
}
|
||||
}
|
||||
if (groupJson) {
|
||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||
}
|
||||
|
||||
if (pages.length === 1) {
|
||||
const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor();
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(embedColor)
|
||||
.setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""))
|
||||
.setDescription(pages[0].slice(0, MAX_DESC))
|
||||
;
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
const totalPages = pages.length;
|
||||
let currentPage = 0;
|
||||
|
||||
const buildPage = (pageIdx, expired = false) => {
|
||||
const isSummaryPage = pageIdx === 0;
|
||||
const pageLabel = isSummaryPage
|
||||
? "Summary"
|
||||
: `Player Detail${pages[pageIdx].split(`"name":`).length - 1 > 1 ? "s" : ""}`;
|
||||
const footerText = expired
|
||||
? this.t(msg, "responses._common.controlsExpired")
|
||||
: `${this.t(msg, "responses.debug.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`;
|
||||
|
||||
const embedColor = (isSummaryPage && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor();
|
||||
const titleSuffix = (isSummaryPage && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "";
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(embedColor)
|
||||
.setTitle(this.t(msg, "responses.debug.voiceTitle") + titleSuffix + ` — ${pageLabel}`)
|
||||
.setDescription(pages[pageIdx].slice(0, MAX_DESC))
|
||||
.setFooter({ text: footerText })
|
||||
;
|
||||
return { embeds: [embed] };
|
||||
};
|
||||
|
||||
const replyMsg = await msg.reply(buildPage(0));
|
||||
if (!replyMsg?.message) return;
|
||||
|
||||
const navEmojis = ["⬅️", "➡️", "❌"];
|
||||
for (const emoji of navEmojis) {
|
||||
await replyMsg.message.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await replyMsg.message.removeAllReactions();
|
||||
} catch (e) {
|
||||
for (const emoji of navEmojis) {
|
||||
try { await replyMsg.message.removeReaction(emoji); } catch (err) { logger.warn("[Debug] removeReaction fallback:", err?.message); }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let emojiTimeout;
|
||||
const resetTimer = () => {
|
||||
clearTimeout(emojiTimeout);
|
||||
emojiTimeout = setTimeout(async () => {
|
||||
unobserve?.();
|
||||
await clearReactions();
|
||||
await replyMsg.edit(buildPage(currentPage, true)).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||
const emoji = e?.emoji_id ?? e?.emoji?.id ?? e?.emoji;
|
||||
|
||||
if (emoji === "❌") {
|
||||
clearTimeout(emojiTimeout);
|
||||
unobserve?.();
|
||||
await replyMsg.message.delete().catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
resetTimer();
|
||||
|
||||
if (emoji === "⬅️") {
|
||||
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
||||
} else if (emoji === "➡️") {
|
||||
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
||||
});
|
||||
|
||||
resetTimer();
|
||||
}
|
||||
+5
-5
@@ -3,12 +3,12 @@
|
||||
* @description Owner-only command to evaluate arbitrary JavaScript code and display the result.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import { inspect } from "node:util";
|
||||
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||
|
||||
/** @private @type {string[]} Property name substrings that indicate sensitive/secret data. */
|
||||
const RESTRICTED = [
|
||||
@@ -88,7 +88,7 @@ function removeSensitive(obj, level = 0, visited = new WeakSet()) {
|
||||
* @private
|
||||
* @async
|
||||
* Sanitize a value for safe display: await promises, redact sensitive keys,
|
||||
* inspect with node:util, and escape Discord markup characters.
|
||||
* inspect with node:util, and escape markup characters.
|
||||
* @param {*} value - The raw eval result.
|
||||
* @returns {Promise<string>} The sanitized output string.
|
||||
*/
|
||||
|
||||
+5
-5
@@ -3,12 +3,12 @@
|
||||
* @description Interactive audio filter picker with emoji-based selection and pagination.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
import { PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI } from "../src/constants/UI.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { Utils } from "../src/utils/Utils.mjs";
|
||||
import { PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI } from "../src/utils/UI.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
|
||||
const NAV_EMOJIS = [PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI];
|
||||
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
* @description Force the bot to leave a voice channel (requires ManageChannels permission).
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { cleanId } from "../src/MessageHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { cleanId } from "../src/ui/index.mjs";
|
||||
|
||||
/**
|
||||
* @type {CommandBuilder}
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@
|
||||
* @description Display the bot invite link and support server information.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/**
|
||||
* @type {CommandBuilder}
|
||||
|
||||
+2
-2
@@ -6,9 +6,9 @@
|
||||
* 24/7 handling, event binding, and permission checks.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/ui/index.mjs";
|
||||
|
||||
/**
|
||||
* @type {CommandBuilder}
|
||||
|
||||
+32
-2510
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* @module commands/lastfm/account
|
||||
* @description Account linking, profile and playlist actions for the lastfm command (link, confirm, unlink, scrobble, np, profile, playlists). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||
*/
|
||||
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { Utils } from "../../src/utils/Utils.mjs";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||
import { notLinked } from "./shared.mjs";
|
||||
|
||||
/**
|
||||
* Action names dispatched to this module.
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
export const ACCOUNT_ACTIONS = new Set([
|
||||
"link",,
|
||||
"confirm",,
|
||||
"unlink",,
|
||||
"scrobble",,
|
||||
"np",,
|
||||
"profile",,
|
||||
"playlists"
|
||||
]);
|
||||
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} data - Parsed command data.
|
||||
* @param {object} lastfm - The Last.fm manager instance.
|
||||
* @param {string} prefix - The guild command prefix.
|
||||
* @param {string} userId - The invoking user's ID.
|
||||
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||
* @param {string} action - The resolved action name.
|
||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||
*/
|
||||
export async function runAccountActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||
switch (action) {
|
||||
case "link": {
|
||||
const existing = await lastfm.getUser(userId);
|
||||
if (existing) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription(this.t(msg, "responses.lastfm.alreadyLinked", { username: existing.username, prefix }))]
|
||||
});
|
||||
}
|
||||
|
||||
let token;
|
||||
try {
|
||||
token = await lastfm.getAuthToken();
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tokenFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
const authUrl = lastfm.getAuthUrl(token);
|
||||
|
||||
let sent = false;
|
||||
try {
|
||||
const dm = await msg.author.createDM();
|
||||
await dm.send({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.authLinkTitle"))
|
||||
.setDescription(this.t(msg, "responses.lastfm.authLinkBody", { url: authUrl, prefix, token }))
|
||||
]
|
||||
});
|
||||
sent = true;
|
||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
|
||||
const replyEmbed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription(
|
||||
sent
|
||||
? this.t(msg, "responses.lastfm.authDM", { prefix })
|
||||
: this.t(msg, "responses.lastfm.authDMFailed", { url: authUrl, prefix })
|
||||
);
|
||||
|
||||
return msg.reply({ embeds: [replyEmbed] });
|
||||
}
|
||||
|
||||
case "confirm": {
|
||||
let tokenValue = data.get("token")?.value;
|
||||
if (!tokenValue) {
|
||||
const rawContent = msg.message?.content ?? "";
|
||||
const args = rawContent.split(/\s+/);
|
||||
const confirmIdx = args.indexOf("confirm");
|
||||
tokenValue = confirmIdx >= 0 ? args[confirmIdx + 1] : null;
|
||||
}
|
||||
|
||||
if (!tokenValue) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmUsage", { prefix }))]
|
||||
});
|
||||
}
|
||||
|
||||
let session;
|
||||
try {
|
||||
session = await lastfm.getSession(tokenValue);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
await lastfm.saveUser(userId, session.key, session.name);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription(this.t(msg, "responses.lastfm.linked", { username: session.name }))]
|
||||
});
|
||||
}
|
||||
|
||||
case "unlink": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
await lastfm.removeUser(userId);
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.unlinked", { username: user.username }))]
|
||||
});
|
||||
}
|
||||
|
||||
case "scrobble": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const newState = !user.scrobbleEnabled;
|
||||
await lastfm.setScrobble(userId, newState);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription(newState
|
||||
? this.t(msg, "responses.lastfm.scrobbleEnabled", { username: user.username })
|
||||
: this.t(msg, "responses.lastfm.scrobbleDisabled")
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
case "np": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let recentData;
|
||||
try {
|
||||
recentData = await lastfm.getRecentTracks(userId, 1);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!recentData.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noRecent", { username: user.username }))]
|
||||
});
|
||||
}
|
||||
|
||||
const track = recentData[0];
|
||||
const statusEmoji = track.now ? this.t(msg, "responses.lastfm.nowPlaying") : this.t(msg, "responses.lastfm.lastPlayed");
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setAuthor({ name: statusEmoji, iconURL: track.image || undefined })
|
||||
.setDescription(this.t(msg, "responses.lastfm.npTrackInfo", { name: track.name, artist: track.artist, url: track.url }))
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.npFooter", { username: user.username }) });
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
case "profile": {
|
||||
const profileUserId = targetUserId || userId;
|
||||
const user = await lastfm.getUser(profileUserId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let info;
|
||||
try {
|
||||
info = await lastfm.getUserInfo(profileUserId);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
lastfm.syncUserScrobbleCount(profileUserId).catch(() => {});
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setAuthor({ name: this.t(msg, "responses.lastfm.profileTitle", { username: info.name }), iconURL: info.image?.[2]?.["#text"] || undefined, url: info.url })
|
||||
.setDescription([
|
||||
this.t(msg, "responses.lastfm.profileScrobbles", { playcount: Utils.formatNumber(info.playcount ?? 0) }),
|
||||
this.t(msg, "responses.lastfm.profileRegistered", { date: info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown" }),
|
||||
this.t(msg, "responses.lastfm.profileScrobbleStatus", { status: user.scrobbleEnabled ? this.t(msg, "responses.lastfm.profileScrobbleEnabled") : this.t(msg, "responses.lastfm.profileScrobbleDisabled") }),
|
||||
``,
|
||||
this.t(msg, "responses.lastfm.profileLink", { url: info.url }),
|
||||
].join("\n"))
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.profileScrobbleFooter", { prefix }) });
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
case "playlists": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let playlists;
|
||||
try {
|
||||
playlists = await lastfm.getPlaylists(userId);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!playlists.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noPlaylists", { username: user.username }))]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = playlists.map((pl, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = pl.url ? `[${pl.title}](${pl.url})` : pl.title;
|
||||
return `\`${num}.\` ${link} — **${pl.trackCount}** tracks`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.playlistsTitle", { username: user.username }))
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.playlistsFooter", { prefix }) })]
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
/**
|
||||
* @module commands/lastfm/discovery
|
||||
* @description Charts and discovery actions for the lastfm command (friends, weekly, trending, geo, artisttracks, search). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||
*/
|
||||
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { Utils } from "../../src/utils/Utils.mjs";
|
||||
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||
import { notLinked, extractCurrentTrack } from "./shared.mjs";
|
||||
|
||||
/**
|
||||
* Action names dispatched to this module.
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
export const DISCOVERY_ACTIONS = new Set([
|
||||
"friends",,
|
||||
"fr",,
|
||||
"weekly",,
|
||||
"wc",,
|
||||
"trending",,
|
||||
"tr",,
|
||||
"geo",,
|
||||
"g",,
|
||||
"artisttracks",,
|
||||
"atr",,
|
||||
"search",,
|
||||
"s"
|
||||
]);
|
||||
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} data - Parsed command data.
|
||||
* @param {object} lastfm - The Last.fm manager instance.
|
||||
* @param {string} prefix - The guild command prefix.
|
||||
* @param {string} userId - The invoking user's ID.
|
||||
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||
* @param {string} action - The resolved action name.
|
||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||
*/
|
||||
export async function runDiscoveryActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||
switch (action) {
|
||||
case "friends":
|
||||
case "fr": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let friends;
|
||||
try {
|
||||
friends = await lastfm.getUserFriends(userId, 20);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!friends.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`👥 No friends found for **${user.username}**.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = friends.map((f, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = f.url ? `[${f.name}](${f.url})` : f.name;
|
||||
const details = [];
|
||||
if (f.realname) details.push(f.realname);
|
||||
if (f.country) details.push(f.country);
|
||||
const detailStr = details.length > 0 ? ` (${details.join(", ")})` : "";
|
||||
return `\`${num}.\` ${link}${detailStr}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`👥 Friends — ${user.username}`)
|
||||
.setDescription(desc)]
|
||||
});
|
||||
}
|
||||
|
||||
case "weekly":
|
||||
case "wc": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const tokenTextWc = data.get("token")?.value?.toLowerCase().trim() ?? "artists";
|
||||
let chartData;
|
||||
let chartTitle;
|
||||
|
||||
try {
|
||||
if (tokenTextWc === "tracks") {
|
||||
chartData = await lastfm.getUserWeeklyTrackChart(userId);
|
||||
chartTitle = `📅 Weekly Track Chart — ${user.username}`;
|
||||
} else if (tokenTextWc === "albums") {
|
||||
chartData = await lastfm.getUserWeeklyAlbumChart(userId);
|
||||
chartTitle = `📅 Weekly Album Chart — ${user.username}`;
|
||||
} else {
|
||||
chartData = await lastfm.getUserWeeklyArtistChart(userId);
|
||||
chartTitle = `📅 Weekly Artist Chart — ${user.username}`;
|
||||
}
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!chartData.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`📅 No weekly chart data found for **${user.username}**.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = chartData.slice(0, 15).map((item, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = item.url ? `[${item.name}](${item.url})` : item.name;
|
||||
const artistStr = item.artist ? ` by **${item.artist}**` : "";
|
||||
return `\`${num}.\` ${link}${artistStr} — **${Utils.formatNumber(item.playcount)}** plays`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(chartTitle)
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: `💡 Use token option: artists, tracks, or albums` })]
|
||||
});
|
||||
}
|
||||
|
||||
case "trending":
|
||||
case "tr": {
|
||||
const tokenTextTr = data.get("token")?.value?.toLowerCase().trim() ?? "tracks";
|
||||
let trendingData;
|
||||
let trendingTitle;
|
||||
|
||||
try {
|
||||
if (tokenTextTr === "artists") {
|
||||
trendingData = await lastfm.getChartTopArtists(15);
|
||||
trendingTitle = "🔥 Trending Artists on Last.fm";
|
||||
} else {
|
||||
trendingData = await lastfm.getChartTopTracks(15);
|
||||
trendingTitle = "🔥 Trending Tracks on Last.fm";
|
||||
}
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!trendingData.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🔥 No trending data found.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = trendingData.map((item, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = item.url ? `[${item.name}](${item.url})` : item.name;
|
||||
const artistStr = item.artist ? ` by **${item.artist}**` : "";
|
||||
const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} listeners` : item.playcount ? ` — ${Utils.formatNumber(item.playcount)} plays` : "";
|
||||
return `\`${num}.\` ${link}${artistStr}${extra}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(trendingTitle)
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: `💡 Use token option: tracks or artists` })]
|
||||
});
|
||||
}
|
||||
|
||||
case "geo":
|
||||
case "g": {
|
||||
const tokenTextG = data.get("token")?.value?.trim() ?? "";
|
||||
if (!tokenTextG) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a query like \`artists <country>\` or \`tracks <country>\`. Example: \`${prefix}lastfm geo artists united states\`.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const lowerToken = tokenTextG.toLowerCase();
|
||||
let type = "artists";
|
||||
let country = tokenTextG;
|
||||
|
||||
if (lowerToken.startsWith("artists ")) {
|
||||
type = "artists";
|
||||
country = tokenTextG.slice(8).trim();
|
||||
} else if (lowerToken.startsWith("tracks ")) {
|
||||
type = "tracks";
|
||||
country = tokenTextG.slice(7).trim();
|
||||
}
|
||||
|
||||
if (!country) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Please specify a country name. Example: \`${prefix}lastfm geo artists united states\`.`)]
|
||||
});
|
||||
}
|
||||
|
||||
let geoData;
|
||||
let geoTitle;
|
||||
|
||||
try {
|
||||
if (type === "tracks") {
|
||||
geoData = await lastfm.getGeoTopTracks(country, 15);
|
||||
geoTitle = `🌍 Top Tracks in ${country}`;
|
||||
} else {
|
||||
geoData = await lastfm.getGeoTopArtists(country, 15);
|
||||
geoTitle = `🌍 Top Artists in ${country}`;
|
||||
}
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!geoData.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🌍 No data found for **${country}**.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = geoData.map((item, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = item.url ? `[${item.name}](${item.url})` : item.name;
|
||||
const artistStr = item.artist ? ` by **${item.artist}**` : "";
|
||||
const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} listeners` : "";
|
||||
return `\`${num}.\` ${link}${artistStr}${extra}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(geoTitle)
|
||||
.setDescription(desc)]
|
||||
});
|
||||
}
|
||||
|
||||
case "artisttracks":
|
||||
case "atr": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let artistName = null;
|
||||
|
||||
const pAtr = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pAtr);
|
||||
if (current?.artist) {
|
||||
artistName = current.artist;
|
||||
}
|
||||
|
||||
const tokenTextAtr = data.get("token")?.value;
|
||||
if (tokenTextAtr) {
|
||||
artistName = tokenTextAtr.trim();
|
||||
}
|
||||
|
||||
if (!artistName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))]
|
||||
});
|
||||
}
|
||||
|
||||
let recentTracks;
|
||||
try {
|
||||
recentTracks = await lastfm.getRecentTracks(userId, 200);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
const artistTracks = recentTracks.filter(t =>
|
||||
t.artist.toLowerCase() === artistName.toLowerCase()
|
||||
);
|
||||
|
||||
if (!artistTracks.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🎵 No scrobbles found for **${artistName}** in your recent history.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = artistTracks.slice(0, 15).map((t, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||
const nowStr = t.now ? " 🎵" : "";
|
||||
return `\`${num}.\` ${link}${nowStr}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`🎵 ${artistName} Scrobbles — ${user.username}`)
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: `${artistTracks.length} scrobble${artistTracks.length !== 1 ? "s" : ""} found` })]
|
||||
});
|
||||
}
|
||||
|
||||
case "search":
|
||||
case "s": {
|
||||
const query = data.get("token")?.value;
|
||||
if (!query) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a search query via the token option. Example: \`${prefix}lastfm search radiohead\``)]
|
||||
});
|
||||
}
|
||||
|
||||
let artistResults, albumResults, trackResult;
|
||||
try {
|
||||
[artistResults, albumResults, trackResult] = await Promise.all([
|
||||
lastfm.searchArtist(query, 5),
|
||||
lastfm.searchAlbum(query, 5),
|
||||
lastfm.searchTrack(query),
|
||||
]);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
const sections = [];
|
||||
|
||||
if (artistResults.length) {
|
||||
const artistLines = artistResults.map((a, i) => {
|
||||
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||
const listeners = a.listeners ? ` — ${Utils.formatNumber(a.listeners)} listeners` : "";
|
||||
return `${i + 1}. ${link}${listeners}`;
|
||||
});
|
||||
sections.push(`**🎤 Artists:**\n${artistLines.join("\n")}`);
|
||||
}
|
||||
|
||||
if (albumResults.length) {
|
||||
const albumLines = albumResults.map((a, i) => {
|
||||
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||
return `${i + 1}. ${link} by **${a.artist}**`;
|
||||
});
|
||||
sections.push(`**💿 Albums:**\n${albumLines.join("\n")}`);
|
||||
}
|
||||
|
||||
if (trackResult) {
|
||||
sections.push(`**🎵 Best Track Match:**\n[${trackResult.name}](${trackResult.url}) by **${trackResult.artist}**`);
|
||||
}
|
||||
|
||||
if (!sections.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🔍 No results found for **${query}**.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const desc = sections.join("\n\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`🔍 Search Results for "${query}"`)
|
||||
.setDescription(desc)]
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* @module commands/lastfm/help
|
||||
* @description Fallback help action for the lastfm command (the original
|
||||
* switch's `default` branch). Extracted verbatim; reached when the action
|
||||
* matches no known action name.
|
||||
*/
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} data - Parsed command data.
|
||||
* @param {object} lastfm - The Last.fm manager instance.
|
||||
* @param {string} prefix - The guild command prefix.
|
||||
* @param {string} userId - The invoking user's ID.
|
||||
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||
* @param {string} action - The resolved action name.
|
||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||
*/
|
||||
export async function runLastFmHelp(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription([
|
||||
`🎵 **Last.fm Commands:**`,
|
||||
``,
|
||||
`\`${prefix}lastfm link\` — Link your Last.fm account`,
|
||||
`\`${prefix}lastfm unlink\` — Disconnect your account`,
|
||||
`\`${prefix}lastfm scrobble\` — Toggle auto-scrobbling`,
|
||||
`\`${prefix}lastfm np\` — Show your Last.fm now playing`,
|
||||
`\`${prefix}lastfm profile\` — View your Last.fm profile (or another user's with user option)`,
|
||||
`\`${prefix}lastfm loved\` — View your loved tracks`,
|
||||
`\`${prefix}lastfm top\` — View your top tracks (supports period)`,
|
||||
`\`${prefix}lastfm artists\` — View your top artists (supports period)`,
|
||||
`\`${prefix}lastfm recent\` — View your recent tracks`,
|
||||
`\`${prefix}lastfm playlists\` — View your Last.fm playlists`,
|
||||
`\`${prefix}lastfm leaderboard\` — Scrobble leaderboard`,
|
||||
`\`${prefix}lastfm love\` — Love the current track`,
|
||||
`\`${prefix}lastfm unlove\` — Unlove the current track`,
|
||||
``,
|
||||
`🔍 **Info Commands:**`,
|
||||
`\`${prefix}lastfm whoknows [artist]\` — Who in the server listens to an artist`,
|
||||
`\`${prefix}lastfm whoknowstrack\` — Who knows a specific track`,
|
||||
`\`${prefix}lastfm whoknowsalbum\` — Who knows a specific album`,
|
||||
`\`${prefix}lastfm artistinfo\` — Detailed info about an artist`,
|
||||
`\`${prefix}lastfm albuminfo\` — Detailed info about an album`,
|
||||
`\`${prefix}lastfm trackinfo\` — Detailed info about a track`,
|
||||
`\`${prefix}lastfm topalbums\` — View your top albums (supports period)`,
|
||||
`\`${prefix}lastfm toptags\` — View your top tags/genres`,
|
||||
`\`${prefix}lastfm tag <name>\` — View info about a specific tag`,
|
||||
`\`${prefix}lastfm compare @user\` — Compare your taste with another user`,
|
||||
`\`${prefix}lastfm cover\` — Get album cover art for the current track`,
|
||||
``,
|
||||
`🏷️ **Tag Commands:**`,
|
||||
`\`${prefix}lastfm artisttags\` — Top tags for an artist`,
|
||||
`\`${prefix}lastfm albumtags\` — Top tags for an album`,
|
||||
`\`${prefix}lastfm tracktags\` — Top tags for a track`,
|
||||
`\`${prefix}lastfm tagalbums <tag>\` — Top albums for a tag`,
|
||||
``,
|
||||
`👥 **Social Commands:**`,
|
||||
`\`${prefix}lastfm affinity\` — Find users with similar taste`,
|
||||
`\`${prefix}lastfm crowns\` — View your artist crowns (#1 listener)`,
|
||||
`\`${prefix}lastfm friends\` — View your Last.fm friends`,
|
||||
`\`${prefix}lastfm refreshmembers\` — Refresh server member cache`,
|
||||
``,
|
||||
`📊 **Charts & Discovery:**`,
|
||||
`\`${prefix}lastfm weekly [artists|tracks|albums]\` — Weekly charts`,
|
||||
`\`${prefix}lastfm trending [tracks|artists]\` — Global trending on Last.fm`,
|
||||
`\`${prefix}lastfm geo [artists|tracks] <country>\` — Top by country`,
|
||||
`\`${prefix}lastfm artisttracks\` — Your scrobbles for an artist`,
|
||||
`\`${prefix}lastfm search <query>\` — Universal search`,
|
||||
``,
|
||||
`🎶 **Play from Last.fm:**`,
|
||||
`\`${prefix}lastfm play loved\` — Play your loved tracks`,
|
||||
`\`${prefix}lastfm play top\` — Play your top tracks`,
|
||||
`\`${prefix}lastfm play recent\` — Play your recent tracks`,
|
||||
`\`${prefix}lastfm play albums\` — Play your top albums`,
|
||||
`\`${prefix}lastfm play artists\` — Play your top artists' tracks`,
|
||||
`\`${prefix}lastfm play playlist 1\` — Play a playlist`,
|
||||
``,
|
||||
`🎧 **Play with a specific provider (defaults to \`top\`):**`,
|
||||
`\`${prefix}lastfm play sp\` or \`${prefix}lastfm play sp:top\` — Play top tracks, search on Spotify`,
|
||||
`\`${prefix}lastfm play td\` or \`${prefix}lastfm play td:top\` — Play top tracks, search on Tidal`,
|
||||
`\`${prefix}lastfm play dz\` or \`${prefix}lastfm play dz:top\` — Play top tracks, search on Deezer`,
|
||||
`\`${prefix}lastfm play yt\` or \`${prefix}lastfm play yt:top\` — Play top tracks, search on YouTube`,
|
||||
``,
|
||||
`🎧 **Last.fm as resolve provider (all categories):**`,
|
||||
`\`${prefix}lastfm play lf:loved\` — Play loved tracks, search on Last.fm`,
|
||||
`\`${prefix}lastfm play lf:top\` — Play top tracks, search on Last.fm`,
|
||||
`\`${prefix}lastfm play lf:recent\` — Play recent tracks, search on Last.fm`,
|
||||
`\`${prefix}lastfm play lf:albums\` — Play top albums, search on Last.fm`,
|
||||
`\`${prefix}lastfm play lf:artists\` — Play top artists, search on Last.fm`,
|
||||
``,
|
||||
`💡 Or use inline: \`${prefix}play lastfm:loved\` or \`${prefix}play lastfm:sp\` or \`${prefix}play lastfm:td:top\``,
|
||||
].join("\n"))]
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* @module commands/lastfm
|
||||
* @description Barrel for the lastfm command group implementation modules.
|
||||
* commands/lastfm.mjs (the command entry file) dispatches through this
|
||||
* barrel; it stays the single import surface for the group.
|
||||
*/
|
||||
|
||||
export { notConfigured, notLinked, extractCurrentTrack, extractPeriod, VALID_PERIODS } from "./shared.mjs";
|
||||
export { runAccountActions, ACCOUNT_ACTIONS } from "./account.mjs";
|
||||
export { runPlaybackActions, PLAYBACK_ACTIONS, playLastFmCategory } from "./playback.mjs";
|
||||
export { runListeningActions, LISTENING_ACTIONS } from "./listening.mjs";
|
||||
export { runWhoknowsActions, WHOKNOWS_ACTIONS } from "./whoknows.mjs";
|
||||
export { runInfoActions, INFO_ACTIONS } from "./info.mjs";
|
||||
export { runTagActions, TAG_ACTIONS } from "./tags.mjs";
|
||||
export { runDiscoveryActions, DISCOVERY_ACTIONS } from "./discovery.mjs";
|
||||
export { runLastFmHelp } from "./help.mjs";
|
||||
@@ -0,0 +1,505 @@
|
||||
/**
|
||||
* @module commands/lastfm/info
|
||||
* @description Metadata lookup actions for the lastfm command (artistinfo, albuminfo, trackinfo, topalbums, toptags, cover) with the duration formatter. Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||
*/
|
||||
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { Utils } from "../../src/utils/Utils.mjs";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||
import { notLinked, extractCurrentTrack, extractPeriod } from "./shared.mjs";
|
||||
|
||||
/**
|
||||
* Action names dispatched to this module.
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
export const INFO_ACTIONS = new Set([
|
||||
"artistinfo",,
|
||||
"ai",,
|
||||
"albuminfo",,
|
||||
"ali",,
|
||||
"trackinfo",,
|
||||
"ti",,
|
||||
"topalbums",,
|
||||
"toptags",,
|
||||
"tags",,
|
||||
"cover",,
|
||||
"art"
|
||||
]);
|
||||
|
||||
|
||||
/**
|
||||
* Format seconds into a human-readable duration string (h:mm:ss or m:ss).
|
||||
* @private
|
||||
* @param {number} seconds - Duration in seconds.
|
||||
* @returns {string} Formatted duration, or empty string if invalid.
|
||||
*/
|
||||
function formatDuration(seconds) {
|
||||
if (!seconds || seconds <= 0) return "";
|
||||
const h = Math.floor(seconds / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
const s = seconds % 60;
|
||||
if (h > 0) {
|
||||
return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
|
||||
}
|
||||
return `${m}:${String(s).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} data - Parsed command data.
|
||||
* @param {object} lastfm - The Last.fm manager instance.
|
||||
* @param {string} prefix - The guild command prefix.
|
||||
* @param {string} userId - The invoking user's ID.
|
||||
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||
* @param {string} action - The resolved action name.
|
||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||
*/
|
||||
export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||
switch (action) {
|
||||
case "artistinfo":
|
||||
case "ai": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
|
||||
let artistName = null;
|
||||
|
||||
const pAi = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pAi);
|
||||
if (current?.artist) {
|
||||
artistName = current.artist;
|
||||
}
|
||||
|
||||
const tokenText = data.get("token")?.value;
|
||||
if (tokenText) {
|
||||
artistName = tokenText.trim();
|
||||
}
|
||||
|
||||
if (!artistName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
this.t(msg, "responses.lastfm.noArtistSpecified")
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
let info;
|
||||
try {
|
||||
info = await lastfm.getArtistInfo(artistName, userId);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!info) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.artistNotFound", { artist: artistName }))]
|
||||
});
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`🎤 ${info.name}`)
|
||||
.setURL(info.url || undefined)
|
||||
.setThumbnail(info.image || undefined);
|
||||
|
||||
const fields = [];
|
||||
fields.push({ name: "Listeners", value: Utils.formatNumber(info.stats?.listeners ?? 0), inline: true });
|
||||
fields.push({ name: "Global Plays", value: Utils.formatNumber(info.stats?.playcount ?? 0), inline: true });
|
||||
|
||||
if (info.userplaycount != null && user) {
|
||||
fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true });
|
||||
}
|
||||
|
||||
if (info.tags?.length) {
|
||||
const tagStr = info.tags.slice(0, 8).map(t => {
|
||||
const tagLower = String(t).toLowerCase().replace(/\s+/g, "+");
|
||||
return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
||||
}).join(" · ");
|
||||
fields.push({ name: "Tags", value: tagStr, inline: false });
|
||||
}
|
||||
|
||||
if (info.similar?.length) {
|
||||
const simStr = info.similar.slice(0, 5).map(s => {
|
||||
return s.url ? `[${s.name}](${s.url})` : s.name;
|
||||
}).join(" · ");
|
||||
fields.push({ name: "Similar Artists", value: simStr, inline: false });
|
||||
}
|
||||
|
||||
embed.addFields(...fields);
|
||||
|
||||
if (info.bio) {
|
||||
const cleanBio = info.bio.replace(/<[^>]*>/g, "").trim();
|
||||
if (cleanBio.length > 0) {
|
||||
const truncated = cleanBio.length > 300 ? cleanBio.slice(0, 297) + "..." : cleanBio;
|
||||
embed.setDescription(truncated);
|
||||
}
|
||||
}
|
||||
|
||||
embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" });
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
case "albuminfo":
|
||||
case "ali": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
|
||||
let artistName = null;
|
||||
let albumName = null;
|
||||
|
||||
const pAli = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pAli);
|
||||
if (current?.album && current?.artist) {
|
||||
artistName = current.artist;
|
||||
albumName = current.album;
|
||||
}
|
||||
|
||||
const tokenText = data.get("token")?.value;
|
||||
if (tokenText) {
|
||||
const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||
if (dashMatch) {
|
||||
artistName = dashMatch[1].trim();
|
||||
albumName = dashMatch[2].trim();
|
||||
} else {
|
||||
albumName = tokenText.trim();
|
||||
}
|
||||
}
|
||||
|
||||
if (!albumName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
this.t(msg, "responses.lastfm.noAlbumSpecified")
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
let info;
|
||||
try {
|
||||
info = await lastfm.getAlbumInfo(artistName || "", albumName, userId);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!info) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.albumNotFound", { album: albumName }))]
|
||||
});
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`💿 ${info.name}`)
|
||||
.setURL(info.url || undefined)
|
||||
.setThumbnail(info.image || undefined);
|
||||
|
||||
const fields = [];
|
||||
|
||||
if (info.artist) {
|
||||
fields.push({ name: "Artist", value: info.artist, inline: true });
|
||||
}
|
||||
|
||||
if (info.userplaycount != null && user) {
|
||||
fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true });
|
||||
}
|
||||
|
||||
if (info.tags?.length) {
|
||||
const tagStr = info.tags.slice(0, 8).map(t => {
|
||||
const tagLower = String(t).toLowerCase().replace(/\s+/g, "+");
|
||||
return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
||||
}).join(" · ");
|
||||
fields.push({ name: "Tags", value: tagStr, inline: false });
|
||||
}
|
||||
|
||||
if (info.tracks?.length) {
|
||||
const trackLines = info.tracks.slice(0, 15).map((t, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const dur = t.duration > 0 ? ` (${formatDuration(t.duration)})` : "";
|
||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||
return `\`${num}.\` ${link}${dur}`;
|
||||
});
|
||||
fields.push({ name: "Tracklist", value: trackLines.join("\n").slice(0, 1024), inline: false });
|
||||
}
|
||||
|
||||
embed.addFields(...fields);
|
||||
embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" });
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
case "trackinfo":
|
||||
case "ti": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let artistName = null;
|
||||
let trackName = null;
|
||||
|
||||
const pTi = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pTi);
|
||||
if (current?.artist && current?.name) {
|
||||
artistName = current.artist;
|
||||
trackName = current.name;
|
||||
}
|
||||
|
||||
const tokenText = data.get("token")?.value;
|
||||
if (tokenText) {
|
||||
const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||
if (dashMatch) {
|
||||
artistName = dashMatch[1].trim();
|
||||
trackName = dashMatch[2].trim();
|
||||
} else {
|
||||
try {
|
||||
const searchResult = await lastfm.searchTrack(tokenText.trim());
|
||||
if (searchResult) {
|
||||
artistName = searchResult.artist;
|
||||
trackName = searchResult.name;
|
||||
}
|
||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
}
|
||||
}
|
||||
|
||||
if (!artistName || !trackName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
this.t(msg, "responses.lastfm.noTrackSpecified")
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
let info;
|
||||
try {
|
||||
info = await lastfm.getTrackInfo(artistName, trackName, userId);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!info) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.trackNotFound", { track: trackName, artist: artistName }))]
|
||||
});
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`🎵 ${info.name}`)
|
||||
.setURL(info.url || undefined);
|
||||
|
||||
if (info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]) {
|
||||
embed.setThumbnail(info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]);
|
||||
}
|
||||
|
||||
const fields = [];
|
||||
|
||||
if (info.artist?.name || info.artist?.["#text"]) {
|
||||
fields.push({ name: "Artist", value: String(info.artist?.name ?? info.artist?.["#text"] ?? "Unknown"), inline: true });
|
||||
}
|
||||
|
||||
if (info.album?.title) {
|
||||
fields.push({ name: "Album", value: info.album.title, inline: true });
|
||||
}
|
||||
|
||||
if (info.listeners) {
|
||||
fields.push({ name: "Listeners", value: Utils.formatNumber(Number(info.listeners)), inline: true });
|
||||
}
|
||||
|
||||
if (info.playcount) {
|
||||
fields.push({ name: "Global Plays", value: Utils.formatNumber(Number(info.playcount)), inline: true });
|
||||
}
|
||||
|
||||
if (info.userplaycount) {
|
||||
fields.push({ name: "Your Plays", value: Utils.formatNumber(Number(info.userplaycount)), inline: true });
|
||||
}
|
||||
|
||||
const userLoved = info.userloved === "1" || info.userloved === 1 || info.userloved === true;
|
||||
fields.push({ name: "Loved", value: userLoved ? "❤️ Yes" : "🖤 No", inline: true });
|
||||
|
||||
if (info.toptags?.tag?.length) {
|
||||
const tagStr = info.toptags.tag.slice(0, 8).map(t => {
|
||||
const tagName = t.name ?? t;
|
||||
const tagLower = String(tagName).toLowerCase().replace(/\s+/g, "+");
|
||||
return `[${tagName}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
||||
}).join(" · ");
|
||||
fields.push({ name: "Tags", value: tagStr, inline: false });
|
||||
}
|
||||
|
||||
embed.addFields(...fields);
|
||||
|
||||
if (info.wiki?.summary) {
|
||||
const cleanSummary = info.wiki.summary.replace(/<[^>]*>/g, "").trim();
|
||||
if (cleanSummary.length > 0) {
|
||||
const truncated = cleanSummary.length > 200 ? cleanSummary.slice(0, 197) + "..." : cleanSummary;
|
||||
embed.setDescription(truncated);
|
||||
}
|
||||
}
|
||||
|
||||
let similarTracks = [];
|
||||
try {
|
||||
similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 5);
|
||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
|
||||
if (similarTracks.length) {
|
||||
const simStr = similarTracks.map(t => {
|
||||
const matchPct = Math.round(t.match * 100);
|
||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||
return `${link} by **${t.artist}** (${matchPct}%)`;
|
||||
}).join("\n");
|
||||
embed.addFields({ name: "Similar Tracks", value: simStr.slice(0, 1024), inline: false });
|
||||
}
|
||||
|
||||
embed.setFooter({ text: `Last.fm: ${user.username}` });
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
case "topalbums": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const period = extractPeriod(data, msg);
|
||||
|
||||
let albums;
|
||||
try {
|
||||
albums = await lastfm.getTopAlbums(userId, period, 15);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!albums.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTopAlbums", { username: user.username }))]
|
||||
});
|
||||
}
|
||||
|
||||
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
||||
|
||||
const lines = albums.map((a, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
let albumTitle = a.name;
|
||||
if (albumTitle.length > 30) albumTitle = albumTitle.slice(0, 27) + "...";
|
||||
const link = a.url ? `[${albumTitle}](${a.url})` : albumTitle;
|
||||
return `\`${num}.\` ${link} — **${a.artist}** (**${a.playcount}** plays)`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.topAlbumsTitle", { period: periodLabel, username: user.username }))
|
||||
.setDescription(desc);
|
||||
|
||||
if (albums[0]?.image) {
|
||||
embed.setThumbnail(albums[0].image);
|
||||
}
|
||||
|
||||
embed.setFooter({ text: this.t(msg, "responses.lastfm.topAlbumsFooter", { prefix }) });
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
case "toptags":
|
||||
case "tags": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let tags;
|
||||
try {
|
||||
tags = await lastfm.getUserTopTags(userId, 20);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!tags.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTopTags", { username: user.username }))]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = tags.map((t, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||
return `\`${num}.\` ${link} — **${t.count}**`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.topTagsTitle", { username: user.username }))
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.topTagsFooter", { prefix }) })]
|
||||
});
|
||||
}
|
||||
|
||||
case "cover":
|
||||
case "art": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const pCover = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pCover);
|
||||
if (!current || !current.name) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.coverNothingPlaying"))]
|
||||
});
|
||||
}
|
||||
|
||||
const artistName = current.artist ?? "Unknown";
|
||||
const trackName = current.name;
|
||||
const albumName = current.album;
|
||||
|
||||
let coverUrl = null;
|
||||
let albumTitle = albumName ?? "Unknown Album";
|
||||
|
||||
if (albumName) {
|
||||
try {
|
||||
const albumInfo = await lastfm.getAlbumInfo(artistName, albumName, userId);
|
||||
if (albumInfo?.image) {
|
||||
coverUrl = albumInfo.image;
|
||||
albumTitle = `${albumInfo.name} by ${albumInfo.artist}`;
|
||||
}
|
||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
}
|
||||
|
||||
if (!coverUrl) {
|
||||
try {
|
||||
const trackInfo = await lastfm.getTrackInfo(artistName, trackName, userId);
|
||||
if (trackInfo?.album?.image) {
|
||||
const images = trackInfo.album.image;
|
||||
coverUrl = images?.[2]?.["#text"] || images?.[1]?.["#text"] || images?.[0]?.["#text"] || null;
|
||||
if (trackInfo.album?.title) {
|
||||
albumTitle = trackInfo.album.title;
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
}
|
||||
|
||||
if (!coverUrl) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.coverNotFound", { track: trackName, artist: artistName }))]
|
||||
});
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.coverTitle", { album: albumTitle }))
|
||||
.setImage(coverUrl)
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.coverFooter", { track: trackName, artist: artistName }) });
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
/**
|
||||
* @module commands/lastfm/listening
|
||||
* @description Personal listening actions for the lastfm command (loved, top, leaderboard, recent, artists, love, unlove) with their list/leaderboard embed builders. Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||
*/
|
||||
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { Utils } from "../../src/utils/Utils.mjs";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs";
|
||||
import { notLinked, extractPeriod } from "./shared.mjs";
|
||||
|
||||
/**
|
||||
* Action names dispatched to this module.
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
export const LISTENING_ACTIONS = new Set([
|
||||
"loved",,
|
||||
"top",,
|
||||
"leaderboard",,
|
||||
"lb",,
|
||||
"recent",,
|
||||
"artists",,
|
||||
"love",,
|
||||
"unlove"
|
||||
]);
|
||||
|
||||
|
||||
/**
|
||||
* Build an embed listing tracks with optional playcount.
|
||||
* @private
|
||||
* @param {string} username - The Last.fm username.
|
||||
* @param {string} title - The list title.
|
||||
* @param {object[]} tracks - Array of track objects with name, artist, url, and optional playcount.
|
||||
* @param {boolean} [showPlaycount=false] - Whether to show play counts.
|
||||
* @param {string} [prefix="%"] - The command prefix for the footer hint.
|
||||
* @returns {EmbedBuilder} The constructed embed.
|
||||
*/
|
||||
function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") {
|
||||
const lines = tracks.map((t, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
let name = t.name;
|
||||
if (name.length > 40) name = name.slice(0, 37) + "...";
|
||||
const link = t.url ? `[${name}](${t.url})` : name;
|
||||
const extra = showPlaycount && t.playcount ? ` (${t.playcount} plays)` : "";
|
||||
return `\`${num}.\` ${link} — **${t.artist}**${extra}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`${title} — ${username}`)
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` });
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a scrobble leaderboard embed for a given page.
|
||||
* @private
|
||||
* @param {object} lb - Leaderboard data with entries and perPage.
|
||||
* @param {number} pageIdx - The page index (0-based).
|
||||
* @param {string} prefix - The command prefix for the footer hint.
|
||||
* @returns {EmbedBuilder} The constructed embed.
|
||||
*/
|
||||
function buildLeaderboardEmbed(lb, pageIdx, prefix) {
|
||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||
const startRank = pageIdx * lb.perPage;
|
||||
|
||||
const lines = lb.entries.map((entry, i) => {
|
||||
const rank = startRank + i + 1;
|
||||
const medal = rank <= 3 ? MEDALS[rank - 1] : ` `;
|
||||
const name = entry.username || entry.userId;
|
||||
const count = Utils.formatNumber(entry.scrobbleCount);
|
||||
return `${medal} ${rank}. **${name}** — ${count} scrobbles`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle("🎵 Scrobble Leaderboard")
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: `💡 View & sync your count: ${prefix}lastfm profile` });
|
||||
}
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} data - Parsed command data.
|
||||
* @param {object} lastfm - The Last.fm manager instance.
|
||||
* @param {string} prefix - The guild command prefix.
|
||||
* @param {string} userId - The invoking user's ID.
|
||||
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||
* @param {string} action - The resolved action name.
|
||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||
*/
|
||||
export async function runListeningActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||
switch (action) {
|
||||
case "loved": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let tracks;
|
||||
try {
|
||||
tracks = await lastfm.getLovedTracks(userId, 15);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!tracks.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noLoved", { username: user.username }))]
|
||||
});
|
||||
}
|
||||
|
||||
return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.lovedTitle", { username: user.username }), tracks, false, prefix)] });
|
||||
}
|
||||
|
||||
case "top": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const period = extractPeriod(data, msg);
|
||||
|
||||
let tracks;
|
||||
try {
|
||||
tracks = await lastfm.getTopTracks(userId, period, 15);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!tracks.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTop", { username: user.username }))]
|
||||
});
|
||||
}
|
||||
|
||||
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
||||
return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.topTitle", { username: user.username }) + periodLabel, tracks, true, prefix)] });
|
||||
}
|
||||
|
||||
case "leaderboard":
|
||||
case "lb": {
|
||||
let lb;
|
||||
try {
|
||||
lb = await lastfm.getLeaderboard(0, 10);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!lb.entries.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||
this.t(msg, "responses.lastfm.leaderboardEmpty", { prefix })
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
if (lb.totalPages <= 1) {
|
||||
const embed = buildLeaderboardEmbed(lb, 0, prefix);
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
let currentPage = 0;
|
||||
|
||||
const buildPage = (pageIdx, expired = false) => {
|
||||
const footerText = expired
|
||||
? this.t(msg, "responses.lastfm.leaderboardControlsExpired")
|
||||
: this.t(msg, "responses.lastfm.leaderboardPageFooter", { current: pageIdx + 1, total: lb.totalPages });
|
||||
const embed = buildLeaderboardEmbed(lb, pageIdx, prefix);
|
||||
embed.setFooter({ text: footerText });
|
||||
return { embeds: [embed] };
|
||||
};
|
||||
|
||||
const replyMsg = await msg.reply(buildPage(0));
|
||||
if (!replyMsg?.message) return;
|
||||
|
||||
const navEmojis = ["◀️", "▶️", "❌"];
|
||||
for (const emoji of navEmojis) {
|
||||
await replyMsg.message.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await replyMsg.message.removeAllReactions();
|
||||
} catch {
|
||||
for (const emoji of navEmojis) {
|
||||
try { await replyMsg.message.removeReaction(emoji); } catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let emojiTimeout;
|
||||
const resetTimer = () => {
|
||||
clearTimeout(emojiTimeout);
|
||||
emojiTimeout = setTimeout(async () => {
|
||||
unobserve?.();
|
||||
await clearReactions();
|
||||
await replyMsg.edit(buildPage(currentPage, true)).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||
if (e.emoji_id === "❌") {
|
||||
clearTimeout(emojiTimeout);
|
||||
unobserve?.();
|
||||
await replyMsg.message.delete().catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
resetTimer();
|
||||
|
||||
if (e.emoji_id === "◀️") {
|
||||
currentPage = currentPage > 0 ? currentPage - 1 : lb.totalPages - 1;
|
||||
} else if (e.emoji_id === "▶️") {
|
||||
currentPage = currentPage < lb.totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
try {
|
||||
lb = await lastfm.getLeaderboard(currentPage, 10);
|
||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
|
||||
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
||||
});
|
||||
|
||||
resetTimer();
|
||||
break;
|
||||
}
|
||||
|
||||
case "recent": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let tracks;
|
||||
try {
|
||||
tracks = await lastfm.getRecentTracks(userId, 15);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!tracks.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noRecent", { username: user.username }))]
|
||||
});
|
||||
}
|
||||
|
||||
return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.recentTitle", { username: user.username }), tracks, false, prefix)] });
|
||||
}
|
||||
|
||||
case "artists": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const period = extractPeriod(data, msg);
|
||||
|
||||
let artists;
|
||||
try {
|
||||
artists = await lastfm.getTopArtists(userId, period, 15);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!artists.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noArtists", { username: user.username }))]
|
||||
});
|
||||
}
|
||||
|
||||
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
||||
const lines = artists.map((a, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
let name = a.name;
|
||||
if (name.length > 40) name = name.slice(0, 37) + "...";
|
||||
const link = a.url ? `[${name}](${a.url})` : name;
|
||||
return `\`${num}.\` ${link} — **${a.playcount}** plays`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.artistsTitle", { username: user.username }) + periodLabel)
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.artistsFooter", { prefix }) })]
|
||||
});
|
||||
}
|
||||
|
||||
case "love": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const pLove = await this.getPlayer(msg, false, false, false);
|
||||
if (!pLove) return;
|
||||
const track = pLove.queue?.getCurrent();
|
||||
if (!track) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingLove"))]
|
||||
});
|
||||
}
|
||||
|
||||
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? "Unknown";
|
||||
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown";
|
||||
|
||||
try {
|
||||
await lastfm.loveTrack(userId, artist, name);
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.lovedTrack", { name, artist }))]
|
||||
});
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.loveFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
case "unlove": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const pUnlove = await this.getPlayer(msg, false, false, false);
|
||||
if (!pUnlove) return;
|
||||
const track = pUnlove.queue?.getCurrent();
|
||||
if (!track) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingUnlove"))]
|
||||
});
|
||||
}
|
||||
|
||||
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? "Unknown";
|
||||
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown";
|
||||
|
||||
try {
|
||||
await lastfm.unloveTrack(userId, artist, name);
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.unlovedTrack", { name, artist }))]
|
||||
});
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.unloveFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
/**
|
||||
* @module commands/lastfm/playback
|
||||
* @description The `play` action plus the shared Last.fm playback pipeline (playLastFmCategory, kept exported for commands/play.mjs, plus its private helpers). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||
*/
|
||||
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
import { PROVIDER_CHOICES } from "../../src/music/providers.mjs";
|
||||
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||
import { notConfigured, notLinked } from "./shared.mjs";
|
||||
|
||||
/**
|
||||
* Action names dispatched to this module.
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
export const PLAYBACK_ACTIONS = new Set([
|
||||
"play"
|
||||
]);
|
||||
|
||||
|
||||
const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums", "artists"];
|
||||
|
||||
/**
|
||||
* Build a Last.fm track metadata object from a track.
|
||||
* @private
|
||||
* @param {object} track - The track object with artist, name, and url.
|
||||
* @returns {{ source: string, artist: string, name: string, url: string }} Track metadata.
|
||||
*/
|
||||
function buildLastFmTrackMeta(track) {
|
||||
return {
|
||||
source: "lastfm",
|
||||
artist: track.artist,
|
||||
name: track.name,
|
||||
url: track.url ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a Last.fm track to playable audio via a search provider.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} player - The player instance.
|
||||
* @param {object} track - The Last.fm track with query and metadata.
|
||||
* @param {string} [resolveProvider="yt"] - The provider to resolve with.
|
||||
* @returns {Promise<object[]|null>} Array of resolved track data, or null on failure.
|
||||
*/
|
||||
async function resolveLastFmTrack(player, track, resolveProvider = "yt") {
|
||||
const data = await player.generalQuery({
|
||||
query: track.query,
|
||||
provider: resolveProvider,
|
||||
trackMeta: buildLastFmTrackMeta(track),
|
||||
});
|
||||
|
||||
if (!data || data.type === "error") return null;
|
||||
if (data.type === "video") return [data.data];
|
||||
if (data.type === "list") return data.data ?? [];
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch and play tracks from a Last.fm category (loved, top, recent, albums, artists, playlist).
|
||||
* @async
|
||||
* @param {object} ctx - The bot (Remix) instance context.
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {string} category - The Last.fm category to play.
|
||||
* @param {object} [options={}] - Additional options.
|
||||
* @param {string} [options.resolveProvider="yt"] - Provider to resolve tracks with.
|
||||
* @param {string} [options.playlistId] - Playlist number for playlist category.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function playLastFmCategory(ctx, msg, userId, category, options = {}) {
|
||||
const lastfm = ctx.lastfm;
|
||||
const prefix = ctx.handler.getPrefix(msg.message?.guildId);
|
||||
const resolveProvider = options.resolveProvider || "yt";
|
||||
|
||||
if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(ctx, msg));
|
||||
|
||||
const validCategories = [...SIMPLE_CATEGORIES, "playlist"];
|
||||
if (!validCategories.includes(category)) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
`❌ Unknown category \`${category}\`. Use \`loved\`, \`top\`, \`recent\`, \`albums\`, \`artists\`, or \`playlist\`.`
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
if (category === "playlist" && !options.playlistId) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
`❌ Specify a playlist number. Use \`${prefix}lastfm playlists\` to see your playlists, then \`${prefix}lastfm play playlist <number>\`.`
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(ctx, msg, prefix));
|
||||
|
||||
const p = await ctx.getPlayer(msg, true, true, true);
|
||||
if (!p) return;
|
||||
|
||||
const categoryEmoji = { loved: "❤️", top: "📊", recent: "🕐", playlist: "📋", albums: "💿", artists: "🎤" }[category];
|
||||
const categoryLabel = { loved: "Loved", top: "Top", recent: "Recent", playlist: "Playlist", albums: "Top Albums", artists: "Top Artists" }[category];
|
||||
|
||||
const resolveLabel = resolveProvider !== "yt" ? ` via ${resolveProvider.toUpperCase()}` : "";
|
||||
|
||||
let statusMsg;
|
||||
try {
|
||||
statusMsg = await msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||
`${categoryEmoji} Fetching your ${categoryLabel} tracks from Last.fm${resolveLabel}...`
|
||||
)]
|
||||
});
|
||||
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await lastfm.getTracksForPlay(userId, category, options);
|
||||
} catch (err) {
|
||||
const errMsg = err.message === "NOT_LINKED"
|
||||
? notLinked(ctx, msg, prefix)
|
||||
: { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(ctx.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||
if (statusMsg) statusMsg.edit(errMsg).catch(() => msg.reply(errMsg));
|
||||
else msg.reply(errMsg);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!result.tracks.length) {
|
||||
const noTracks = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||
`${categoryEmoji} No ${categoryLabel.toLowerCase()} tracks found for **${result.username}**.`
|
||||
)] };
|
||||
if (statusMsg) statusMsg.edit(noTracks).catch(() => msg.reply(noTracks));
|
||||
else msg.reply(noTracks);
|
||||
return;
|
||||
}
|
||||
|
||||
let added = 0;
|
||||
let failed = 0;
|
||||
|
||||
if (statusMsg) {
|
||||
statusMsg.edit({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||
`${categoryEmoji} Loading **${result.tracks.length}** ${categoryLabel.toLowerCase()} tracks from **${result.username}**${resolveLabel}...`
|
||||
)]
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
for (const track of result.tracks) {
|
||||
try {
|
||||
const resolvedTracks = await resolveLastFmTrack(p, track, resolveProvider);
|
||||
if (!resolvedTracks?.length) {
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
|
||||
p.addManyToQueue(resolvedTracks, false);
|
||||
added += resolvedTracks.length;
|
||||
|
||||
if (!p.queue.getCurrent()) {
|
||||
p.playNext();
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[LastfmCmd] Track resolve failed:", e?.message);
|
||||
failed++;
|
||||
}
|
||||
}
|
||||
|
||||
const summary = [];
|
||||
if (added > 0) summary.push(`✅ Added **${added}** track${added !== 1 ? "s" : ""} to the queue`);
|
||||
if (failed > 0) summary.push(`⚠️ ${failed} track${failed !== 1 ? "s" : ""} couldn't be found`);
|
||||
|
||||
const doneEmbed = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||
`${categoryEmoji} **${categoryLabel} Tracks — ${result.username}**\n${summary.join(" · ")}`
|
||||
)] };
|
||||
|
||||
if (statusMsg) statusMsg.edit(doneEmbed).catch(() => msg.reply(doneEmbed));
|
||||
else msg.reply(doneEmbed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse play subcommand arguments for category and provider.
|
||||
* @private
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} data - Parsed command data.
|
||||
* @returns {{ category: string, resolveProvider?: string, playlistId?: string, showAllCategories?: boolean, invalidCategory?: string }} Parsed args.
|
||||
*/
|
||||
function parsePlayArgs(msg, data) {
|
||||
let raw = data.get("token")?.value;
|
||||
if (!raw) {
|
||||
const content = msg.message?.content ?? "";
|
||||
const args = content.split(/\s+/);
|
||||
const playIdx = args.indexOf("play");
|
||||
if (playIdx >= 0 && args[playIdx + 1]) {
|
||||
raw = args.slice(playIdx + 1).join(" ");
|
||||
}
|
||||
}
|
||||
|
||||
if (!raw) return { category: "" };
|
||||
|
||||
const lower = raw.toLowerCase().trim();
|
||||
|
||||
const subMatch = lower.match(/^([a-z]+):\s*(.*)$/);
|
||||
if (subMatch) {
|
||||
const maybeProvider = subMatch[1];
|
||||
const rest = subMatch[2].trim();
|
||||
if (PROVIDER_CHOICES.includes(maybeProvider)) {
|
||||
const isLastFmProvider = maybeProvider === "lf" || maybeProvider === "lastfm";
|
||||
|
||||
if (!rest) {
|
||||
if (isLastFmProvider) {
|
||||
return { category: "", resolveProvider: maybeProvider, showAllCategories: true };
|
||||
}
|
||||
return { category: "top", resolveProvider: maybeProvider };
|
||||
}
|
||||
|
||||
if (isLastFmProvider) {
|
||||
const playlistMatch = rest.match(/^playlist\s+(\d+)$/);
|
||||
if (playlistMatch) {
|
||||
return { category: "playlist", playlistId: playlistMatch[1], resolveProvider: maybeProvider };
|
||||
}
|
||||
if (SIMPLE_CATEGORIES.includes(rest)) {
|
||||
return { category: rest, resolveProvider: maybeProvider };
|
||||
}
|
||||
} else {
|
||||
if (rest === "top") {
|
||||
return { category: "top", resolveProvider: maybeProvider };
|
||||
}
|
||||
return { category: "", resolveProvider: maybeProvider, invalidCategory: rest };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (PROVIDER_CHOICES.includes(lower)) {
|
||||
const isLastFmProvider = lower === "lf" || lower === "lastfm";
|
||||
if (isLastFmProvider) {
|
||||
return { category: "", resolveProvider: lower, showAllCategories: true };
|
||||
}
|
||||
return { category: "top", resolveProvider: lower };
|
||||
}
|
||||
|
||||
const playlistMatch = lower.match(/^playlist\s+(\d+)$/);
|
||||
if (playlistMatch) {
|
||||
return { category: "playlist", playlistId: playlistMatch[1] };
|
||||
}
|
||||
|
||||
if (SIMPLE_CATEGORIES.includes(lower)) {
|
||||
return { category: lower };
|
||||
}
|
||||
|
||||
return { category: "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} data - Parsed command data.
|
||||
* @param {object} lastfm - The Last.fm manager instance.
|
||||
* @param {string} prefix - The guild command prefix.
|
||||
* @param {string} userId - The invoking user's ID.
|
||||
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||
* @param {string} action - The resolved action name.
|
||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||
*/
|
||||
export async function runPlaybackActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||
switch (action) {
|
||||
case "play": {
|
||||
const parsed = parsePlayArgs(msg, data);
|
||||
|
||||
if (parsed.invalidCategory) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
`❌ \`${parsed.resolveProvider}:${parsed.invalidCategory}\` is not valid. Non-Last.fm providers only support \`top\`.\nUse \`${prefix}lastfm play ${parsed.resolveProvider}\` or \`${prefix}lastfm play ${parsed.resolveProvider}:top\` instead.\nFor other categories, use Last.fm as the resolve provider: \`${prefix}lastfm play lf:${parsed.invalidCategory}\``
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
if (!parsed.category) {
|
||||
const lfProviderNote = parsed.showAllCategories && parsed.resolveProvider
|
||||
? `\n\n💡 \`${prefix}lastfm play ${parsed.resolveProvider}:<category>\` — Specify a category after the provider:`
|
||||
: "";
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([
|
||||
`❌ Usage: \`${prefix}lastfm play <category>\``,
|
||||
``,
|
||||
`**Categories:**`,
|
||||
`\`loved\` — Play your loved tracks`,
|
||||
`\`top\` — Play your top tracks`,
|
||||
`\`recent\` — Play your recent tracks`,
|
||||
`\`albums\` — Play your top albums`,
|
||||
`\`artists\` — Play your top artists' tracks`,
|
||||
`\`playlist <number>\` — Play a playlist (use \`${prefix}lastfm playlists\` to list)`,
|
||||
``,
|
||||
`**With a search provider (defaults to \`top\`):**`,
|
||||
`\`${prefix}lastfm play td\` or \`${prefix}lastfm play td:top\` — Play top tracks, search on Tidal`,
|
||||
`\`${prefix}lastfm play sp\` or \`${prefix}lastfm play sp:top\` — Play top tracks, search on Spotify`,
|
||||
`\`${prefix}lastfm play dz\` or \`${prefix}lastfm play dz:top\` — Play top tracks, search on Deezer`,
|
||||
`\`${prefix}lastfm play yt\` or \`${prefix}lastfm play yt:top\` — Play top tracks, search on YouTube`,
|
||||
``,
|
||||
`**Last.fm as resolve provider (all categories):**`,
|
||||
`\`${prefix}lastfm play lf:loved\` — Play loved tracks, search on Last.fm`,
|
||||
`\`${prefix}lastfm play lf:top\` — Play top tracks, search on Last.fm`,
|
||||
`\`${prefix}lastfm play lf:recent\` — Play recent tracks, search on Last.fm`,
|
||||
`\`${prefix}lastfm play lf:albums\` — Play top albums, search on Last.fm`,
|
||||
`\`${prefix}lastfm play lf:artists\` — Play top artists, search on Last.fm`,
|
||||
``,
|
||||
`**Examples:**`,
|
||||
`\`${prefix}lastfm play loved\``,
|
||||
`\`${prefix}lastfm play td\``,
|
||||
`\`${prefix}lastfm play sp:top\``,
|
||||
`\`${prefix}lastfm play lf:loved\``,
|
||||
`\`${prefix}lastfm play playlist 1\``,
|
||||
lfProviderNote,
|
||||
].join("\n"))]
|
||||
});
|
||||
}
|
||||
|
||||
return playLastFmCategory(this, msg, userId, parsed.category, {
|
||||
playlistId: parsed.playlistId,
|
||||
resolveProvider: parsed.resolveProvider,
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* @module commands/lastfm/shared
|
||||
* @description Helpers shared by several lastfm action modules. Bodies
|
||||
* are verbatim from the original single-file command; the `export `
|
||||
* prefixes are the only addition.
|
||||
*/
|
||||
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||
|
||||
export const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"];
|
||||
|
||||
/**
|
||||
* Return an embed indicating Last.fm is not configured.
|
||||
* @private
|
||||
* @param {object} ctx - The bot (Remix) instance context.
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @returns {{ embeds: EmbedBuilder[] }} Error embed payload.
|
||||
*/
|
||||
export function notConfigured(ctx, msg) {
|
||||
return {
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(ERROR_COLOR)
|
||||
.setDescription(ctx.t(msg, "responses.lastfm.notConfigured"))]
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an embed indicating the user has not linked their Last.fm account.
|
||||
* @private
|
||||
* @param {object} ctx - The bot (Remix) instance context.
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {string} prefix - The guild's command prefix.
|
||||
* @returns {{ embeds: EmbedBuilder[] }} Error embed payload.
|
||||
*/
|
||||
export function notLinked(ctx, msg, prefix) {
|
||||
return {
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription(ctx.t(msg, "responses.lastfm.notLinked", { prefix }))]
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Last.fm-relevant info from the player's current track.
|
||||
* @private
|
||||
* @param {object} player - The player instance.
|
||||
* @returns {{ artist: string|null, name: string|null, album: string|null, track: object|null }} Extracted track info.
|
||||
*/
|
||||
export function extractCurrentTrack(player) {
|
||||
const track = player?.queue?.getCurrent();
|
||||
if (!track) return null;
|
||||
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? null;
|
||||
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? null;
|
||||
const album = track.album ?? track.lastfm?.album ?? null;
|
||||
return { artist, name, album, track };
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a valid time period from command data or message content.
|
||||
* @private
|
||||
* @param {object} data - Parsed command data.
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @returns {string} The period string, defaults to "overall".
|
||||
*/
|
||||
export function extractPeriod(data, msg) {
|
||||
let raw = data.get("token")?.value;
|
||||
if (!raw) {
|
||||
const content = msg.message?.content ?? "";
|
||||
const args = content.split(/\s+/);
|
||||
const last = args[args.length - 1];
|
||||
if (last && VALID_PERIODS.includes(last.toLowerCase())) raw = last;
|
||||
}
|
||||
if (raw && VALID_PERIODS.includes(raw.toLowerCase().trim())) {
|
||||
return raw.toLowerCase().trim();
|
||||
}
|
||||
return "overall";
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
/**
|
||||
* @module commands/lastfm/tags
|
||||
* @description Tag/genre actions for the lastfm command (tag, artisttags, albumtags, tracktags, tagalbums). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||
*/
|
||||
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { Utils } from "../../src/utils/Utils.mjs";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||
import { extractCurrentTrack } from "./shared.mjs";
|
||||
|
||||
/**
|
||||
* Action names dispatched to this module.
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
export const TAG_ACTIONS = new Set([
|
||||
"tag",,
|
||||
"artisttags",,
|
||||
"at",,
|
||||
"albumtags",,
|
||||
"alt",,
|
||||
"tracktags",,
|
||||
"tt",,
|
||||
"tagalbums",,
|
||||
"ta"
|
||||
]);
|
||||
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} data - Parsed command data.
|
||||
* @param {object} lastfm - The Last.fm manager instance.
|
||||
* @param {string} prefix - The guild command prefix.
|
||||
* @param {string} userId - The invoking user's ID.
|
||||
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||
* @param {string} action - The resolved action name.
|
||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||
*/
|
||||
export async function runTagActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||
switch (action) {
|
||||
case "tag": {
|
||||
const tagName = data.get("token")?.value;
|
||||
if (!tagName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
this.t(msg, "responses.lastfm.tagProvideName", { prefix })
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
let tagInfo;
|
||||
let topTracks;
|
||||
let topArtists;
|
||||
|
||||
try {
|
||||
[tagInfo, topTracks, topArtists] = await Promise.all([
|
||||
lastfm.getTagInfo(tagName),
|
||||
lastfm.getTagTopTracks(tagName, 5),
|
||||
lastfm.getTagTopArtists(tagName, 5),
|
||||
]);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!tagInfo) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tagNotFound", { tag: tagName }))]
|
||||
});
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`🏷️ ${tagInfo.name}`)
|
||||
.setURL(tagInfo.url || undefined);
|
||||
|
||||
const fields = [];
|
||||
fields.push({ name: "Reach", value: Utils.formatNumber(tagInfo.reach), inline: true });
|
||||
fields.push({ name: "Total Taggings", value: Utils.formatNumber(tagInfo.count), inline: true });
|
||||
|
||||
if (topArtists.length) {
|
||||
const artistStr = topArtists.map((a, i) => {
|
||||
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||
return `${i + 1}. ${link} (**${Utils.formatNumber(a.playcount)}** plays)`;
|
||||
}).join("\n");
|
||||
fields.push({ name: "Top Artists", value: artistStr.slice(0, 1024), inline: false });
|
||||
}
|
||||
|
||||
if (topTracks.length) {
|
||||
const trackStr = topTracks.map((t, i) => {
|
||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||
return `${i + 1}. ${link} by **${t.artist}**`;
|
||||
}).join("\n");
|
||||
fields.push({ name: "Top Tracks", value: trackStr.slice(0, 1024), inline: false });
|
||||
}
|
||||
|
||||
embed.addFields(...fields);
|
||||
|
||||
if (tagInfo.summary) {
|
||||
const cleanSummary = tagInfo.summary.replace(/<[^>]*>/g, "").trim();
|
||||
if (cleanSummary.length > 0) {
|
||||
const truncated = cleanSummary.length > 300 ? cleanSummary.slice(0, 297) + "..." : cleanSummary;
|
||||
embed.setDescription(truncated);
|
||||
}
|
||||
}
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
case "artisttags":
|
||||
case "at": {
|
||||
let artistName = null;
|
||||
|
||||
const pAt = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pAt);
|
||||
if (current?.artist) {
|
||||
artistName = current.artist;
|
||||
}
|
||||
|
||||
const tokenTextAt = data.get("token")?.value;
|
||||
if (tokenTextAt) {
|
||||
artistName = tokenTextAt.trim();
|
||||
}
|
||||
|
||||
if (!artistName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))]
|
||||
});
|
||||
}
|
||||
|
||||
let tags;
|
||||
try {
|
||||
tags = await lastfm.getArtistTopTags(artistName, 15);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!tags.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noArtistTags", { artist: artistName }))]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = tags.map((t, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||
return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: artistName }))
|
||||
.setDescription(desc)]
|
||||
});
|
||||
}
|
||||
|
||||
case "albumtags":
|
||||
case "alt": {
|
||||
let artistName = null;
|
||||
let albumName = null;
|
||||
|
||||
const pAlt = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pAlt);
|
||||
if (current?.album && current?.artist) {
|
||||
artistName = current.artist;
|
||||
albumName = current.album;
|
||||
}
|
||||
|
||||
const tokenTextAlt = data.get("token")?.value;
|
||||
if (tokenTextAlt) {
|
||||
const dashMatch = tokenTextAlt.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||
if (dashMatch) {
|
||||
artistName = dashMatch[1].trim();
|
||||
albumName = dashMatch[2].trim();
|
||||
} else {
|
||||
albumName = tokenTextAlt.trim();
|
||||
}
|
||||
}
|
||||
|
||||
if (!albumName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))]
|
||||
});
|
||||
}
|
||||
|
||||
let tags;
|
||||
try {
|
||||
tags = await lastfm.getAlbumTopTags(artistName || "", albumName, 15);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!tags.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🏷️ No tags found for album **${albumName}**.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = tags.map((t, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||
return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: albumName }))
|
||||
.setDescription(desc)]
|
||||
});
|
||||
}
|
||||
|
||||
case "tracktags":
|
||||
case "tt": {
|
||||
let artistName = null;
|
||||
let trackName = null;
|
||||
|
||||
const pTt = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pTt);
|
||||
if (current?.artist && current?.name) {
|
||||
artistName = current.artist;
|
||||
trackName = current.name;
|
||||
}
|
||||
|
||||
const tokenTextTt = data.get("token")?.value;
|
||||
if (tokenTextTt) {
|
||||
const dashMatch = tokenTextTt.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||
if (dashMatch) {
|
||||
artistName = dashMatch[1].trim();
|
||||
trackName = dashMatch[2].trim();
|
||||
} else {
|
||||
try {
|
||||
const searchResult = await lastfm.searchTrack(tokenTextTt.trim());
|
||||
if (searchResult) {
|
||||
artistName = searchResult.artist;
|
||||
trackName = searchResult.name;
|
||||
}
|
||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
}
|
||||
}
|
||||
|
||||
if (!artistName || !trackName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))]
|
||||
});
|
||||
}
|
||||
|
||||
let tags;
|
||||
try {
|
||||
tags = await lastfm.getTrackTopTags(artistName, trackName, 15);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!tags.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🏷️ No tags found for **${trackName}** by **${artistName}**.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = tags.map((t, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||
return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: trackName }))
|
||||
.setDescription(desc)]
|
||||
});
|
||||
}
|
||||
|
||||
case "tagalbums":
|
||||
case "ta": {
|
||||
const tagName = data.get("token")?.value;
|
||||
if (!tagName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a tag name via the token option. Example: \`${prefix}lastfm tagalbums rock\``)]
|
||||
});
|
||||
}
|
||||
|
||||
let albums;
|
||||
try {
|
||||
albums = await lastfm.getTagTopAlbums(tagName.trim(), 15);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!albums.length) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`💿 No top albums found for tag **${tagName}**.`)]
|
||||
});
|
||||
}
|
||||
|
||||
const lines = albums.map((a, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||
return `\`${num}.\` ${link} by **${a.artist}**${a.playcount > 0 ? ` (${Utils.formatNumber(a.playcount)} plays)` : ""}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`💿 Top Albums — ${tagName}`)
|
||||
.setDescription(desc);
|
||||
|
||||
if (albums[0]?.image) {
|
||||
embed.setThumbnail(albums[0].image);
|
||||
}
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
/**
|
||||
* @module commands/lastfm/whoknows
|
||||
* @description Server-social actions for the lastfm command (whoknows, whoknowstrack, whoknowsalbum, affinity, crowns, compare, refreshmembers) with the guild-member helper. Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||
*/
|
||||
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { Utils } from "../../src/utils/Utils.mjs";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||
import { notLinked, extractCurrentTrack } from "./shared.mjs";
|
||||
|
||||
/**
|
||||
* Action names dispatched to this module.
|
||||
* @type {Set<string>}
|
||||
*/
|
||||
export const WHOKNOWS_ACTIONS = new Set([
|
||||
"whoknows",,
|
||||
"wk",,
|
||||
"compare",,
|
||||
"fmc",,
|
||||
"refreshmembers",,
|
||||
"rm",,
|
||||
"affinity",,
|
||||
"af",,
|
||||
"crowns",,
|
||||
"cr",,
|
||||
"whoknowstrack",,
|
||||
"wkt",,
|
||||
"whoknowsalbum",,
|
||||
"wka"
|
||||
]);
|
||||
|
||||
|
||||
/**
|
||||
* Get all non-bot user IDs in a guild.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} guild - The guild object.
|
||||
* @returns {Promise<string[]>} Array of user ID strings.
|
||||
*/
|
||||
async function getGuildLinkedUsers(guild) {
|
||||
const memberIds = [];
|
||||
try {
|
||||
const members = guild?.members;
|
||||
if (members) {
|
||||
const iter = typeof members.values === "function" ? members.values() : Object.values(members);
|
||||
for (const m of iter) {
|
||||
const userId = m.user?.id ?? m.id;
|
||||
if (userId && !m.user?.bot) memberIds.push(String(userId));
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
return memberIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} data - Parsed command data.
|
||||
* @param {object} lastfm - The Last.fm manager instance.
|
||||
* @param {string} prefix - The guild command prefix.
|
||||
* @param {string} userId - The invoking user's ID.
|
||||
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||
* @param {string} action - The resolved action name.
|
||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||
*/
|
||||
export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||
switch (action) {
|
||||
case "whoknows":
|
||||
case "wk": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let artistName = null;
|
||||
const tokenTextWk = data.get("token")?.value;
|
||||
if (tokenTextWk) {
|
||||
artistName = tokenTextWk.trim();
|
||||
} else {
|
||||
const pWk = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pWk);
|
||||
if (current?.artist) {
|
||||
artistName = current.artist;
|
||||
}
|
||||
}
|
||||
|
||||
if (!artistName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingNoArtist"))]
|
||||
});
|
||||
}
|
||||
|
||||
let statusMsg;
|
||||
try {
|
||||
statusMsg = await msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||
this.t(msg, "responses.lastfm.whoknowsChecking", { artist: artistName })
|
||||
)]
|
||||
});
|
||||
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||
|
||||
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||
const memberIds = await getGuildLinkedUsers(guild);
|
||||
|
||||
let listeners;
|
||||
try {
|
||||
listeners = await lastfm.getWhoKnows(artistName, memberIds);
|
||||
} catch (err) {
|
||||
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||
else msg.reply(errEmbed);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!listeners.length) {
|
||||
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||
this.t(msg, "responses.lastfm.whoknowsNobody", { artist: artistName })
|
||||
)] };
|
||||
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||
else msg.reply(noData);
|
||||
return;
|
||||
}
|
||||
|
||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
||||
|
||||
const lines = listeners.map((l, i) => {
|
||||
const medal = i < 3 ? MEDALS[i] : ` `;
|
||||
return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.whoknowsTitle", { artist: artistName }))
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) });
|
||||
|
||||
const replyPayload = { embeds: [embed] };
|
||||
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||
else msg.reply(replyPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
case "compare":
|
||||
case "fmc": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
if (!targetUserId) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
this.t(msg, "responses.lastfm.compareSpecifyUser", { prefix })
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
const targetUser = await lastfm.getUser(targetUserId);
|
||||
if (!targetUser) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||
this.t(msg, "responses.lastfm.compareUserNotLinked")
|
||||
)]
|
||||
});
|
||||
}
|
||||
|
||||
let comparison;
|
||||
try {
|
||||
comparison = await lastfm.compareUsers(userId, targetUserId);
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||
});
|
||||
}
|
||||
|
||||
if (!comparison) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.compareFailed"))]
|
||||
});
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.compareTitle"))
|
||||
.setDescription([
|
||||
`**${comparison.user1.username}** vs **${comparison.user2.username}**`,
|
||||
``,
|
||||
`📊 **${comparison.matchPercentage}%** match`,
|
||||
``,
|
||||
`👤 ${comparison.user1.username}: ${comparison.user1.totalArtists} top artists`,
|
||||
`👤 ${comparison.user2.username}: ${comparison.user2.totalArtists} top artists`,
|
||||
].join("\n"));
|
||||
|
||||
if (comparison.commonArtists?.length) {
|
||||
const commonStr = comparison.commonArtists.slice(0, 15).map((a, i) => {
|
||||
const num = String(i + 1).padStart(2, " ");
|
||||
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||
return `\`${num}.\` ${link} (**${a.playcount}** plays)`;
|
||||
}).join("\n");
|
||||
embed.addFields({ name: `Common Artists (${comparison.commonArtists.length})`, value: commonStr.slice(0, 1024), inline: false });
|
||||
}
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
case "refreshmembers":
|
||||
case "rm": {
|
||||
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||
if (!guild) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.refreshFailed"))]
|
||||
});
|
||||
}
|
||||
let count = 0;
|
||||
try {
|
||||
if (guild.members && typeof guild.members.fetch === "function") {
|
||||
const fetched = await guild.members.fetch();
|
||||
count = fetched.size;
|
||||
} else {
|
||||
const memberIds = await getGuildLinkedUsers(guild);
|
||||
count = memberIds.length;
|
||||
}
|
||||
} catch {
|
||||
const memberIds = await getGuildLinkedUsers(guild);
|
||||
count = memberIds.length;
|
||||
}
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.refreshSuccess", { count: Utils.formatNumber(count) }))]
|
||||
});
|
||||
}
|
||||
|
||||
case "affinity":
|
||||
case "af": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||
const memberIds = await getGuildLinkedUsers(guild);
|
||||
|
||||
if (memberIds.length < 2) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityNeedUsers"))]
|
||||
});
|
||||
}
|
||||
|
||||
let statusMsg;
|
||||
try {
|
||||
statusMsg = await msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityChecking"))]
|
||||
});
|
||||
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||
|
||||
let affinityResults;
|
||||
try {
|
||||
affinityResults = await lastfm.getAffinity(memberIds, 10);
|
||||
} catch (err) {
|
||||
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||
else msg.reply(errEmbed);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!affinityResults.length) {
|
||||
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityNoCommon"))] };
|
||||
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||
else msg.reply(noData);
|
||||
return;
|
||||
}
|
||||
|
||||
const lines = affinityResults.map(r => {
|
||||
const topCommon = r.commonArtists.slice(0, 3).map(a => a.name).join(", ");
|
||||
return `**${r.users[0]}** & **${r.users[1]}** — ${r.matchCount} common artists (${topCommon}${r.commonArtists.length > 3 ? "..." : ""})`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.affinityTitle"))
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.affinityFooter", { count: memberIds.length }) });
|
||||
|
||||
const replyPayload = { embeds: [embed] };
|
||||
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||
else msg.reply(replyPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
case "crowns":
|
||||
case "cr": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||
const memberIds = await getGuildLinkedUsers(guild);
|
||||
|
||||
let statusMsg;
|
||||
try {
|
||||
statusMsg = await msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.crownsChecking"))]
|
||||
});
|
||||
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||
|
||||
let crowns;
|
||||
try {
|
||||
crowns = await lastfm.getCrowns(userId, memberIds);
|
||||
} catch (err) {
|
||||
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||
else msg.reply(errEmbed);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!crowns.length) {
|
||||
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.crownsNone"))] };
|
||||
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||
else msg.reply(noData);
|
||||
return;
|
||||
}
|
||||
|
||||
const tokenFilter = data.get("token")?.value?.toLowerCase().trim();
|
||||
|
||||
let filteredCrowns = crowns;
|
||||
if (tokenFilter === "stolen") {
|
||||
filteredCrowns = crowns.filter(c => c.nextBest && c.nextBest.playcount > 0);
|
||||
} else if (tokenFilter === "recent") {
|
||||
filteredCrowns = crowns.slice(0, 10);
|
||||
}
|
||||
|
||||
const lines = filteredCrowns.slice(0, 20).map(c => {
|
||||
const link = c.artistUrl ? `[${c.artist}](${c.artistUrl})` : c.artist;
|
||||
const nextStr = c.nextBest ? ` (next: **${c.nextBest.username}** with ${Utils.formatNumber(c.nextBest.playcount)})` : "";
|
||||
return `👑 ${link} — **${Utils.formatNumber(c.userPlaycount)}** plays${nextStr}`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.crownsTitle", { username: user.username }))
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.crownsFooter", { count: filteredCrowns.length, plural: filteredCrowns.length !== 1 ? "s" : "" }) });
|
||||
|
||||
if (filteredCrowns[0]?.image) {
|
||||
embed.setThumbnail(filteredCrowns[0].image);
|
||||
}
|
||||
|
||||
const replyPayload = { embeds: [embed] };
|
||||
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||
else msg.reply(replyPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
case "whoknowstrack":
|
||||
case "wkt": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let artistName = null;
|
||||
let trackName = null;
|
||||
|
||||
const pWkt = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pWkt);
|
||||
if (current?.artist && current?.name) {
|
||||
artistName = current.artist;
|
||||
trackName = current.name;
|
||||
}
|
||||
|
||||
const tokenTextWkt = data.get("token")?.value;
|
||||
if (tokenTextWkt) {
|
||||
const dashMatch = tokenTextWkt.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||
if (dashMatch) {
|
||||
artistName = dashMatch[1].trim();
|
||||
trackName = dashMatch[2].trim();
|
||||
} else {
|
||||
try {
|
||||
const searchResult = await lastfm.searchTrack(tokenTextWkt.trim());
|
||||
if (searchResult) {
|
||||
artistName = searchResult.artist;
|
||||
trackName = searchResult.name;
|
||||
}
|
||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||
}
|
||||
}
|
||||
|
||||
if (!artistName || !trackName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))]
|
||||
});
|
||||
}
|
||||
|
||||
let statusMsg;
|
||||
try {
|
||||
statusMsg = await msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsTrackChecking", { track: trackName, artist: artistName }))]
|
||||
});
|
||||
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||
|
||||
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||
const memberIds = await getGuildLinkedUsers(guild);
|
||||
|
||||
let listeners;
|
||||
try {
|
||||
listeners = await lastfm.getWhoKnowsTrack(artistName, trackName, memberIds);
|
||||
} catch (err) {
|
||||
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||
else msg.reply(errEmbed);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!listeners.length) {
|
||||
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsTrackNobody", { track: trackName, artist: artistName }))] };
|
||||
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||
else msg.reply(noData);
|
||||
return;
|
||||
}
|
||||
|
||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
||||
|
||||
const lines = listeners.map((l, i) => {
|
||||
const medal = i < 3 ? MEDALS[i] : ` `;
|
||||
return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.whoknowsTrackTitle", { track: trackName }))
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsTrackFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays), artist: artistName }) });
|
||||
|
||||
const replyPayload = { embeds: [embed] };
|
||||
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||
else msg.reply(replyPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
case "whoknowsalbum":
|
||||
case "wka": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||
|
||||
let artistName = null;
|
||||
let albumName = null;
|
||||
|
||||
const pWka = await this.getPlayer(msg, false, false, false);
|
||||
const current = extractCurrentTrack(pWka);
|
||||
if (current?.album && current?.artist) {
|
||||
artistName = current.artist;
|
||||
albumName = current.album;
|
||||
}
|
||||
|
||||
const tokenTextWka = data.get("token")?.value;
|
||||
if (tokenTextWka) {
|
||||
const dashMatch = tokenTextWka.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||
if (dashMatch) {
|
||||
artistName = dashMatch[1].trim();
|
||||
albumName = dashMatch[2].trim();
|
||||
} else {
|
||||
albumName = tokenTextWka.trim();
|
||||
}
|
||||
}
|
||||
|
||||
if (!albumName) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))]
|
||||
});
|
||||
}
|
||||
|
||||
let statusMsg;
|
||||
try {
|
||||
statusMsg = await msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsAlbumChecking", { album: albumName, artistClause: artistName ? ` by **${artistName}**` : "" }))]
|
||||
});
|
||||
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||
|
||||
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||
const memberIds = await getGuildLinkedUsers(guild);
|
||||
|
||||
let listeners;
|
||||
try {
|
||||
listeners = await lastfm.getWhoKnowsAlbum(artistName || "", albumName, memberIds);
|
||||
} catch (err) {
|
||||
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||
else msg.reply(errEmbed);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!listeners.length) {
|
||||
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsAlbumNobody", { album: albumName }))] };
|
||||
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||
else msg.reply(noData);
|
||||
return;
|
||||
}
|
||||
|
||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
||||
|
||||
const lines = listeners.map((l, i) => {
|
||||
const medal = i < 3 ? MEDALS[i] : ` `;
|
||||
return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`;
|
||||
});
|
||||
|
||||
const desc = lines.join("\n").slice(0, 4096);
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.lastfm.whoknowsAlbumTitle", { album: albumName }))
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) });
|
||||
|
||||
const replyPayload = { embeds: [embed] };
|
||||
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||
else msg.reply(replyPayload);
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -3,10 +3,10 @@
|
||||
* @description Make the bot leave a voice channel, with 24/7 cleanup and player destruction.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import { getGlobalColor, cleanId } from "../src/ui/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the leave/stop command. */
|
||||
export const command = new CommandBuilder()
|
||||
@@ -25,7 +25,7 @@ export const command = new CommandBuilder()
|
||||
* Resolve the guild ID from a player, its map key, or the channel object.
|
||||
* @param {Player} player - The player instance.
|
||||
* @param {string} mapKey - The key under which the player is stored in playerMap.
|
||||
* @param {import('@fluxerjs/core').Client} client - The Discord/Fluxer client.
|
||||
* @param {import('@fluxerjs/core').Client} client - The Fluxer client.
|
||||
* @returns {string} Cleaned guild ID, or empty string if unresolvable.
|
||||
*/
|
||||
function resolvePlayerGuildId(player, mapKey, client) {
|
||||
|
||||
+2
-2
@@ -3,8 +3,8 @@
|
||||
* @description List the songs in the queue of the current voice channel with pagination.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { QueuePaginator, getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { QueuePaginator, getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@
|
||||
* @description Toggle looping of the current song or the entire queue.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the loop command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+5
-5
@@ -3,12 +3,12 @@
|
||||
* @description Display synced or unsynced lyrics for the currently playing track from NodeLink.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { Utils } from "../src/utils/Utils.mjs";
|
||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the lyrics command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* @description Move a track from one position to another in the queue.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the move command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@
|
||||
* @description Display the currently playing track name and URL.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the np (now playing) command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@
|
||||
* @description Pause the currently playing track.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the pause command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+6
-6
@@ -4,14 +4,14 @@
|
||||
* Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and Last.fm integration.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||
import { playLastFmCategory } from "./lastfm.mjs";
|
||||
import { parseLastFmUrl, isLastFmUrl } from "../src/LastFmManager.mjs";
|
||||
import { ERROR_COLOR } from "../src/constants/UI.mjs";
|
||||
import { parseLastFmUrl, isLastFmUrl } from "../src/services/lastfm/LastFmManager.mjs";
|
||||
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||
|
||||
const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
|
||||
|
||||
|
||||
+21
-270
@@ -1,15 +1,17 @@
|
||||
/**
|
||||
* @module commands/player
|
||||
* @description Create an interactive player control panel with live progress, reaction controls,
|
||||
* and embedded lyrics viewer.
|
||||
* and embedded lyrics viewer. The panel embed construction, display constants and the lyrics
|
||||
* viewer live in commands/player/; run() below owns the session lifecycle (timers, player
|
||||
* event wiring and the control-reaction dispatcher).
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { Utils } from "../src/utils/Utils.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import { CONTROLS, buildPlayerEmbed, openLyricsViewer, clearLyricsReactions } from "./player/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the player command. */
|
||||
export const command = new CommandBuilder()
|
||||
@@ -17,40 +19,6 @@ export const command = new CommandBuilder()
|
||||
.setDescription("Create an interactive player control panel with live progress", "commands.player")
|
||||
.setCategory("music");
|
||||
|
||||
/** @private @type {Object.<string, string>} Emoji indicators for player states. */
|
||||
const STATES = {
|
||||
playing: "🎵",
|
||||
paused: "⏸️",
|
||||
stopped: "🔇",
|
||||
loading: "⏳"
|
||||
};
|
||||
|
||||
/** @private @type {Object.<string, {emoji: string, action: string, desc: string}>} Available control button definitions. */
|
||||
const CONTROLS = {
|
||||
prev: { emoji: "⏮️", action: "previous", desc: "Previous" },
|
||||
play: { emoji: "▶️", action: "resume", desc: "Play" },
|
||||
pause: { emoji: "⏸️", action: "pause", desc: "Pause" },
|
||||
stop: { emoji: "⏹️", action: "stop", desc: "Stop" },
|
||||
next: { emoji: "⏭️", action: "skip", desc: "Skip" },
|
||||
loop: { emoji: "🔁", action: "loop", desc: "Loop" },
|
||||
shuffle: { emoji: "🔀", action: "shuffle", desc: "Shuffle" },
|
||||
volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" },
|
||||
volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" },
|
||||
lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" },
|
||||
filter: { emoji: "🎛️", action: "filter", desc: "Audio Filters" },
|
||||
close: { emoji: "❌", action: "close", desc: "Close" }
|
||||
};
|
||||
|
||||
/** @private @type {Object.<string, string>} Progress bar character set. */
|
||||
const PROGRESS = {
|
||||
filled: "▰",
|
||||
empty: "▱",
|
||||
indicator: "●",
|
||||
start: "▏",
|
||||
end: "▕"
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @async
|
||||
* Run handler for the player command.
|
||||
@@ -73,89 +41,7 @@ export async function run(msg) {
|
||||
const allControls = controlsLayout.flat();
|
||||
const controlEmojis = allControls.map(c => c.emoji);
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Build the player panel embed with current state, progress, volume, and loop info.
|
||||
* @param {object} [state={}] - Optional state override with a message field.
|
||||
* @returns {EmbedBuilder} The constructed embed builder.
|
||||
*/
|
||||
const buildEmbed = (state = {}) => {
|
||||
const current = player.queue.getCurrent();
|
||||
const isPlaying = !player.paused && current;
|
||||
const statusEmoji = isPlaying ? STATES.playing : player.paused ? STATES.paused : STATES.stopped;
|
||||
|
||||
let progressBar = "";
|
||||
let timeDisplay = "`0:00 / 0:00`";
|
||||
|
||||
if (current?.duration && player.startedPlaying) {
|
||||
const elapsed = Date.now() - player.startedPlaying;
|
||||
const totalMs = typeof current.duration === "object"
|
||||
? (current.duration.seconds ?? 0) * 1000
|
||||
: current.duration;
|
||||
|
||||
const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled);
|
||||
progressBar = PROGRESS.start + bar + PROGRESS.end;
|
||||
|
||||
const elapsedStr = Utils.prettifyMS(elapsed);
|
||||
const totalStr = Utils.prettifyMS(totalMs);
|
||||
timeDisplay = `\`${elapsedStr} / ${totalStr}\``;
|
||||
} else {
|
||||
progressBar = PROGRESS.start + PROGRESS.empty.repeat(20) + PROGRESS.end;
|
||||
}
|
||||
|
||||
const volPercent = Math.round((player.preferredVolume ?? 1) * 100);
|
||||
const volBars = Math.ceil(volPercent / 10);
|
||||
const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars);
|
||||
|
||||
const queueSize = player.queue.size();
|
||||
const loopStatus = player.queue.songLoop ? this.t(msg, "responses.player.loopSong") : player.queue.loop ? this.t(msg, "responses.player.loopQueue") : this.t(msg, "responses.player.loopOff");
|
||||
|
||||
let filterStatus = this.t(msg, "responses.player.filterOff");
|
||||
if (player.activeFilter) {
|
||||
if (player.activeFilter.label.includes("+")) {
|
||||
filterStatus = `🔥 **${player.activeFilter.label}**`;
|
||||
} else {
|
||||
filterStatus = `${player.activeFilter.emoji ?? "🎛️"} **${player.activeFilter.label}**`;
|
||||
}
|
||||
}
|
||||
|
||||
const nowPlaying = current
|
||||
? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})`
|
||||
: this.t(msg, "responses.filter.nothingPlayingInline");
|
||||
|
||||
const description = [
|
||||
`${statusEmoji} ${this.t(msg, "responses.player.nowPlayingLabel")}`,
|
||||
`${nowPlaying}`,
|
||||
``,
|
||||
`${progressBar}`,
|
||||
`${timeDisplay}`,
|
||||
``,
|
||||
this.t(msg, "responses.player.volumeLabel", { volume: volPercent }) + " " + volumeBar,
|
||||
`${this.t(msg, "responses.player.queueLabel", { count: queueSize })} | Loop: ${loopStatus} | Filter: ${filterStatus}`,
|
||||
``,
|
||||
state.message ? `💬 *${state.message}*` : `💡 *${this.t(msg, "responses.player.reactHint")}*`,
|
||||
``,
|
||||
this.t(msg, "responses.player.sessionExpires", { minutes: Math.ceil(timeout / 60000) })
|
||||
].join("\n");
|
||||
|
||||
const avatarUrl = typeof msg.author?.avatarURL === "function"
|
||||
? msg.author.avatarURL()
|
||||
: msg.author?.avatarURL ?? null;
|
||||
|
||||
const builder = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(this.t(msg, "responses.player.title"))
|
||||
.setDescription(description)
|
||||
.setFooter({
|
||||
text: this.t(msg, "responses.player.requestedBy", { username: msg.author?.username || "Unknown" }),
|
||||
iconURL: avatarUrl
|
||||
});
|
||||
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
||||
if (current?.thumbnail) builder.setThumbnail(current.thumbnail);
|
||||
return builder;
|
||||
};
|
||||
|
||||
const message = await msg.reply({ embeds: [buildEmbed()] });
|
||||
const message = await msg.reply({ embeds: [buildPlayerEmbed(this, msg, player, timeout)] });
|
||||
if (!message?.message) return;
|
||||
|
||||
for (const row of controlsLayout) {
|
||||
@@ -172,9 +58,8 @@ export async function run(msg) {
|
||||
let emojiRemoveTimeout;
|
||||
let lastState = {};
|
||||
|
||||
let activeLyricsMsg = null;
|
||||
let lyricsUnobserve = null;
|
||||
let lyricsEmojiTimeout = null;
|
||||
/** @private @type {object} Shared lyrics-viewer session state (cleaned up by closeSession). */
|
||||
const lyrics = { activeLyricsMsg: null, unobserve: null, emojiTimeout: null };
|
||||
|
||||
/**
|
||||
* @private
|
||||
@@ -202,31 +87,12 @@ export async function run(msg) {
|
||||
clearTimeout(emojiRemoveTimeout);
|
||||
emojiRemoveTimeout = setTimeout(async () => {
|
||||
await clearReactions();
|
||||
const disabledEmbed = buildEmbed({ message: this.t(msg, "responses.player.controlsDisabled") });
|
||||
const disabledEmbed = buildPlayerEmbed(this, msg, player, timeout, { message: this.t(msg, "responses.player.controlsDisabled") });
|
||||
disabledEmbed.footer = { text: this.t(msg, "responses._common.controlsExpired") };
|
||||
await message.edit({ embeds: [disabledEmbed] }).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Remove navigation reactions from a lyrics message.
|
||||
* @param {object} lyricsMsg - The wrapped lyrics message with a .message property.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
const clearLyricsReactions = async (lyricsMsg) => {
|
||||
if (!lyricsMsg?.message) return;
|
||||
try {
|
||||
await lyricsMsg.message.removeAllReactions();
|
||||
} catch (e) {
|
||||
for (const emoji of ["⬅️", "➡️", "❌"]) {
|
||||
try {
|
||||
await lyricsMsg.message.removeReaction(emoji);
|
||||
} catch(e) { logger.warn("[Player] Error:", e?.message); }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let editFailures = 0;
|
||||
|
||||
/**
|
||||
@@ -236,7 +102,7 @@ export async function run(msg) {
|
||||
* @returns {void}
|
||||
*/
|
||||
const refresh = (extra = {}) => {
|
||||
const embed = buildEmbed(extra);
|
||||
const embed = buildPlayerEmbed(this, msg, player, timeout, extra);
|
||||
message.edit({ embeds: [embed] })
|
||||
.then(() => { editFailures = 0; })
|
||||
.catch(() => {
|
||||
@@ -275,17 +141,17 @@ export async function run(msg) {
|
||||
player.off("filter", onFilter);
|
||||
player.off("autoleave", onAutoLeave);
|
||||
|
||||
if (lyricsUnobserve) {
|
||||
lyricsUnobserve();
|
||||
clearTimeout(lyricsEmojiTimeout);
|
||||
if (lyrics.unobserve) {
|
||||
lyrics.unobserve();
|
||||
clearTimeout(lyrics.emojiTimeout);
|
||||
}
|
||||
if (activeLyricsMsg) {
|
||||
await clearLyricsReactions(activeLyricsMsg);
|
||||
if (lyrics.activeLyricsMsg) {
|
||||
await clearLyricsReactions(lyrics.activeLyricsMsg);
|
||||
}
|
||||
|
||||
await clearReactions();
|
||||
|
||||
const closedEmbed = buildEmbed({
|
||||
const closedEmbed = buildPlayerEmbed(this, msg, player, timeout, {
|
||||
message: this.t(msg, "responses.player.sessionClosed", { reason: reason !== "timeout" ? ` • ${reason}` : "" })
|
||||
});
|
||||
closedEmbed.setColor(getGlobalColor());
|
||||
@@ -431,122 +297,7 @@ export async function run(msg) {
|
||||
break;
|
||||
|
||||
case "lyrics":
|
||||
reply = this.t(msg, "responses.player.fetchingLyrics");
|
||||
refresh({ message: reply });
|
||||
|
||||
try {
|
||||
if (lyricsUnobserve) {
|
||||
lyricsUnobserve();
|
||||
clearTimeout(lyricsEmojiTimeout);
|
||||
if (activeLyricsMsg) await clearLyricsReactions(activeLyricsMsg);
|
||||
}
|
||||
|
||||
const lyricsResult = await player.lyrics();
|
||||
if (!lyricsResult) {
|
||||
reply = this.t(msg, "responses.player.noLyricsFound");
|
||||
shouldUpdate = true;
|
||||
break;
|
||||
}
|
||||
|
||||
const syncBadge = lyricsResult.synced ? " ⏱️ Synced" : "";
|
||||
const lines = lyricsResult.text.split('\n');
|
||||
const totalLines = lines.length;
|
||||
const LINES_PER_PAGE = 25;
|
||||
const totalPages = Math.ceil(totalLines / LINES_PER_PAGE);
|
||||
|
||||
const pages = [];
|
||||
for (let i = 0; i < totalLines; i += LINES_PER_PAGE) {
|
||||
pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n'));
|
||||
}
|
||||
|
||||
let currentPage = 0;
|
||||
|
||||
const buildLyricsContent = (pageIdx, expired = false, closed = false) => {
|
||||
const title = Utils.truncate(
|
||||
player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '',
|
||||
50
|
||||
);
|
||||
const footerText = closed
|
||||
? `👋 Lyrics closed • NodeLink • ${totalLines} lines`
|
||||
: expired
|
||||
? `⌛ Controls expired • NodeLink • ${totalLines} lines`
|
||||
: `NodeLink • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`;
|
||||
const desc = [
|
||||
`**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`,
|
||||
``,
|
||||
'```',
|
||||
pages[pageIdx],
|
||||
totalPages > 1 && !expired && !closed ? `\n\n💡 ⬅️ ➡️ Navigate • ❌ Close` : '',
|
||||
'```'
|
||||
].join('\n');
|
||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText })] };
|
||||
};
|
||||
|
||||
activeLyricsMsg = await msg.reply(buildLyricsContent(0));
|
||||
|
||||
if (activeLyricsMsg?.message && totalPages > 1) {
|
||||
const navEmojis = ["⬅️", "➡️", "❌"];
|
||||
for (const emoji of navEmojis) {
|
||||
await activeLyricsMsg.message.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
const resetLyricsTimer = () => {
|
||||
clearTimeout(lyricsEmojiTimeout);
|
||||
lyricsEmojiTimeout = setTimeout(async () => {
|
||||
await clearLyricsReactions(activeLyricsMsg);
|
||||
await activeLyricsMsg.edit(buildLyricsContent(currentPage, true, false)).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
lyricsUnobserve = activeLyricsMsg.onReaction(navEmojis, async (e) => {
|
||||
if (e.emoji_id === "❌") {
|
||||
lyricsUnobserve();
|
||||
clearTimeout(lyricsEmojiTimeout);
|
||||
await clearLyricsReactions(activeLyricsMsg);
|
||||
await activeLyricsMsg.edit(buildLyricsContent(currentPage, false, true)).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
resetLyricsTimer();
|
||||
|
||||
if (e.emoji_id === "⬅️") {
|
||||
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
||||
} else if (e.emoji_id === "➡️") {
|
||||
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
await activeLyricsMsg.edit(buildLyricsContent(currentPage));
|
||||
});
|
||||
|
||||
resetLyricsTimer();
|
||||
} else if (activeLyricsMsg?.message) {
|
||||
await activeLyricsMsg.message.react("❌").catch(() => {});
|
||||
|
||||
const resetLyricsTimer = () => {
|
||||
clearTimeout(lyricsEmojiTimeout);
|
||||
lyricsEmojiTimeout = setTimeout(async () => {
|
||||
await clearLyricsReactions(activeLyricsMsg);
|
||||
await activeLyricsMsg.edit(buildLyricsContent(0, true, false)).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
lyricsUnobserve = activeLyricsMsg.onReaction(["❌"], async (e) => {
|
||||
if (e.emoji_id === "❌") {
|
||||
lyricsUnobserve();
|
||||
clearTimeout(lyricsEmojiTimeout);
|
||||
await clearLyricsReactions(activeLyricsMsg);
|
||||
await activeLyricsMsg.edit(buildLyricsContent(0, false, true)).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
resetLyricsTimer();
|
||||
}
|
||||
|
||||
reply = this.t(msg, "responses.player.lyricsDisplayed", { lines: totalLines, pages: totalPages });
|
||||
|
||||
} catch (err) {
|
||||
reply = this.t(msg, "responses.player.lyricsError", { error: Utils.truncate(err.message, 50) });
|
||||
}
|
||||
reply = await openLyricsViewer(this, msg, player, refresh, lyrics);
|
||||
shouldUpdate = true;
|
||||
break;
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* @module commands/player/consts
|
||||
* @description Pure display constants for the player control panel: state
|
||||
* emoji indicators, control button definitions and progress-bar characters.
|
||||
*/
|
||||
|
||||
/** @type {Object.<string, string>} Emoji indicators for player states. */
|
||||
export const STATES = {
|
||||
playing: "🎵",
|
||||
paused: "⏸️",
|
||||
stopped: "🔇",
|
||||
loading: "⏳"
|
||||
};
|
||||
|
||||
/** @type {Object.<string, {emoji: string, action: string, desc: string}>} Available control button definitions. */
|
||||
export const CONTROLS = {
|
||||
prev: { emoji: "⏮️", action: "previous", desc: "Previous" },
|
||||
play: { emoji: "▶️", action: "resume", desc: "Play" },
|
||||
pause: { emoji: "⏸️", action: "pause", desc: "Pause" },
|
||||
stop: { emoji: "⏹️", action: "stop", desc: "Stop" },
|
||||
next: { emoji: "⏭️", action: "skip", desc: "Skip" },
|
||||
loop: { emoji: "🔁", action: "loop", desc: "Loop" },
|
||||
shuffle: { emoji: "🔀", action: "shuffle", desc: "Shuffle" },
|
||||
volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" },
|
||||
volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" },
|
||||
lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" },
|
||||
filter: { emoji: "🎛️", action: "filter", desc: "Audio Filters" },
|
||||
close: { emoji: "❌", action: "close", desc: "Close" }
|
||||
};
|
||||
|
||||
/** @type {Object.<string, string>} Progress bar character set. */
|
||||
export const PROGRESS = {
|
||||
filled: "▰",
|
||||
empty: "▱",
|
||||
indicator: "●",
|
||||
start: "▏",
|
||||
end: "▕"
|
||||
};
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* @module commands/player/embed
|
||||
* @description Player panel embed construction: state emoji, progress bar,
|
||||
* volume gauge, loop/filter status and footer (verbatim body of the original
|
||||
* run() closure, with the bot instance passed explicitly instead of `this`).
|
||||
*/
|
||||
|
||||
import { Utils } from "../../src/utils/Utils.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { STATES, PROGRESS } from "./consts.mjs";
|
||||
|
||||
/**
|
||||
* Build the player panel embed with current state, progress, volume, and loop info.
|
||||
* @param {object} bot - The bot instance (used for locale translation).
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} player - The guild player.
|
||||
* @param {number} timeout - Session timeout in ms (shown in the footer area).
|
||||
* @param {object} [state={}] - Optional state override with a message field.
|
||||
* @returns {EmbedBuilder} The constructed embed builder.
|
||||
*/
|
||||
export function buildPlayerEmbed(bot, msg, player, timeout, state = {}) {
|
||||
const current = player.queue.getCurrent();
|
||||
const isPlaying = !player.paused && current;
|
||||
const statusEmoji = isPlaying ? STATES.playing : player.paused ? STATES.paused : STATES.stopped;
|
||||
|
||||
let progressBar = "";
|
||||
let timeDisplay = "`0:00 / 0:00`";
|
||||
|
||||
if (current?.duration && player.startedPlaying) {
|
||||
const elapsed = Date.now() - player.startedPlaying;
|
||||
const totalMs = typeof current.duration === "object"
|
||||
? (current.duration.seconds ?? 0) * 1000
|
||||
: current.duration;
|
||||
|
||||
const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled);
|
||||
progressBar = PROGRESS.start + bar + PROGRESS.end;
|
||||
|
||||
const elapsedStr = Utils.prettifyMS(elapsed);
|
||||
const totalStr = Utils.prettifyMS(totalMs);
|
||||
timeDisplay = `\`${elapsedStr} / ${totalStr}\``;
|
||||
} else {
|
||||
progressBar = PROGRESS.start + PROGRESS.empty.repeat(20) + PROGRESS.end;
|
||||
}
|
||||
|
||||
const volPercent = Math.round((player.preferredVolume ?? 1) * 100);
|
||||
const volBars = Math.ceil(volPercent / 10);
|
||||
const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars);
|
||||
|
||||
const queueSize = player.queue.size();
|
||||
const loopStatus = player.queue.songLoop ? bot.t(msg, "responses.player.loopSong") : player.queue.loop ? bot.t(msg, "responses.player.loopQueue") : bot.t(msg, "responses.player.loopOff");
|
||||
|
||||
let filterStatus = bot.t(msg, "responses.player.filterOff");
|
||||
if (player.activeFilter) {
|
||||
if (player.activeFilter.label.includes("+")) {
|
||||
filterStatus = `🔥 **${player.activeFilter.label}**`;
|
||||
} else {
|
||||
filterStatus = `${player.activeFilter.emoji ?? "🎛️"} **${player.activeFilter.label}**`;
|
||||
}
|
||||
}
|
||||
|
||||
const nowPlaying = current
|
||||
? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})`
|
||||
: bot.t(msg, "responses.filter.nothingPlayingInline");
|
||||
|
||||
const description = [
|
||||
`${statusEmoji} ${bot.t(msg, "responses.player.nowPlayingLabel")}`,
|
||||
`${nowPlaying}`,
|
||||
``,
|
||||
`${progressBar}`,
|
||||
`${timeDisplay}`,
|
||||
``,
|
||||
bot.t(msg, "responses.player.volumeLabel", { volume: volPercent }) + " " + volumeBar,
|
||||
`${bot.t(msg, "responses.player.queueLabel", { count: queueSize })} | Loop: ${loopStatus} | Filter: ${filterStatus}`,
|
||||
``,
|
||||
state.message ? `💬 *${state.message}*` : `💡 *${bot.t(msg, "responses.player.reactHint")}*`,
|
||||
``,
|
||||
bot.t(msg, "responses.player.sessionExpires", { minutes: Math.ceil(timeout / 60000) })
|
||||
].join("\n");
|
||||
|
||||
const avatarUrl = typeof msg.author?.avatarURL === "function"
|
||||
? msg.author.avatarURL()
|
||||
: msg.author?.avatarURL ?? null;
|
||||
|
||||
const builder = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(bot.t(msg, "responses.player.title"))
|
||||
.setDescription(description)
|
||||
.setFooter({
|
||||
text: bot.t(msg, "responses.player.requestedBy", { username: msg.author?.username || "Unknown" }),
|
||||
iconURL: avatarUrl
|
||||
});
|
||||
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
||||
if (current?.thumbnail) builder.setThumbnail(current.thumbnail);
|
||||
return builder;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* @module commands/player
|
||||
* @description Barrel for the player control-panel implementation modules.
|
||||
* commands/player.mjs (the command entry file) imports through this barrel;
|
||||
* it stays the single import surface for the group.
|
||||
*/
|
||||
|
||||
export { STATES, CONTROLS, PROGRESS } from "./consts.mjs";
|
||||
export { buildPlayerEmbed } from "./embed.mjs";
|
||||
export { openLyricsViewer, clearLyricsReactions } from "./lyrics.mjs";
|
||||
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* @module commands/player/lyrics
|
||||
* @description Embedded lyrics viewer for the player panel (verbatim body of
|
||||
* the original "lyrics" reaction case): paginated lyric pages with navigation
|
||||
* reactions, control-expiry timer and close handling. Session-scoped mutable
|
||||
* state lives in the shared `session` object ({activeLyricsMsg, unobserve,
|
||||
* emojiTimeout}) so the panel's closeSession can clean it up.
|
||||
*/
|
||||
|
||||
import { Utils } from "../../src/utils/Utils.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||
import { EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs";
|
||||
import { logger } from "../../src/core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Remove navigation reactions from a lyrics message.
|
||||
* @param {object} lyricsMsg - The wrapped lyrics message with a .message property.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function clearLyricsReactions(lyricsMsg) {
|
||||
if (!lyricsMsg?.message) return;
|
||||
try {
|
||||
await lyricsMsg.message.removeAllReactions();
|
||||
} catch (e) {
|
||||
for (const emoji of ["⬅️", "➡️", "❌"]) {
|
||||
try {
|
||||
await lyricsMsg.message.removeReaction(emoji);
|
||||
} catch(e) { logger.warn("[Player] Error:", e?.message); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Open (or reopen) the lyrics viewer for the player's current track.
|
||||
*
|
||||
* Mirrors the original `case "lyrics":` flow exactly: announces fetching,
|
||||
* tears down a previous viewer, fetches lyrics from the player, renders
|
||||
* paginated content, wires navigation/close reactions with the shared
|
||||
* emoji-expiry timer, and returns the final reply string. Every exit path
|
||||
* corresponds to `shouldUpdate = true` in the original switch, so the caller
|
||||
* always refreshes the panel afterwards.
|
||||
*
|
||||
* @param {object} bot - The bot instance (locale translation via bot.t).
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {object} player - The guild player (player.lyrics(), queue).
|
||||
* @param {function} refresh - Panel refresh callback ({ message }) => void.
|
||||
* @param {object} session - Shared viewer state: { activeLyricsMsg, unobserve, emojiTimeout }.
|
||||
* @returns {Promise<string>} The reply message text to surface on the panel.
|
||||
*/
|
||||
export async function openLyricsViewer(bot, msg, player, refresh, session) {
|
||||
let reply = bot.t(msg, "responses.player.fetchingLyrics");
|
||||
refresh({ message: reply });
|
||||
|
||||
try {
|
||||
if (session.unobserve) {
|
||||
session.unobserve();
|
||||
clearTimeout(session.emojiTimeout);
|
||||
if (session.activeLyricsMsg) await clearLyricsReactions(session.activeLyricsMsg);
|
||||
}
|
||||
|
||||
const lyricsResult = await player.lyrics();
|
||||
if (!lyricsResult) {
|
||||
return bot.t(msg, "responses.player.noLyricsFound");
|
||||
}
|
||||
|
||||
const syncBadge = lyricsResult.synced ? " ⏱️ Synced" : "";
|
||||
const lines = lyricsResult.text.split('\n');
|
||||
const totalLines = lines.length;
|
||||
const LINES_PER_PAGE = 25;
|
||||
const totalPages = Math.ceil(totalLines / LINES_PER_PAGE);
|
||||
|
||||
const pages = [];
|
||||
for (let i = 0; i < totalLines; i += LINES_PER_PAGE) {
|
||||
pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n'));
|
||||
}
|
||||
|
||||
let currentPage = 0;
|
||||
|
||||
const buildLyricsContent = (pageIdx, expired = false, closed = false) => {
|
||||
const title = Utils.truncate(
|
||||
player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '',
|
||||
50
|
||||
);
|
||||
const footerText = closed
|
||||
? `👋 Lyrics closed • NodeLink • ${totalLines} lines`
|
||||
: expired
|
||||
? `⌛ Controls expired • NodeLink • ${totalLines} lines`
|
||||
: `NodeLink • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`;
|
||||
const desc = [
|
||||
`**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`,
|
||||
``,
|
||||
'```',
|
||||
pages[pageIdx],
|
||||
totalPages > 1 && !expired && !closed ? `\n\n💡 ⬅️ ➡️ Navigate • ❌ Close` : '',
|
||||
'```'
|
||||
].join('\n');
|
||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText })] };
|
||||
};
|
||||
|
||||
session.activeLyricsMsg = await msg.reply(buildLyricsContent(0));
|
||||
|
||||
if (session.activeLyricsMsg?.message && totalPages > 1) {
|
||||
const navEmojis = ["⬅️", "➡️", "❌"];
|
||||
for (const emoji of navEmojis) {
|
||||
await session.activeLyricsMsg.message.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
const resetLyricsTimer = () => {
|
||||
clearTimeout(session.emojiTimeout);
|
||||
session.emojiTimeout = setTimeout(async () => {
|
||||
await clearLyricsReactions(session.activeLyricsMsg);
|
||||
await session.activeLyricsMsg.edit(buildLyricsContent(currentPage, true, false)).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
session.unobserve = session.activeLyricsMsg.onReaction(navEmojis, async (e) => {
|
||||
if (e.emoji_id === "❌") {
|
||||
session.unobserve();
|
||||
clearTimeout(session.emojiTimeout);
|
||||
await clearLyricsReactions(session.activeLyricsMsg);
|
||||
await session.activeLyricsMsg.edit(buildLyricsContent(currentPage, false, true)).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
resetLyricsTimer();
|
||||
|
||||
if (e.emoji_id === "⬅️") {
|
||||
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
||||
} else if (e.emoji_id === "➡️") {
|
||||
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
await session.activeLyricsMsg.edit(buildLyricsContent(currentPage));
|
||||
});
|
||||
|
||||
resetLyricsTimer();
|
||||
} else if (session.activeLyricsMsg?.message) {
|
||||
await session.activeLyricsMsg.message.react("❌").catch(() => {});
|
||||
|
||||
const resetLyricsTimer = () => {
|
||||
clearTimeout(session.emojiTimeout);
|
||||
session.emojiTimeout = setTimeout(async () => {
|
||||
await clearLyricsReactions(session.activeLyricsMsg);
|
||||
await session.activeLyricsMsg.edit(buildLyricsContent(0, true, false)).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
session.unobserve = session.activeLyricsMsg.onReaction(["❌"], async (e) => {
|
||||
if (e.emoji_id === "❌") {
|
||||
session.unobserve();
|
||||
clearTimeout(session.emojiTimeout);
|
||||
await clearLyricsReactions(session.activeLyricsMsg);
|
||||
await session.activeLyricsMsg.edit(buildLyricsContent(0, false, true)).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
resetLyricsTimer();
|
||||
}
|
||||
|
||||
return bot.t(msg, "responses.player.lyricsDisplayed", { lines: totalLines, pages: totalPages });
|
||||
|
||||
} catch (err) {
|
||||
return bot.t(msg, "responses.player.lyricsError", { error: Utils.truncate(err.message, 50) });
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,10 @@
|
||||
* Supports inline provider prefixes and flag-based provider selection.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||
|
||||
|
||||
/**
|
||||
|
||||
+4
-4
@@ -3,11 +3,11 @@
|
||||
* @description Play internet radio stations with interactive station selection via reactions.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/constants/UI.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/utils/UI.mjs";
|
||||
|
||||
|
||||
/**
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@
|
||||
* @description Owner-only command to hot-reload commands, source modules, or audio modules at runtime.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
* @description Remove a specific track from the queue by its position.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the remove command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@
|
||||
* @description Resume paused playback in the current voice channel.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/**
|
||||
* @type {CommandBuilder}
|
||||
|
||||
+5
-5
@@ -3,12 +3,12 @@
|
||||
* @description Search for tracks across providers and pick one to play via reaction selection.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { Message, getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { Message, getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/constants/providers.mjs";
|
||||
import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/constants/UI.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||
import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/utils/UI.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the search command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+4
-4
@@ -3,11 +3,11 @@
|
||||
* @description Seek to a specific position in the currently playing track.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
import { ERROR_COLOR } from "../src/constants/UI.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { Utils } from "../src/utils/Utils.mjs";
|
||||
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the seek command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
* @description Owner-only command to list all servers the bot is in with pagination.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the servers command (owner-only). */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+15
-448
@@ -1,455 +1,22 @@
|
||||
/**
|
||||
* @module commands/settings
|
||||
* @description Server settings management with subcommands (get/set/reset/help) and shortcut aliases (prefix, 247).
|
||||
* @description Server settings management with subcommands (get/set/reset/help) and
|
||||
* shortcut aliases (prefix, 247). The helpers live in commands/settings/ (utils,
|
||||
* channels247, setters); the command factory and run() dispatch stay here.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import runnables from "../settings/runnables.mjs";
|
||||
|
||||
/**
|
||||
* Command alias to setting key mapping.
|
||||
* @type {Object.<string, string>}
|
||||
*/
|
||||
const SHORTCUTS = {
|
||||
prefix: "prefix",
|
||||
pfx: "prefix",
|
||||
"247": "stay_247",
|
||||
};
|
||||
|
||||
/** @private @type {Set<string>} Strings that evaluate to boolean true. */
|
||||
const BOOL_TRUE = new Set(["true", "1", "yes", "on", "enable", "enabled"]);
|
||||
/** @private @type {Set<string>} Strings that evaluate to boolean false. */
|
||||
const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]);
|
||||
/** @private @type {Set<string>} Setting keys that use boolean display formatting. */
|
||||
const BOOL_SETTINGS = new Set(["songAnnouncements"]);
|
||||
|
||||
/** @private @type {Set<string>} Available locale codes, populated at load time. */
|
||||
let VALID_LOCALES = new Set(["en"]);
|
||||
|
||||
/** @private @type {number} Minimum allowed volume value. */
|
||||
const VOLUME_MIN = 1;
|
||||
/** @private @type {number} Maximum allowed volume value. */
|
||||
const VOLUME_MAX = 200;
|
||||
/** @private @type {number} Maximum prefix length in characters. */
|
||||
const PREFIX_MAX = 5;
|
||||
/** @private @type {number} Maximum number of 24/7 channels per guild. */
|
||||
const MAX_247_CHANNELS = 1;
|
||||
|
||||
/**
|
||||
* Check whether a string looks like a valid Fluxer ID (Snowflake-like).
|
||||
* @param {string} id - The ID to validate.
|
||||
* @returns {boolean} True if the ID is 15-22 characters after cleaning.
|
||||
*/
|
||||
function isValidFluxerId(id) {
|
||||
const cleaned = cleanId(id);
|
||||
return cleaned.length >= 15 && cleaned.length <= 22;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a string into a boolean, or return null if unrecognised.
|
||||
* @param {string} str - The string to parse.
|
||||
* @returns {boolean|null} True, false, or null if not a boolean string.
|
||||
*/
|
||||
function parseBool(str) {
|
||||
const s = String(str).toLowerCase().trim();
|
||||
if (BOOL_TRUE.has(s)) return true;
|
||||
if (BOOL_FALSE.has(s)) return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a setting value for display in embed messages.
|
||||
* @param {string} key - The setting key.
|
||||
* @param {*} value - The setting value.
|
||||
* @returns {string} Formatted display string.
|
||||
*/
|
||||
function displayValue(key, value) {
|
||||
if (BOOL_SETTINGS.has(key)) return value ? "\u2705 enabled" : "\u274c disabled";
|
||||
if (value === null || value === undefined || value === "none") return "none";
|
||||
return "`" + value + "`";
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Get the display name of the guild from a message object.
|
||||
* @param {object} message - The command message wrapper.
|
||||
* @returns {string} The guild name, or a fallback string.
|
||||
*/
|
||||
function getGuildName(message) {
|
||||
return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server";
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Create a simple embed payload with global color, description, and optional title/footer.
|
||||
* @param {string} desc - The embed description text.
|
||||
* @param {object} [opts={}] - Optional overrides for title, iconURL, and footer.
|
||||
* @returns {object} Embed payload for message.reply().
|
||||
*/
|
||||
function embed(desc, opts = {}) {
|
||||
const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
|
||||
if (opts.title) b.setTitle(opts.title);
|
||||
if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL });
|
||||
if (opts.footer) b.setFooter({ text: opts.footer });
|
||||
return { embeds: [b] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the stay_247 setting into a Set of validated channel IDs.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @returns {Set<string>} Set of cleaned, valid channel IDs.
|
||||
*/
|
||||
function get247Channels(set) {
|
||||
const raw = set.get("stay_247");
|
||||
if (!raw || raw === "none") return new Set();
|
||||
if (typeof raw === "string") {
|
||||
const id = cleanId(raw);
|
||||
return (id && isValidFluxerId(id)) ? new Set([id]) : new Set();
|
||||
}
|
||||
if (Array.isArray(raw)) {
|
||||
return new Set(raw.map(id => cleanId(id)).filter(id => id && isValidFluxerId(id)));
|
||||
}
|
||||
return new Set();
|
||||
}
|
||||
|
||||
/**
|
||||
* Save a Set of channel IDs back to the stay_247 setting.
|
||||
* Writes 'none' if the set is empty.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {Set<string>} channels - The channel IDs to save.
|
||||
*/
|
||||
function save247Channels(set, channels) {
|
||||
const arr = [...channels].filter(id => id && isValidFluxerId(id));
|
||||
set.set("stay_247", arr.length > 0 ? arr : "none");
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Resolve a channel ID to a human-readable channel name from the client cache.
|
||||
* @param {import('@fluxerjs/core').Client} client - The Discord/Fluxer client.
|
||||
* @param {string} channelId - The channel ID to look up.
|
||||
* @returns {string|null} The channel name, or null if not found.
|
||||
*/
|
||||
function resolveChannelName(client, channelId) {
|
||||
try {
|
||||
const ch = client?.channels?.get?.(channelId);
|
||||
if (ch?.name) return ch.name;
|
||||
} catch (_) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Create a translation function bound to the given context and guild.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {string} guildId - The guild ID for localization.
|
||||
* @returns {Function} A translation function with signature (key, data?) => string.
|
||||
*/
|
||||
function tWrap(ctx, guildId) {
|
||||
const tFn = ctx.locale?.translate?.bind(ctx.locale);
|
||||
return (key, data = {}) => tFn ? tFn(guildId, key, data) : key;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Get a human-readable label for a setting key, using locale translations when available.
|
||||
* @param {string} key - The setting key.
|
||||
* @param {Function|null} t - Translation function (guildId, key, data) => string.
|
||||
* @param {string} guildId - The guild ID for localization.
|
||||
* @returns {string} The pretty-printed setting label.
|
||||
*/
|
||||
function prettifySettingLabel(key, t, guildId) {
|
||||
const localeMap = {
|
||||
songAnnouncements: "responses.settings.labelSongAnnouncements",
|
||||
prefix: "responses.settings.labelPrefix",
|
||||
pfx: "responses.settings.labelPfp",
|
||||
locale: "responses.settings.labelLocale",
|
||||
stay_247: "responses.settings.label247",
|
||||
volume: "responses.settings.labelVolume",
|
||||
};
|
||||
if (localeMap[key] && t && guildId) return t(guildId, localeMap[key]);
|
||||
const fallback = {
|
||||
songAnnouncements: "Song announcements",
|
||||
prefix: "Prefix",
|
||||
pfp: "Bot avatar style",
|
||||
locale: "Locale",
|
||||
stay_247: "24/7 mode",
|
||||
volume: "Default volume",
|
||||
};
|
||||
return fallback[key] ?? key.replace(/_/g, " ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an embed payload showing the current 24/7 status for the guild.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string|null} channelId - The channel ID (for active indicator), or null.
|
||||
* @returns {object} Embed payload object for message.reply().
|
||||
*/
|
||||
function build247Panel(set, ctx, guildId, channelId) {
|
||||
const channels = [...get247Channels(set)];
|
||||
const prefix = ctx.handler.getPrefix(guildId);
|
||||
|
||||
if (channels.length > 0) {
|
||||
const lines = channels.map(id => {
|
||||
const name = resolveChannelName(ctx.client, id);
|
||||
const isActive = id === channelId;
|
||||
return (isActive ? "\u25b6 " : "\u2022 ") + (name ? "**" + name + "** " : "") + "<#" + id + ">";
|
||||
});
|
||||
return embed(
|
||||
channels.length === 1 && channelId
|
||||
? "\u2705 24/7 is now **enabled** in <#" + channelId + ">\n\n" +
|
||||
"The bot will stay connected and auto-rejoin if disconnected."
|
||||
: "\u2705 24/7 active in " + channels.length + " channel(s):\n\n" + lines.join("\n"),
|
||||
{ title: "\u2705 24/7 Mode" }
|
||||
);
|
||||
}
|
||||
|
||||
return embed(
|
||||
"\u274c 24/7 is **disabled**\n\n" +
|
||||
"The bot will leave voice channels when idle.\n\n" +
|
||||
"Join a voice channel and use `" + prefix + "247` to enable.",
|
||||
{ title: "\u274c 24/7 Mode" }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Disable 24/7 mode for a specific channel.
|
||||
* Removes the channel from stay_247, marks intentional leave, and destroys the player.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The channel ID to disable.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function disable247(ctx, set, guildId, channelId) {
|
||||
const id = cleanId(channelId);
|
||||
const channels = get247Channels(set);
|
||||
channels.delete(id);
|
||||
save247Channels(set, channels);
|
||||
ctx.markIntentionalLeave?.(id);
|
||||
const player = ctx.players.playerMap.get(id)
|
||||
?? [...ctx.players.playerMap.values()].find(p =>
|
||||
cleanId(p?._channelId ?? "") === id &&
|
||||
cleanId(p?._guildId ?? "") === cleanId(guildId)
|
||||
);
|
||||
if (player) {
|
||||
const activeId = cleanId(player._channelId ?? id);
|
||||
ctx.players.playerMap.delete(activeId);
|
||||
if (activeId !== id) ctx.players.playerMap.delete(id);
|
||||
await player.leave().catch(() => {});
|
||||
player.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable 24/7 mode for a specific channel.
|
||||
* Enforces MAX_247_CHANNELS (1) by disabling any existing 24/7 channel first,
|
||||
* then saves the new channel and spawns a player if none exists.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The channel ID to enable.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function enable247(ctx, set, guildId, channelId) {
|
||||
const id = cleanId(channelId);
|
||||
const channels = get247Channels(set);
|
||||
if (channels.has(id)) return;
|
||||
|
||||
// Platform only supports 1 voice channel per bot per guild.
|
||||
// If another channel already has 24/7, disable it first.
|
||||
if (channels.size >= MAX_247_CHANNELS) {
|
||||
for (const oldId of channels) {
|
||||
if (oldId !== id) {
|
||||
ctx.markIntentionalLeave?.(oldId);
|
||||
const oldPlayer = ctx.players.playerMap.get(oldId)
|
||||
?? [...ctx.players.playerMap.values()].find(p =>
|
||||
cleanId(p?._channelId ?? "") === oldId &&
|
||||
cleanId(p?._guildId ?? "") === cleanId(guildId)
|
||||
);
|
||||
if (oldPlayer) {
|
||||
const activeId = cleanId(oldPlayer._channelId ?? oldId);
|
||||
ctx.players.playerMap.delete(activeId);
|
||||
if (activeId !== oldId) ctx.players.playerMap.delete(oldId);
|
||||
await oldPlayer.leave().catch(() => {});
|
||||
oldPlayer.destroy();
|
||||
}
|
||||
channels.delete(oldId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
channels.add(id);
|
||||
save247Channels(set, channels);
|
||||
const playerExists = ctx.players.playerMap.has(id) ||
|
||||
[...ctx.players.playerMap.values()].some(p =>
|
||||
cleanId(p?._channelId ?? "") === id && cleanId(p?._guildId ?? "") === cleanId(guildId)
|
||||
);
|
||||
if (!playerExists) {
|
||||
try { await ctx._spawnPlayer(guildId, id); } catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the !247 toggle command. If the user is in a 24/7 channel, disable it;
|
||||
* otherwise, enable it for the user's current voice channel.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {object} message - The command message.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function handle247Toggle(ctx, message, set, guildId) {
|
||||
const loc = tWrap(ctx, guildId);
|
||||
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
|
||||
|
||||
const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message);
|
||||
if (!userChannelId) {
|
||||
return message.reply(build247Panel(set, ctx, guildId, null));
|
||||
}
|
||||
|
||||
const id = cleanId(userChannelId);
|
||||
const channels = get247Channels(set);
|
||||
|
||||
if (channels.has(id)) {
|
||||
await disable247(ctx, set, guildId, userChannelId);
|
||||
return message.reply(build247Panel(set, ctx, guildId, id));
|
||||
}
|
||||
|
||||
const result = await enable247(ctx, set, guildId, userChannelId);
|
||||
if (result?.max) {
|
||||
return message.reply(embed(
|
||||
loc("responses.settings.max247Channels", { max: MAX_247_CHANNELS, prefix: ctx.handler.getPrefix(guildId) })
|
||||
));
|
||||
}
|
||||
|
||||
return message.reply(build247Panel(set, ctx, guildId, id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a new value to a setting, with type-specific validation.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {object} message - The command message.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {string} key - The setting key.
|
||||
* @param {string} rawValue - The raw string value from the command.
|
||||
* @returns {Promise<string|null>} Error message string, or null on success.
|
||||
*/
|
||||
async function applySet(ctx, message, set, key, rawValue) {
|
||||
if (BOOL_SETTINGS.has(key)) {
|
||||
const bool = parseBool(rawValue);
|
||||
if (bool === null) {
|
||||
return ctx.t(message, "responses.settings.mustBeBool", { setting: key });
|
||||
}
|
||||
set.set(key, bool);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (key === "volume") {
|
||||
const num = parseInt(rawValue, 10);
|
||||
if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) {
|
||||
return ctx.t(message, "responses.settings.volumeRange");
|
||||
}
|
||||
set.set(key, num);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (key === "locale") {
|
||||
if (!VALID_LOCALES.has(rawValue)) {
|
||||
return ctx.t(message, "responses.settings.invalidLocale", {
|
||||
locale: rawValue,
|
||||
locales: [...VALID_LOCALES].map(l => "`" + l + "`").join(", ")
|
||||
});
|
||||
}
|
||||
set.set(key, rawValue);
|
||||
const gid = getMessageGuildId(message);
|
||||
if (gid) ctx.locale.invalidateCache(gid);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (key === "prefix") {
|
||||
if (!rawValue || rawValue.length > PREFIX_MAX) {
|
||||
return ctx.t(message, "responses.settings.prefixLength");
|
||||
}
|
||||
if (/\s/.test(rawValue)) {
|
||||
return ctx.t(message, "responses.settings.prefixSpaces");
|
||||
}
|
||||
}
|
||||
|
||||
if (runnables[key]) {
|
||||
const err = runnables[key].call(ctx, rawValue, { msg: message });
|
||||
if (err) return "\u274c " + err;
|
||||
}
|
||||
|
||||
set.set(key, rawValue);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
* @async
|
||||
* Handle a settings shortcut command (e.g. `prefix`, `247`).
|
||||
* Dispatches to 24/7 toggle, value display, or value set depending on arguments.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {object} message - The command message.
|
||||
* @param {string} settingKey - The resolved setting key.
|
||||
* @param {string[]} valueTokens - Remaining argument tokens after the shortcut alias.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
||||
const set = ctx.getSettings(message);
|
||||
const guildId = getMessageGuildId(message);
|
||||
const t247 = ctx.locale?.translate?.bind(ctx.locale);
|
||||
|
||||
if (valueTokens.length === 0) {
|
||||
if (settingKey === "stay_247") {
|
||||
return handle247Toggle(ctx, message, set, guildId);
|
||||
}
|
||||
const val = set.get(settingKey);
|
||||
const label = prettifySettingLabel(settingKey, t247, guildId);
|
||||
return message.reply(embed("**" + label + "**\nValue: " + displayValue(settingKey, val)));
|
||||
}
|
||||
|
||||
const rawValue = valueTokens.join(" ");
|
||||
|
||||
if (settingKey === "stay_247") {
|
||||
const mode = rawValue.toLowerCase().trim();
|
||||
if (mode === "off" || mode === "false" || mode === "disable" || mode === "0") {
|
||||
const loc = tWrap(ctx, guildId);
|
||||
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
|
||||
const { channelId } = await ctx.players.checkVoiceChannels(message);
|
||||
if (channelId) {
|
||||
await disable247(ctx, set, guildId, channelId);
|
||||
return message.reply(build247Panel(set, ctx, guildId, cleanId(channelId)));
|
||||
}
|
||||
for (const [chId, player] of [...ctx.players.playerMap.entries()]) {
|
||||
if (cleanId(player?._guildId ?? "") === cleanId(guildId)) {
|
||||
const activeId = cleanId(player._channelId ?? chId);
|
||||
ctx.markIntentionalLeave?.(activeId);
|
||||
ctx.players.playerMap.delete(activeId);
|
||||
if (activeId !== chId) ctx.players.playerMap.delete(chId);
|
||||
await player.leave().catch(() => {});
|
||||
player.destroy();
|
||||
}
|
||||
}
|
||||
save247Channels(set, new Set());
|
||||
return message.reply(build247Panel(set, ctx, guildId, null));
|
||||
}
|
||||
return handle247Toggle(ctx, message, set, guildId);
|
||||
}
|
||||
|
||||
const err = await applySet(ctx, message, set, settingKey, rawValue);
|
||||
if (err) return message.reply(embed(err));
|
||||
|
||||
const val = set.get(settingKey);
|
||||
const label = prettifySettingLabel(settingKey, t247, guildId);
|
||||
return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label, value: displayValue(settingKey, val) })));
|
||||
}
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { getMessageGuildId } from "../src/ui/index.mjs";
|
||||
// kept verbatim from the original file (unused there as well):
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import {
|
||||
SHORTCUTS, BOOL_SETTINGS, VALID_LOCALES, setValidLocales,
|
||||
VOLUME_MIN, VOLUME_MAX,
|
||||
displayValue, getGuildName, embed, prettifySettingLabel,
|
||||
} from "./settings/utils.mjs";
|
||||
import { get247Channels, build247Panel } from "./settings/channels247.mjs";
|
||||
import { applySet, handleShortcut } from "./settings/setters.mjs";
|
||||
|
||||
/**
|
||||
* @type {Function}
|
||||
@@ -459,7 +26,7 @@ async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
||||
*/
|
||||
export const command = function() {
|
||||
if (this.locale) {
|
||||
VALID_LOCALES = this.locale.availableLocales();
|
||||
setValidLocales(this.locale.availableLocales());
|
||||
}
|
||||
|
||||
if (this.loader) {
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* @module commands/settings/channels247
|
||||
* @description 24/7 channel storage, panel
|
||||
* rendering and enable/disable/toggle handling for the settings command.
|
||||
* Bodies are verbatim from the original single-file command.
|
||||
*/
|
||||
|
||||
|
||||
import { cleanId } from "../../src/ui/index.mjs";
|
||||
import { isValidFluxerId, MAX_247_CHANNELS, embed, tWrap } from "./utils.mjs";
|
||||
|
||||
/**
|
||||
* Parse the stay_247 setting into a Set of validated channel IDs.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @returns {Set<string>} Set of cleaned, valid channel IDs.
|
||||
*/
|
||||
export function get247Channels(set) {
|
||||
const raw = set.get("stay_247");
|
||||
if (!raw || raw === "none") return new Set();
|
||||
if (typeof raw === "string") {
|
||||
const id = cleanId(raw);
|
||||
return (id && isValidFluxerId(id)) ? new Set([id]) : new Set();
|
||||
}
|
||||
if (Array.isArray(raw)) {
|
||||
return new Set(raw.map(id => cleanId(id)).filter(id => id && isValidFluxerId(id)));
|
||||
}
|
||||
return new Set();
|
||||
}
|
||||
/**
|
||||
* Save a Set of channel IDs back to the stay_247 setting.
|
||||
* Writes 'none' if the set is empty.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {Set<string>} channels - The channel IDs to save.
|
||||
*/
|
||||
export function save247Channels(set, channels) {
|
||||
const arr = [...channels].filter(id => id && isValidFluxerId(id));
|
||||
set.set("stay_247", arr.length > 0 ? arr : "none");
|
||||
}
|
||||
/**
|
||||
* @private
|
||||
* Resolve a channel ID to a human-readable channel name from the client cache.
|
||||
* @param {import('@fluxerjs/core').Client} client - The Fluxer client.
|
||||
* @param {string} channelId - The channel ID to look up.
|
||||
* @returns {string|null} The channel name, or null if not found.
|
||||
*/
|
||||
function resolveChannelName(client, channelId) {
|
||||
try {
|
||||
const ch = client?.channels?.get?.(channelId);
|
||||
if (ch?.name) return ch.name;
|
||||
} catch (_) {}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an embed payload showing the current 24/7 status for the guild.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string|null} channelId - The channel ID (for active indicator), or null.
|
||||
* @returns {object} Embed payload object for message.reply().
|
||||
*/
|
||||
export function build247Panel(set, ctx, guildId, channelId) {
|
||||
const channels = [...get247Channels(set)];
|
||||
const prefix = ctx.handler.getPrefix(guildId);
|
||||
|
||||
if (channels.length > 0) {
|
||||
const lines = channels.map(id => {
|
||||
const name = resolveChannelName(ctx.client, id);
|
||||
const isActive = id === channelId;
|
||||
return (isActive ? "\u25b6 " : "\u2022 ") + (name ? "**" + name + "** " : "") + "<#" + id + ">";
|
||||
});
|
||||
return embed(
|
||||
channels.length === 1 && channelId
|
||||
? "\u2705 24/7 is now **enabled** in <#" + channelId + ">\n\n" +
|
||||
"The bot will stay connected and auto-rejoin if disconnected."
|
||||
: "\u2705 24/7 active in " + channels.length + " channel(s):\n\n" + lines.join("\n"),
|
||||
{ title: "\u2705 24/7 Mode" }
|
||||
);
|
||||
}
|
||||
|
||||
return embed(
|
||||
"\u274c 24/7 is **disabled**\n\n" +
|
||||
"The bot will leave voice channels when idle.\n\n" +
|
||||
"Join a voice channel and use `" + prefix + "247` to enable.",
|
||||
{ title: "\u274c 24/7 Mode" }
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Disable 24/7 mode for a specific channel.
|
||||
* Removes the channel from stay_247, marks intentional leave, and destroys the player.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The channel ID to disable.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function disable247(ctx, set, guildId, channelId) {
|
||||
const id = cleanId(channelId);
|
||||
const channels = get247Channels(set);
|
||||
channels.delete(id);
|
||||
save247Channels(set, channels);
|
||||
ctx.markIntentionalLeave?.(id);
|
||||
const player = ctx.players.playerMap.get(id)
|
||||
?? [...ctx.players.playerMap.values()].find(p =>
|
||||
cleanId(p?._channelId ?? "") === id &&
|
||||
cleanId(p?._guildId ?? "") === cleanId(guildId)
|
||||
);
|
||||
if (player) {
|
||||
const activeId = cleanId(player._channelId ?? id);
|
||||
ctx.players.playerMap.delete(activeId);
|
||||
if (activeId !== id) ctx.players.playerMap.delete(id);
|
||||
await player.leave().catch(() => {});
|
||||
player.destroy();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Enable 24/7 mode for a specific channel.
|
||||
* Enforces MAX_247_CHANNELS (1) by disabling any existing 24/7 channel first,
|
||||
* then saves the new channel and spawns a player if none exists.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The channel ID to enable.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function enable247(ctx, set, guildId, channelId) {
|
||||
const id = cleanId(channelId);
|
||||
const channels = get247Channels(set);
|
||||
if (channels.has(id)) return;
|
||||
|
||||
// Platform only supports 1 voice channel per bot per guild.
|
||||
// If another channel already has 24/7, disable it first.
|
||||
if (channels.size >= MAX_247_CHANNELS) {
|
||||
for (const oldId of channels) {
|
||||
if (oldId !== id) {
|
||||
ctx.markIntentionalLeave?.(oldId);
|
||||
const oldPlayer = ctx.players.playerMap.get(oldId)
|
||||
?? [...ctx.players.playerMap.values()].find(p =>
|
||||
cleanId(p?._channelId ?? "") === oldId &&
|
||||
cleanId(p?._guildId ?? "") === cleanId(guildId)
|
||||
);
|
||||
if (oldPlayer) {
|
||||
const activeId = cleanId(oldPlayer._channelId ?? oldId);
|
||||
ctx.players.playerMap.delete(activeId);
|
||||
if (activeId !== oldId) ctx.players.playerMap.delete(oldId);
|
||||
await oldPlayer.leave().catch(() => {});
|
||||
oldPlayer.destroy();
|
||||
}
|
||||
channels.delete(oldId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
channels.add(id);
|
||||
save247Channels(set, channels);
|
||||
const playerExists = ctx.players.playerMap.has(id) ||
|
||||
[...ctx.players.playerMap.values()].some(p =>
|
||||
cleanId(p?._channelId ?? "") === id && cleanId(p?._guildId ?? "") === cleanId(guildId)
|
||||
);
|
||||
if (!playerExists) {
|
||||
try { await ctx._spawnPlayer(guildId, id); } catch (_) {}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handle the !247 toggle command. If the user is in a 24/7 channel, disable it;
|
||||
* otherwise, enable it for the user's current voice channel.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {object} message - The command message.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function handle247Toggle(ctx, message, set, guildId) {
|
||||
const loc = tWrap(ctx, guildId);
|
||||
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
|
||||
|
||||
const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message);
|
||||
if (!userChannelId) {
|
||||
return message.reply(build247Panel(set, ctx, guildId, null));
|
||||
}
|
||||
|
||||
const id = cleanId(userChannelId);
|
||||
const channels = get247Channels(set);
|
||||
|
||||
if (channels.has(id)) {
|
||||
await disable247(ctx, set, guildId, userChannelId);
|
||||
return message.reply(build247Panel(set, ctx, guildId, id));
|
||||
}
|
||||
|
||||
const result = await enable247(ctx, set, guildId, userChannelId);
|
||||
if (result?.max) {
|
||||
return message.reply(embed(
|
||||
loc("responses.settings.max247Channels", { max: MAX_247_CHANNELS, prefix: ctx.handler.getPrefix(guildId) })
|
||||
));
|
||||
}
|
||||
|
||||
return message.reply(build247Panel(set, ctx, guildId, id));
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* @module commands/settings/setters
|
||||
* @description Value application (applySet) and
|
||||
* shortcut dispatch (handleShortcut) for the settings command. Bodies are
|
||||
* verbatim from the original single-file command.
|
||||
*/
|
||||
|
||||
|
||||
import { cleanId, getMessageGuildId } from "../../src/ui/index.mjs";
|
||||
import runnables from "../../settings/runnables.mjs";
|
||||
import {
|
||||
parseBool, displayValue, getGuildName, embed, tWrap, prettifySettingLabel,
|
||||
BOOL_SETTINGS, VALID_LOCALES, VOLUME_MIN, VOLUME_MAX, PREFIX_MAX, SHORTCUTS,
|
||||
} from "./utils.mjs";
|
||||
import {
|
||||
get247Channels, save247Channels, build247Panel, disable247, handle247Toggle,
|
||||
} from "./channels247.mjs";
|
||||
|
||||
/**
|
||||
* Apply a new value to a setting, with type-specific validation.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {object} message - The command message.
|
||||
* @param {ServerSettings} set - The guild settings instance.
|
||||
* @param {string} key - The setting key.
|
||||
* @param {string} rawValue - The raw string value from the command.
|
||||
* @returns {Promise<string|null>} Error message string, or null on success.
|
||||
*/
|
||||
export async function applySet(ctx, message, set, key, rawValue) {
|
||||
if (BOOL_SETTINGS.has(key)) {
|
||||
const bool = parseBool(rawValue);
|
||||
if (bool === null) {
|
||||
return ctx.t(message, "responses.settings.mustBeBool", { setting: key });
|
||||
}
|
||||
set.set(key, bool);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (key === "volume") {
|
||||
const num = parseInt(rawValue, 10);
|
||||
if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) {
|
||||
return ctx.t(message, "responses.settings.volumeRange");
|
||||
}
|
||||
set.set(key, num);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (key === "locale") {
|
||||
if (!VALID_LOCALES.has(rawValue)) {
|
||||
return ctx.t(message, "responses.settings.invalidLocale", {
|
||||
locale: rawValue,
|
||||
locales: [...VALID_LOCALES].map(l => "`" + l + "`").join(", ")
|
||||
});
|
||||
}
|
||||
set.set(key, rawValue);
|
||||
const gid = getMessageGuildId(message);
|
||||
if (gid) ctx.locale.invalidateCache(gid);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (key === "prefix") {
|
||||
if (!rawValue || rawValue.length > PREFIX_MAX) {
|
||||
return ctx.t(message, "responses.settings.prefixLength");
|
||||
}
|
||||
if (/\s/.test(rawValue)) {
|
||||
return ctx.t(message, "responses.settings.prefixSpaces");
|
||||
}
|
||||
}
|
||||
|
||||
if (runnables[key]) {
|
||||
const err = runnables[key].call(ctx, rawValue, { msg: message });
|
||||
if (err) return "\u274c " + err;
|
||||
}
|
||||
|
||||
set.set(key, rawValue);
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* @private
|
||||
* @async
|
||||
* Handle a settings shortcut command (e.g. `prefix`, `247`).
|
||||
* Dispatches to 24/7 toggle, value display, or value set depending on arguments.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {object} message - The command message.
|
||||
* @param {string} settingKey - The resolved setting key.
|
||||
* @param {string[]} valueTokens - Remaining argument tokens after the shortcut alias.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
||||
const set = ctx.getSettings(message);
|
||||
const guildId = getMessageGuildId(message);
|
||||
const t247 = ctx.locale?.translate?.bind(ctx.locale);
|
||||
|
||||
if (valueTokens.length === 0) {
|
||||
if (settingKey === "stay_247") {
|
||||
return handle247Toggle(ctx, message, set, guildId);
|
||||
}
|
||||
const val = set.get(settingKey);
|
||||
const label = prettifySettingLabel(settingKey, t247, guildId);
|
||||
return message.reply(embed("**" + label + "**\nValue: " + displayValue(settingKey, val)));
|
||||
}
|
||||
|
||||
const rawValue = valueTokens.join(" ");
|
||||
|
||||
if (settingKey === "stay_247") {
|
||||
const mode = rawValue.toLowerCase().trim();
|
||||
if (mode === "off" || mode === "false" || mode === "disable" || mode === "0") {
|
||||
const loc = tWrap(ctx, guildId);
|
||||
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
|
||||
const { channelId } = await ctx.players.checkVoiceChannels(message);
|
||||
if (channelId) {
|
||||
await disable247(ctx, set, guildId, channelId);
|
||||
return message.reply(build247Panel(set, ctx, guildId, cleanId(channelId)));
|
||||
}
|
||||
for (const [chId, player] of [...ctx.players.playerMap.entries()]) {
|
||||
if (cleanId(player?._guildId ?? "") === cleanId(guildId)) {
|
||||
const activeId = cleanId(player._channelId ?? chId);
|
||||
ctx.markIntentionalLeave?.(activeId);
|
||||
ctx.players.playerMap.delete(activeId);
|
||||
if (activeId !== chId) ctx.players.playerMap.delete(chId);
|
||||
await player.leave().catch(() => {});
|
||||
player.destroy();
|
||||
}
|
||||
}
|
||||
save247Channels(set, new Set());
|
||||
return message.reply(build247Panel(set, ctx, guildId, null));
|
||||
}
|
||||
return handle247Toggle(ctx, message, set, guildId);
|
||||
}
|
||||
|
||||
const err = await applySet(ctx, message, set, settingKey, rawValue);
|
||||
if (err) return message.reply(embed(err));
|
||||
|
||||
const val = set.get(settingKey);
|
||||
const label = prettifySettingLabel(settingKey, t247, guildId);
|
||||
return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label, value: displayValue(settingKey, val) })));
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* @module commands/settings/utils
|
||||
* @description Constants and pure helpers
|
||||
* shared by the settings command modules. Bodies are verbatim from the
|
||||
* original single-file command; `export ` prefixes and setValidLocales()
|
||||
* are the only additions.
|
||||
*/
|
||||
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor, cleanId } from "../../src/ui/index.mjs";
|
||||
|
||||
/**
|
||||
* Command alias to setting key mapping.
|
||||
* @type {Object.<string, string>}
|
||||
*/
|
||||
export const SHORTCUTS = {
|
||||
prefix: "prefix",
|
||||
pfx: "prefix",
|
||||
"247": "stay_247",
|
||||
};
|
||||
|
||||
/** @private @type {Set<string>} Strings that evaluate to boolean true. */
|
||||
const BOOL_TRUE = new Set(["true", "1", "yes", "on", "enable", "enabled"]);
|
||||
/** @private @type {Set<string>} Strings that evaluate to boolean false. */
|
||||
const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]);
|
||||
/** @private @type {Set<string>} Setting keys that use boolean display formatting. */
|
||||
export const BOOL_SETTINGS = new Set(["songAnnouncements"]);
|
||||
|
||||
/** @private @type {Set<string>} Available locale codes, populated at load time. */
|
||||
export let VALID_LOCALES = new Set(["en"]);
|
||||
|
||||
/** @private @type {number} Minimum allowed volume value. */
|
||||
export const VOLUME_MIN = 1;
|
||||
/** @private @type {number} Maximum allowed volume value. */
|
||||
export const VOLUME_MAX = 200;
|
||||
/** @private @type {number} Maximum prefix length in characters. */
|
||||
export const PREFIX_MAX = 5;
|
||||
/** @private @type {number} Maximum number of 24/7 channels per guild. */
|
||||
export const MAX_247_CHANNELS = 1;
|
||||
|
||||
/**
|
||||
* Replace the set of known locale codes (called by the settings command
|
||||
* factory at load time). Importers read VALID_LOCALES as a live binding,
|
||||
* so this stays behavior-identical to the original module-level assignment.
|
||||
* @param {Iterable<string>} locales
|
||||
*/
|
||||
export function setValidLocales(locales) {
|
||||
VALID_LOCALES = locales;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check whether a string looks like a valid Fluxer ID (Snowflake-like).
|
||||
* @param {string} id - The ID to validate.
|
||||
* @returns {boolean} True if the ID is 15-22 characters after cleaning.
|
||||
*/
|
||||
export function isValidFluxerId(id) {
|
||||
const cleaned = cleanId(id);
|
||||
return cleaned.length >= 15 && cleaned.length <= 22;
|
||||
}
|
||||
/**
|
||||
* Parse a string into a boolean, or return null if unrecognised.
|
||||
* @param {string} str - The string to parse.
|
||||
* @returns {boolean|null} True, false, or null if not a boolean string.
|
||||
*/
|
||||
export function parseBool(str) {
|
||||
const s = String(str).toLowerCase().trim();
|
||||
if (BOOL_TRUE.has(s)) return true;
|
||||
if (BOOL_FALSE.has(s)) return false;
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Format a setting value for display in embed messages.
|
||||
* @param {string} key - The setting key.
|
||||
* @param {*} value - The setting value.
|
||||
* @returns {string} Formatted display string.
|
||||
*/
|
||||
export function displayValue(key, value) {
|
||||
if (BOOL_SETTINGS.has(key)) return value ? "\u2705 enabled" : "\u274c disabled";
|
||||
if (value === null || value === undefined || value === "none") return "none";
|
||||
return "`" + value + "`";
|
||||
}
|
||||
/**
|
||||
* @private
|
||||
* Get the display name of the guild from a message object.
|
||||
* @param {object} message - The command message wrapper.
|
||||
* @returns {string} The guild name, or a fallback string.
|
||||
*/
|
||||
export function getGuildName(message) {
|
||||
return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server";
|
||||
}
|
||||
/**
|
||||
* @private
|
||||
* Create a simple embed payload with global color, description, and optional title/footer.
|
||||
* @param {string} desc - The embed description text.
|
||||
* @param {object} [opts={}] - Optional overrides for title, iconURL, and footer.
|
||||
* @returns {object} Embed payload for message.reply().
|
||||
*/
|
||||
export function embed(desc, opts = {}) {
|
||||
const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
|
||||
if (opts.title) b.setTitle(opts.title);
|
||||
if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL });
|
||||
if (opts.footer) b.setFooter({ text: opts.footer });
|
||||
return { embeds: [b] };
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Create a translation function bound to the given context and guild.
|
||||
* @param {object} ctx - The bot (Remix) context.
|
||||
* @param {string} guildId - The guild ID for localization.
|
||||
* @returns {Function} A translation function with signature (key, data?) => string.
|
||||
*/
|
||||
export function tWrap(ctx, guildId) {
|
||||
const tFn = ctx.locale?.translate?.bind(ctx.locale);
|
||||
return (key, data = {}) => tFn ? tFn(guildId, key, data) : key;
|
||||
}
|
||||
/**
|
||||
* @private
|
||||
* Get a human-readable label for a setting key, using locale translations when available.
|
||||
* @param {string} key - The setting key.
|
||||
* @param {Function|null} t - Translation function (guildId, key, data) => string.
|
||||
* @param {string} guildId - The guild ID for localization.
|
||||
* @returns {string} The pretty-printed setting label.
|
||||
*/
|
||||
export function prettifySettingLabel(key, t, guildId) {
|
||||
const localeMap = {
|
||||
songAnnouncements: "responses.settings.labelSongAnnouncements",
|
||||
prefix: "responses.settings.labelPrefix",
|
||||
pfx: "responses.settings.labelPfp",
|
||||
locale: "responses.settings.labelLocale",
|
||||
stay_247: "responses.settings.label247",
|
||||
volume: "responses.settings.labelVolume",
|
||||
};
|
||||
if (localeMap[key] && t && guildId) return t(guildId, localeMap[key]);
|
||||
const fallback = {
|
||||
songAnnouncements: "Song announcements",
|
||||
prefix: "Prefix",
|
||||
pfp: "Bot avatar style",
|
||||
locale: "Locale",
|
||||
stay_247: "24/7 mode",
|
||||
volume: "Default volume",
|
||||
};
|
||||
return fallback[key] ?? key.replace(/_/g, " ");
|
||||
}
|
||||
@@ -3,9 +3,9 @@
|
||||
* @description Randomly re-order the tracks in the playback queue.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/**
|
||||
* @type {CommandBuilder}
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@
|
||||
* @description Skip the currently playing track.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the skip command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+45
-5
@@ -5,11 +5,11 @@
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { Utils } from "../src/utils/Utils.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* @type {CommandBuilder}
|
||||
@@ -33,6 +33,9 @@ const RATE_LIMIT_MAX_RETRIES = 2;
|
||||
const RATE_LIMIT_MAX_WAIT_MS = 15_000;
|
||||
/** Where the warm cache is persisted (cwd-relative, same convention as ./storage/defaults.json). */
|
||||
const CACHE_FILE = path.join(process.cwd(), "storage", "stats-cache.json");
|
||||
/** Last-resort label for the gateway line when locale files lack the key
|
||||
* (customized deployments keep their own locale files across updates). */
|
||||
const GATEWAY_FALLBACK_LABEL = "\u{1F310} **Gateway**";
|
||||
|
||||
let cache = { guilds: null, users: null, scrobbles: null, linkedUsers: null, updatedAt: 0 };
|
||||
let lastPing = null;
|
||||
@@ -180,6 +183,23 @@ function withBudget(promise, ms, fallback) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the gateway heartbeat ACK latency from the WebSocket manager
|
||||
* (`client.ws.ping`). Returns -1 when unavailable (not logged in yet, or
|
||||
* no heartbeat ACK received yet).
|
||||
* @private
|
||||
* @param {object} client - The client instance.
|
||||
* @returns {number} Gateway latency in ms, or -1.
|
||||
*/
|
||||
function readGatewayPing(client) {
|
||||
try {
|
||||
const ping = client?.ws?.ping;
|
||||
return typeof ping === "number" && Number.isFinite(ping) ? ping : -1;
|
||||
} catch (_) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a message send/edit action, transparently retrying when the REST
|
||||
* library throws a 429 RateLimitError. Waits exactly as long as the API
|
||||
@@ -236,6 +256,22 @@ function getLivePlayerCount(playerMap) {
|
||||
return live;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate with a hardcoded fallback. Locale lookups that miss (custom or
|
||||
* outdated locale files make translate() return the raw dot-notation key)
|
||||
* render the readable fallback instead of an ugly key path in the embed.
|
||||
* @private
|
||||
* @param {Function} t - Translation function.
|
||||
* @param {object} msg - The command message wrapper.
|
||||
* @param {string} key - Locale key.
|
||||
* @param {string} fallback - Label used when the key is missing.
|
||||
* @returns {string}
|
||||
*/
|
||||
function tOr(t, msg, key, fallback) {
|
||||
const value = t(msg, key);
|
||||
return value === key ? fallback : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the stats embed with all bot information.
|
||||
* @private
|
||||
@@ -247,7 +283,8 @@ function getLivePlayerCount(playerMap) {
|
||||
* @param {number} s.playerCount - Number of active players.
|
||||
* @param {number} s.scrobbleCount - Total Last.fm scrobbles.
|
||||
* @param {number} s.linkedUsers - Number of Last.fm linked users.
|
||||
* @param {number} s.ping - Bot response ping in ms.
|
||||
* @param {number} s.ping - Bot response ping in ms (REST reply round trip).
|
||||
* @param {number} s.gatewayPing - Gateway heartbeat ACK latency in ms (-1 if unknown).
|
||||
* @param {string} s.uptime - Formatted uptime string.
|
||||
* @param {string} s.comHash - Git commit hash.
|
||||
* @param {string} s.comLink - Git commit link URL.
|
||||
@@ -276,6 +313,7 @@ function buildEmbed(t, msg, s, pending = []) {
|
||||
|
||||
description.push(
|
||||
`${t(msg, "responses.stats.ping")} — ${field("ping", `${num(s.ping)}ms`)}`,
|
||||
s.gatewayPing >= 0 ? `${tOr(t, msg, "responses.stats.gateway", GATEWAY_FALLBACK_LABEL)} — \`${num(s.gatewayPing)}ms\`` : null,
|
||||
`${t(msg, "responses.stats.uptime")} — \`${s.uptime}\``,
|
||||
`${t(msg, "responses.stats.build")} — [\`${s.comHash}\`](${s.comLink})`,
|
||||
s.reason ? `${t(msg, "responses.stats.lastRestart")} — \`${s.reason}\`` : null,
|
||||
@@ -330,6 +368,7 @@ export async function run(message) {
|
||||
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
||||
lastfmEnabled,
|
||||
ping: lastPing ?? 0,
|
||||
gatewayPing: readGatewayPing(this.client),
|
||||
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
|
||||
comHash: this.comHash,
|
||||
comLink: this.comLink,
|
||||
@@ -374,6 +413,7 @@ export async function run(message) {
|
||||
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
|
||||
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
||||
ping: lastPing ?? 0,
|
||||
gatewayPing: readGatewayPing(this.client),
|
||||
};
|
||||
|
||||
const stillPending = [];
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
* @description Displays a link and invitation to the bot's support server.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the support command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+3
-3
@@ -3,10 +3,10 @@
|
||||
* @description Owner-only diagnostic command to display voice channel user counts.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the test command (owner-only). */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
* @description Display the thumbnail artwork of the currently playing track.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the thumbnail command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
* @description Set custom start/end times for tracks with named alias support.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { ERROR_COLOR } from "../src/constants/UI.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { Utils } from "../src/utils/Utils.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||
|
||||
/** @private @type {string} The default alias name for non-named track options. */
|
||||
const DEFAULT_ALIAS = "default";
|
||||
|
||||
+3
-3
@@ -3,10 +3,10 @@
|
||||
* @description Get or change the playback volume for the current voice channel.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { MAX_VOLUME } from "../src/constants/UI.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { MAX_VOLUME } from "../src/utils/UI.mjs";
|
||||
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
* @description View or set the server default volume. Requires Manage Server permission to set.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { PermissionFlags } from "@fluxerjs/core";
|
||||
import { MAX_VOLUME } from "../src/constants/UI.mjs";
|
||||
import { MAX_VOLUME } from "../src/utils/UI.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the volumedefault command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
+6
-6
@@ -3,13 +3,13 @@
|
||||
* @description View voting info, check voters, or browse voter lists for a server/bot on FluxerList.
|
||||
*/
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
import { FLUXERLIST, buildVoteLink } from "../src/constants/API.mjs";
|
||||
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||
import { Utils } from "../src/utils/Utils.mjs";
|
||||
import { FLUXERLIST, buildVoteLink } from "../src/utils/API.mjs";
|
||||
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||
import { logger } from "../src/core/Logger.mjs";
|
||||
|
||||
/** @type {CommandBuilder} @description Command definition for the vote command. */
|
||||
export const command = new CommandBuilder()
|
||||
|
||||
Reference in new issue
Block a user