mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
refactor: centralize shared utilities, fix voice intent, and improve error visibility
- extract `cleanId()` to `Utils.mjs` and remove 97+ inline `String(x).replace(/\D/g, "")` duplicates
- add `VoiceStateResolver.mjs` with `iterateVoiceStates`, `hasHumansInChannel`, `getChannelsWithHumans` — eliminates 12+ duplicated voice-state-iteration blocks across `Player`, `PlayerManager`, `GatewayHandler`, `Dashboard`
- add `UI.mjs` for shared color, emoji, and timeout constants
- move `parseInlineProvider` to `providers.mjs`, `getMessageGuildId` to `MessageHandler.mjs`
- fix `VoiceStateCache.removeGuild` and `TrackOptionsManager` cache deletion mutating Maps during iteration
- fix `checkVoiceChannels` now async returning `{channelId, alreadyInVoice, hasHumans}` — all callers updated
- fix `FluxerRevoice` global `console.log` monkey-patch replaced with scoped `withSuppressedLiveKitLogs(fn)`
- fix `Player._get247Mode()` settings resolution chain
- fix `runnables.mjs` validators were no-ops
- promote `Player` magic numbers to named static constants
- replace all silent `catch (_) {}` with `logger.warn()` throughout
- remove unused deps: `express`, `genius-lyrics`, `ws`
- add `@file` JSDoc headers to all modules
This commit is contained in:
1 parent
0d3035b093
commit
092268281a
67 files changed
+2520
-2179
No files matched your search
+12
-2
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file autoplay command — Toggle autoplay to automatically play similar tracks when the queue ends
|
||||||
|
* @module commands/autoplay
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -8,6 +13,12 @@ export const command = new CommandBuilder()
|
|||||||
.setCategory("music")
|
.setCategory("music")
|
||||||
.addAliases("ap");
|
.addAliases("ap");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the autoplay command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const p = await this.getPlayer(msg, true, true, false);
|
const p = await this.getPlayer(msg, true, true, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -39,8 +50,7 @@ export async function run(msg, data) {
|
|||||||
const pick = similar[Math.floor(Math.random() * Math.min(3, similar.length))];
|
const pick = similar[Math.floor(Math.random() * Math.min(3, similar.length))];
|
||||||
query = `${pick.name} ${pick.artist}`.trim();
|
query = `${pick.name} ${pick.artist}`.trim();
|
||||||
}
|
}
|
||||||
} catch (_) {
|
} catch(e) { }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!query) {
|
if (!query) {
|
||||||
|
|||||||
+12
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file clear command — Remove all songs from the queue
|
||||||
|
* @module commands/clear
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -8,6 +13,12 @@ export const command = new CommandBuilder()
|
|||||||
.addAliases("c")
|
.addAliases("c")
|
||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the clear command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg) {
|
export async function run(msg) {
|
||||||
const p = await this.getPlayer(msg, false, false, false);
|
const p = await this.getPlayer(msg, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -16,5 +27,5 @@ export async function run(msg) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(msg, "responses.clear.cleared"))
|
.setDescription(this.t(msg, "responses.clear.cleared"))
|
||||||
;
|
;
|
||||||
msg.reply({ embeds: [embed] });
|
msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+75
-34
@@ -1,12 +1,24 @@
|
|||||||
|
/**
|
||||||
|
* @file debug command — Owner-only debug utilities for voice connections, ghost detection, and forced rejoins
|
||||||
|
* @module commands/debug
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
|
import { cleanId } from "../src/Utils.mjs";
|
||||||
import { getVoiceManager } from "@fluxerjs/voice";
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
|
import { ERROR_COLOR, WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR } from "../src/constants/UI.mjs";
|
||||||
|
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
const EMOJI_REMOVE_TIMEOUT = 60_000;
|
|
||||||
const REJOIN_DELAY_MS = 2_000;
|
const REJOIN_DELAY_MS = 2_000;
|
||||||
const INTENTIONAL_LEAVE_TTL = 30_000;
|
const INTENTIONAL_LEAVE_TTL = 30_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a human-readable label for a voice room's connection state.
|
||||||
|
* @param {object} room - The voice room instance
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
function roomStateLabel(room) {
|
function roomStateLabel(room) {
|
||||||
if (!room) return "none";
|
if (!room) return "none";
|
||||||
const cs = room.connectionState;
|
const cs = room.connectionState;
|
||||||
@@ -20,6 +32,12 @@ function roomStateLabel(room) {
|
|||||||
return String(cs);
|
return String(cs);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detect whether a player has a "ghost" connection — the player object exists
|
||||||
|
* but the underlying voice room is disconnected, reconnecting, or absent.
|
||||||
|
* @param {import("../src/Player.mjs").default} player
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
function isGhostConnection(player) {
|
function isGhostConnection(player) {
|
||||||
const conn = player.connection;
|
const conn = player.connection;
|
||||||
if (!conn) return false;
|
if (!conn) return false;
|
||||||
@@ -41,22 +59,28 @@ function isGhostConnection(player) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the bot's voice state from the gateway cache for a given guild.
|
||||||
|
* @param {object} client - The Discord client instance
|
||||||
|
* @param {string} guildId - The guild ID to look up
|
||||||
|
* @returns {{ userId: string, channelId: string } | null}
|
||||||
|
*/
|
||||||
function getBotGatewayVoiceState(client, guildId) {
|
function getBotGatewayVoiceState(client, guildId) {
|
||||||
const botId = client.user?.id;
|
const botId = client.user?.id;
|
||||||
if (!botId || !guildId) return null;
|
if (!botId || !guildId) return null;
|
||||||
try {
|
try {
|
||||||
const vm = getVoiceManager(client);
|
const vm = getVoiceManager(client);
|
||||||
if (vm?.voiceStates) {
|
if (vm?.voiceStates) {
|
||||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
const cleanGuild = cleanId(guildId);
|
||||||
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
|
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
|
||||||
if (guildVoiceMap && typeof guildVoiceMap.get === "function") {
|
if (guildVoiceMap && typeof guildVoiceMap.get === "function") {
|
||||||
const channelId = guildVoiceMap.get(botId);
|
const channelId = guildVoiceMap.get(botId);
|
||||||
if (channelId) return { userId: botId, channelId: String(channelId).replace(/\D/g, "") };
|
if (channelId) return { userId: botId, channelId: cleanId(channelId) };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
try {
|
try {
|
||||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
const cleanGuild = cleanId(guildId);
|
||||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
||||||
if (!voiceStates) return null;
|
if (!voiceStates) return null;
|
||||||
@@ -73,13 +97,18 @@ function getBotGatewayVoiceState(client, guildId) {
|
|||||||
const uid = state?.user_id ?? state?.userId ?? state?.id;
|
const uid = state?.user_id ?? state?.userId ?? state?.id;
|
||||||
if (uid === botId) {
|
if (uid === botId) {
|
||||||
const chId = state?.channel_id ?? state?.channelId ?? null;
|
const chId = state?.channel_id ?? state?.channelId ?? null;
|
||||||
if (chId) return { userId: botId, channelId: String(chId).replace(/\D/g, "") };
|
if (chId) return { userId: botId, channelId: cleanId(chId) };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether the gateway voice state is stale compared to the player's expected channel.
|
||||||
|
* @param {object} client - The Discord client instance
|
||||||
|
* @param {import("../src/Player.mjs").default} player
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
function isStaleGatewayPresence(client, player) {
|
function isStaleGatewayPresence(client, player) {
|
||||||
const guildId = player._guildId ?? player._resolveGuildId?.();
|
const guildId = player._guildId ?? player._resolveGuildId?.();
|
||||||
if (!guildId) return false;
|
if (!guildId) return false;
|
||||||
@@ -87,7 +116,7 @@ function isStaleGatewayPresence(client, player) {
|
|||||||
const gatewayState = getBotGatewayVoiceState(client, guildId);
|
const gatewayState = getBotGatewayVoiceState(client, guildId);
|
||||||
if (!gatewayState) return false;
|
if (!gatewayState) return false;
|
||||||
|
|
||||||
const playerChannel = String(player._channelId ?? player._home247Channel ?? "").replace(/\D/g, "");
|
const playerChannel = cleanId(player._channelId ?? player._home247Channel);
|
||||||
const gatewayChannel = gatewayState.channelId;
|
const gatewayChannel = gatewayState.channelId;
|
||||||
|
|
||||||
if (!playerChannel) return true;
|
if (!playerChannel) return true;
|
||||||
@@ -96,13 +125,19 @@ function isStaleGatewayPresence(client, player) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Destroy a player's stale connection and respawn a fresh player, restoring queue and playback.
|
||||||
|
* @param {object} ctx - The bot context (this)
|
||||||
|
* @param {import("../src/Player.mjs").default} player
|
||||||
|
* @returns {Promise<{ success: boolean, reason?: string, channelId?: string, roomConnected?: boolean, roomState?: string, resumedPlayback?: boolean }>}
|
||||||
|
*/
|
||||||
async function forceRejoinPlayer(ctx, player) {
|
async function forceRejoinPlayer(ctx, player) {
|
||||||
const channelId = player._channelId ?? player._home247Channel;
|
const channelId = player._channelId ?? player._home247Channel;
|
||||||
const guildId = player._guildId ?? player._resolveGuildId?.();
|
const guildId = player._guildId ?? player._resolveGuildId?.();
|
||||||
if (!channelId || !guildId) return { success: false, reason: "no channel or guild id" };
|
if (!channelId || !guildId) return { success: false, reason: "no channel or guild id" };
|
||||||
|
|
||||||
const cleanChannelId = String(channelId).replace(/\D/g, "");
|
const cleanChannelId = cleanId(channelId);
|
||||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
|
||||||
const currentTrack = player.queue?.getCurrent();
|
const currentTrack = player.queue?.getCurrent();
|
||||||
const queueTracks = player.queue?.data ? [...player.queue.data] : [];
|
const queueTracks = player.queue?.data ? [...player.queue.data] : [];
|
||||||
@@ -118,7 +153,7 @@ async function forceRejoinPlayer(ctx, player) {
|
|||||||
|
|
||||||
const altIds = [player._channelId, player._home247Channel]
|
const altIds = [player._channelId, player._home247Channel]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.map(id => String(id).replace(/\D/g, ""))
|
.map(id => cleanId(id))
|
||||||
.filter(id => id !== cleanChannelId);
|
.filter(id => id !== cleanChannelId);
|
||||||
for (const altId of altIds) {
|
for (const altId of altIds) {
|
||||||
ctx.players.playerMap.delete(altId);
|
ctx.players.playerMap.delete(altId);
|
||||||
@@ -135,16 +170,16 @@ async function forceRejoinPlayer(ctx, player) {
|
|||||||
|
|
||||||
const revoiceConn = ctx.revoice?.connections?.get(cleanChannelId);
|
const revoiceConn = ctx.revoice?.connections?.get(cleanChannelId);
|
||||||
if (revoiceConn) {
|
if (revoiceConn) {
|
||||||
try { await ctx.revoice._destroyStaleConnection(cleanChannelId, revoiceConn); } catch (_) {}
|
try { await ctx.revoice._destroyStaleConnection(cleanChannelId, revoiceConn); } catch(e) { }
|
||||||
} else if (player.connection) {
|
} else if (player.connection) {
|
||||||
try { player.connection.removeAllListeners(); } catch (_) {}
|
try { player.connection.removeAllListeners(); } catch(e) { }
|
||||||
try { ctx.revoice?._leaveGateway?.(cleanChannelId, cleanGuildId); } catch (_) {}
|
try { ctx.revoice?._leaveGateway?.(cleanChannelId, cleanGuildId); } catch(e) { }
|
||||||
try { ctx.revoice?.deleteConnection?.(cleanChannelId); } catch (_) {}
|
try { ctx.revoice?.deleteConnection?.(cleanChannelId); } catch(e) { }
|
||||||
try { await player.connection.disconnect(); } catch (_) {}
|
try { await player.connection.disconnect(); } catch(e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
try { await player.leave(); } catch (_) {}
|
try { await player.leave(); } catch(e) { }
|
||||||
try { player.destroy(); } catch (_) {}
|
try { player.destroy(); } catch(e) { }
|
||||||
|
|
||||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||||
|
|
||||||
@@ -160,7 +195,7 @@ async function forceRejoinPlayer(ctx, player) {
|
|||||||
newPlayer.queue.current = null;
|
newPlayer.queue.current = null;
|
||||||
await newPlayer.playNext();
|
await newPlayer.playNext();
|
||||||
if (wasPaused) newPlayer.pause();
|
if (wasPaused) newPlayer.pause();
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (wasAutoplay) newPlayer._autoplay = true;
|
if (wasAutoplay) newPlayer._autoplay = true;
|
||||||
@@ -189,6 +224,12 @@ export const command = new CommandBuilder()
|
|||||||
.addChoices("voice", "voice-rejoin", "247-rejoin")
|
.addChoices("voice", "voice-rejoin", "247-rejoin")
|
||||||
.setRequired(true));
|
.setRequired(true));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the debug command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
switch (data.get("target").value) {
|
switch (data.get("target").value) {
|
||||||
case "247-rejoin": {
|
case "247-rejoin": {
|
||||||
@@ -197,7 +238,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (channels247.length === 0) {
|
if (channels247.length === 0) {
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(0xFFAA00)
|
.setColor(WARN_COLOR)
|
||||||
.setTitle("Debug — 24/7 Rejoin")
|
.setTitle("Debug — 24/7 Rejoin")
|
||||||
.setDescription("No 24/7 channels found in the player map.")
|
.setDescription("No 24/7 channels found in the player map.")
|
||||||
;
|
;
|
||||||
@@ -214,7 +255,7 @@ export async function run(msg, data) {
|
|||||||
const [cid, player] = channels247[i];
|
const [cid, player] = channels247[i];
|
||||||
const channel = this.client.channels.get(cid);
|
const channel = this.client.channels.get(cid);
|
||||||
const gId = player._guildId ?? channel?.guildId;
|
const gId = player._guildId ?? channel?.guildId;
|
||||||
const guild = gId ? this.client.guilds.get(String(gId).replace(/\D/g, "")) : null;
|
const guild = gId ? this.client.guilds.get(cleanId(gId)) : null;
|
||||||
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
||||||
const ghost = isGhostConnection(player) ? " 👻GHOST" : "";
|
const ghost = isGhostConnection(player) ? " 👻GHOST" : "";
|
||||||
const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none";
|
const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none";
|
||||||
@@ -223,7 +264,7 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const statusEmbed = new EmbedBuilder()
|
const statusEmbed = new EmbedBuilder()
|
||||||
.setColor(0xFFAA00)
|
.setColor(WARN_COLOR)
|
||||||
.setTitle("Debug — 24/7 Rejoin")
|
.setTitle("Debug — 24/7 Rejoin")
|
||||||
.setDescription(statusLines.join("\n").slice(0, 4096))
|
.setDescription(statusLines.join("\n").slice(0, 4096))
|
||||||
;
|
;
|
||||||
@@ -235,7 +276,7 @@ export async function run(msg, data) {
|
|||||||
const [cid, player] = channels247[i];
|
const [cid, player] = channels247[i];
|
||||||
const channel = this.client.channels.get(cid);
|
const channel = this.client.channels.get(cid);
|
||||||
const gId = player._guildId ?? channel?.guildId;
|
const gId = player._guildId ?? channel?.guildId;
|
||||||
const guild = gId ? this.client.guilds.get(String(gId).replace(/\D/g, "")) : null;
|
const guild = gId ? this.client.guilds.get(cleanId(gId)) : null;
|
||||||
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
||||||
|
|
||||||
const result = await forceRejoinPlayer(this, player);
|
const result = await forceRejoinPlayer(this, player);
|
||||||
@@ -274,7 +315,7 @@ export async function run(msg, data) {
|
|||||||
resultLines.push("", `⚠️ **${failedCount}** channel(s) could not be restored.`);
|
resultLines.push("", `⚠️ **${failedCount}** channel(s) could not be restored.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const finalColor = failedCount === 0 ? 0x00CC66 : 0xFF4444;
|
const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR;
|
||||||
const finalEmbed = new EmbedBuilder()
|
const finalEmbed = new EmbedBuilder()
|
||||||
.setColor(finalColor)
|
.setColor(finalColor)
|
||||||
.setTitle("Debug — 24/7 Rejoin")
|
.setTitle("Debug — 24/7 Rejoin")
|
||||||
@@ -296,7 +337,7 @@ export async function run(msg, data) {
|
|||||||
? `\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.`
|
? `\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()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(0x00CC66)
|
.setColor(SUCCESS_COLOR)
|
||||||
.setTitle("Debug — Voice Rejoin")
|
.setTitle("Debug — Voice Rejoin")
|
||||||
.setDescription(`No ghost connections found. All voice connections appear healthy.${hintLine}`)
|
.setDescription(`No ghost connections found. All voice connections appear healthy.${hintLine}`)
|
||||||
;
|
;
|
||||||
@@ -313,7 +354,7 @@ export async function run(msg, data) {
|
|||||||
const [cid, player] = ghostEntries[i];
|
const [cid, player] = ghostEntries[i];
|
||||||
const channel = this.client.channels.get(cid);
|
const channel = this.client.channels.get(cid);
|
||||||
const gId = player._guildId ?? channel?.guildId;
|
const gId = player._guildId ?? channel?.guildId;
|
||||||
const guild = gId ? this.client.guilds.get(String(gId).replace(/\D/g, "")) : null;
|
const guild = gId ? this.client.guilds.get(cleanId(gId)) : null;
|
||||||
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
||||||
const is247 = player._home247Channel ? "yes" : "no";
|
const is247 = player._home247Channel ? "yes" : "no";
|
||||||
const hasTrack = player.queue?.getCurrent() ? "yes" : "no";
|
const hasTrack = player.queue?.getCurrent() ? "yes" : "no";
|
||||||
@@ -321,7 +362,7 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const statusEmbed = new EmbedBuilder()
|
const statusEmbed = new EmbedBuilder()
|
||||||
.setColor(0xFFAA00)
|
.setColor(WARN_COLOR)
|
||||||
.setTitle("Debug — Voice Rejoin")
|
.setTitle("Debug — Voice Rejoin")
|
||||||
.setDescription(statusLines.join("\n").slice(0, 4096))
|
.setDescription(statusLines.join("\n").slice(0, 4096))
|
||||||
;
|
;
|
||||||
@@ -333,7 +374,7 @@ export async function run(msg, data) {
|
|||||||
const [cid, player] = ghostEntries[i];
|
const [cid, player] = ghostEntries[i];
|
||||||
const channel = this.client.channels.get(cid);
|
const channel = this.client.channels.get(cid);
|
||||||
const gId = player._guildId ?? channel?.guildId;
|
const gId = player._guildId ?? channel?.guildId;
|
||||||
const guild = gId ? this.client.guilds.get(String(gId).replace(/\D/g, "")) : null;
|
const guild = gId ? this.client.guilds.get(cleanId(gId)) : null;
|
||||||
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
||||||
|
|
||||||
const result = await forceRejoinPlayer(this, player);
|
const result = await forceRejoinPlayer(this, player);
|
||||||
@@ -372,7 +413,7 @@ export async function run(msg, data) {
|
|||||||
resultLines.push("", `⚠️ **${failedCount}** connection(s) could not be restored.`);
|
resultLines.push("", `⚠️ **${failedCount}** connection(s) could not be restored.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const finalColor = failedCount === 0 ? 0x00CC66 : 0xFF4444;
|
const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR;
|
||||||
const finalEmbed = new EmbedBuilder()
|
const finalEmbed = new EmbedBuilder()
|
||||||
.setColor(finalColor)
|
.setColor(finalColor)
|
||||||
.setTitle("Debug — Voice Rejoin")
|
.setTitle("Debug — Voice Rejoin")
|
||||||
@@ -388,7 +429,7 @@ export async function run(msg, data) {
|
|||||||
const servers = [...this.players.playerMap.entries()].map(([cid, s]) => {
|
const servers = [...this.players.playerMap.entries()].map(([cid, s]) => {
|
||||||
const channel = this.client.channels.get(cid);
|
const channel = this.client.channels.get(cid);
|
||||||
const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id;
|
const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id;
|
||||||
const guild = guildId ? this.client.guilds.get(String(guildId).replace(/\D/g, "")) : null;
|
const guild = guildId ? this.client.guilds.get(cleanId(guildId)) : null;
|
||||||
const conn = s.connection;
|
const conn = s.connection;
|
||||||
const room = conn?.room;
|
const room = conn?.room;
|
||||||
const ghost = isGhostConnection(s);
|
const ghost = isGhostConnection(s);
|
||||||
@@ -520,7 +561,7 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (pages.length === 1) {
|
if (pages.length === 1) {
|
||||||
const embedColor = ghostConnections.length > 0 ? 0xFF4444 : getGlobalColor();
|
const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor();
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(embedColor)
|
.setColor(embedColor)
|
||||||
.setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""))
|
.setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""))
|
||||||
@@ -540,7 +581,7 @@ export async function run(msg, data) {
|
|||||||
? this.t(msg, "responses._common.controlsExpired")
|
? this.t(msg, "responses._common.controlsExpired")
|
||||||
: `${this.t(msg, "responses.eval.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`;
|
: `${this.t(msg, "responses.eval.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`;
|
||||||
|
|
||||||
const embedColor = (pageIdx === 0 && ghostConnections.length > 0) ? 0xFF4444 : getGlobalColor();
|
const embedColor = (pageIdx === 0 && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor();
|
||||||
const titleSuffix = (pageIdx === 0 && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "";
|
const titleSuffix = (pageIdx === 0 && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "";
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
@@ -565,7 +606,7 @@ export async function run(msg, data) {
|
|||||||
await replyMsg.message.removeAllReactions();
|
await replyMsg.message.removeAllReactions();
|
||||||
} catch {
|
} catch {
|
||||||
for (const emoji of navEmojis) {
|
for (const emoji of navEmojis) {
|
||||||
try { await replyMsg.message.removeReaction(emoji); } catch {}
|
try { await replyMsg.message.removeReaction(emoji); } catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
+39
-4
@@ -1,9 +1,14 @@
|
|||||||
|
/**
|
||||||
|
* @file eval command — Owner-only JavaScript code evaluation with sensitive-data redaction
|
||||||
|
* @module commands/eval
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { inspect } from "node:util";
|
import { inspect } from "node:util";
|
||||||
|
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
const EMOJI_REMOVE_TIMEOUT = 60000;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Matches any key that *contains* one of these strings (case-insensitive).
|
* Matches any key that *contains* one of these strings (case-insensitive).
|
||||||
@@ -27,6 +32,13 @@ const RESTRICTED = [
|
|||||||
|
|
||||||
const SCAN_DEPTH = 6;
|
const SCAN_DEPTH = 6;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether an object contains sensitive keys at any nesting level.
|
||||||
|
* @param {object} obj - The object to scan
|
||||||
|
* @param {number} [level=0] - Current recursion depth
|
||||||
|
* @param {WeakSet} [visited=new WeakSet()] - Visited object tracker
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
function hasSensitive(obj, level = 0, visited = new WeakSet()) {
|
function hasSensitive(obj, level = 0, visited = new WeakSet()) {
|
||||||
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return false;
|
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return false;
|
||||||
if (visited.has(obj)) return false;
|
if (visited.has(obj)) return false;
|
||||||
@@ -38,6 +50,13 @@ function hasSensitive(obj, level = 0, visited = new WeakSet()) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recursively redact sensitive keys from an object, replacing values with "[REDACTED]".
|
||||||
|
* @param {object} obj - The object to scrub
|
||||||
|
* @param {number} [level=0] - Current recursion depth
|
||||||
|
* @param {WeakSet} [visited=new WeakSet()] - Visited object tracker
|
||||||
|
* @returns {object} The scrubbed object (or the original if no changes were needed)
|
||||||
|
*/
|
||||||
function removeSensitive(obj, level = 0, visited = new WeakSet()) {
|
function removeSensitive(obj, level = 0, visited = new WeakSet()) {
|
||||||
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return obj;
|
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return obj;
|
||||||
if (visited.has(obj)) return "[Circular]";
|
if (visited.has(obj)) return "[Circular]";
|
||||||
@@ -64,6 +83,11 @@ function removeSensitive(obj, level = 0, visited = new WeakSet()) {
|
|||||||
return modified ? newObj : obj;
|
return modified ? newObj : obj;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Await a value if it is a Promise, then redact sensitive data and format for display.
|
||||||
|
* @param {*} value - The value to clean and format
|
||||||
|
* @returns {Promise<string>} Formatted, safe string representation
|
||||||
|
*/
|
||||||
async function clean(value) {
|
async function clean(value) {
|
||||||
if (value instanceof Promise) value = await value;
|
if (value instanceof Promise) value = await value;
|
||||||
|
|
||||||
@@ -85,6 +109,11 @@ async function clean(value) {
|
|||||||
.replace(/@/g, "@\u200b") || "undefined";
|
.replace(/@/g, "@\u200b") || "undefined";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine whether a code string is a single expression (no semicolons, blocks, or declarations).
|
||||||
|
* @param {string} code - The code to inspect
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
function isSingleExpression(code) {
|
function isSingleExpression(code) {
|
||||||
const trimmed = code.trim();
|
const trimmed = code.trim();
|
||||||
|
|
||||||
@@ -144,6 +173,12 @@ export const command = new CommandBuilder()
|
|||||||
.setRequired(true)
|
.setRequired(true)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the eval command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const expression = data.get("expression").value;
|
const expression = data.get("expression").value;
|
||||||
|
|
||||||
@@ -183,7 +218,7 @@ export async function run(msg, data) {
|
|||||||
else footerText += " " + this.t(msg, "responses.eval.deleteHint");
|
else footerText += " " + this.t(msg, "responses.eval.deleteHint");
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(isError ? "#ff0000" : getGlobalColor())
|
.setColor(isError ? ERROR_COLOR : getGlobalColor())
|
||||||
.setTitle(title)
|
.setTitle(title)
|
||||||
.setDescription(desc)
|
.setDescription(desc)
|
||||||
.setFooter({ text: footerText })
|
.setFooter({ text: footerText })
|
||||||
@@ -210,7 +245,7 @@ export async function run(msg, data) {
|
|||||||
for (const emoji of navEmojis) {
|
for (const emoji of navEmojis) {
|
||||||
try {
|
try {
|
||||||
await replyMsg.message.removeReaction(emoji);
|
await replyMsg.message.removeReaction(emoji);
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -244,4 +279,4 @@ export async function run(msg, data) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
resetTimer();
|
resetTimer();
|
||||||
}
|
}
|
||||||
+27
-8
@@ -1,7 +1,15 @@
|
|||||||
|
/**
|
||||||
|
* @file filter command — Interactive audio filter picker with emoji-based toggling
|
||||||
|
* @module commands/filter
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/Utils.mjs";
|
||||||
|
import { PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
|
const NAV_EMOJIS = [PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI];
|
||||||
|
|
||||||
const FILTERS = [
|
const FILTERS = [
|
||||||
{
|
{
|
||||||
@@ -160,10 +168,6 @@ const FILTERS = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
const PAGE_SIZE = 9;
|
const PAGE_SIZE = 9;
|
||||||
const PREV_EMOJI = "⬅️";
|
|
||||||
const NEXT_EMOJI = "➡️";
|
|
||||||
const CANCEL_EMOJI = "❌";
|
|
||||||
const NAV_EMOJIS = [PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI];
|
|
||||||
|
|
||||||
const SESSION_MS = 60_000;
|
const SESSION_MS = 60_000;
|
||||||
|
|
||||||
@@ -195,6 +199,15 @@ export const command = new CommandBuilder()
|
|||||||
.setCategory("music")
|
.setCategory("music")
|
||||||
.addAliases("filters", "fx", "effect");
|
.addAliases("filters", "fx", "effect");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the embed for a single page of the filter picker.
|
||||||
|
* @param {Function} t - Translation function
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {number} page - Current page index (0-based)
|
||||||
|
* @param {string[]} activeKeys - Currently active filter keys
|
||||||
|
* @param {object} [current] - The currently playing track
|
||||||
|
* @returns {import("@fluxerjs/core").EmbedBuilder}
|
||||||
|
*/
|
||||||
function buildPageEmbed(t, msg, page, activeKeys, current) {
|
function buildPageEmbed(t, msg, page, activeKeys, current) {
|
||||||
const totalPages = Math.ceil(FILTERS.length / PAGE_SIZE);
|
const totalPages = Math.ceil(FILTERS.length / PAGE_SIZE);
|
||||||
const start = page * PAGE_SIZE;
|
const start = page * PAGE_SIZE;
|
||||||
@@ -238,6 +251,12 @@ function buildPageEmbed(t, msg, page, activeKeys, current) {
|
|||||||
;
|
;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the filter command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg) {
|
export async function run(msg) {
|
||||||
const player = await this.getPlayer(msg, false, false, false);
|
const player = await this.getPlayer(msg, false, false, false);
|
||||||
if (!player) return;
|
if (!player) return;
|
||||||
@@ -267,14 +286,14 @@ export async function run(msg) {
|
|||||||
try {
|
try {
|
||||||
await menuMsg.message.react(emoji);
|
await menuMsg.message.react(emoji);
|
||||||
await Utils.sleep(50);
|
await Utils.sleep(50);
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const removePageFilterEmojis = async (p) => {
|
const removePageFilterEmojis = async (p) => {
|
||||||
const pageEmojis = getPageItems(p).map(f => f.emoji);
|
const pageEmojis = getPageItems(p).map(f => f.emoji);
|
||||||
for (const emoji of pageEmojis) {
|
for (const emoji of pageEmojis) {
|
||||||
try { await menuMsg.message.removeReaction(emoji); } catch (_) {}
|
try { await menuMsg.message.removeReaction(emoji); } catch(e) { }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -288,7 +307,7 @@ export async function run(msg) {
|
|||||||
await menuMsg.message.removeAllReactions();
|
await menuMsg.message.removeAllReactions();
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
for (const emoji of [...FILTERS.map(f => f.emoji), ...NAV_EMOJIS]) {
|
for (const emoji of [...FILTERS.map(f => f.emoji), ...NAV_EMOJIS]) {
|
||||||
try { await menuMsg.message.removeReaction(emoji); } catch (_) {}
|
try { await menuMsg.message.removeReaction(emoji); } catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -442,4 +461,4 @@ export async function run(msg) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
resetTimer();
|
resetTimer();
|
||||||
}
|
}
|
||||||
+16
-13
@@ -1,6 +1,10 @@
|
|||||||
|
/**
|
||||||
|
* @file forceleave command — Force the bot to leave a voice channel (requires ManageChannels)
|
||||||
|
* @module commands/forceleave
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { cleanId } from "../src/MessageHandler.mjs";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("forceleave")
|
.setName("forceleave")
|
||||||
@@ -14,23 +18,22 @@ export const command = new CommandBuilder()
|
|||||||
.setRequired(true)
|
.setRequired(true)
|
||||||
);
|
);
|
||||||
|
|
||||||
function embed(desc) {
|
|
||||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] };
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanId(value) {
|
|
||||||
return String(value ?? "").replace(/\D/g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the forceleave command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const cid = cleanId(data.get("channelId").value);
|
const cid = cleanId(data.get("channelId").value);
|
||||||
const targetChannel = this.client.channels.get(cid);
|
const targetChannel = this.client.channels.get(cid);
|
||||||
if (!targetChannel) return msg.reply(embed(this.t(msg, "responses.forceleave.channelNotFound")));
|
if (!targetChannel) return msg.reply(this.t(msg, "responses.forceleave.channelNotFound"));
|
||||||
if (cleanId(msg.message?.guildId) !== cleanId(targetChannel.guildId))
|
if (cleanId(msg.message?.guildId) !== cleanId(targetChannel.guildId))
|
||||||
return msg.reply(embed(this.t(msg, "responses.forceleave.wrongServer")));
|
return msg.reply(this.t(msg, "responses.forceleave.wrongServer"));
|
||||||
const p = this.players.playerMap.get(cid)
|
const p = this.players.playerMap.get(cid)
|
||||||
?? [...this.players.playerMap.values()].find((player) => cleanId(player?._channelId) === cid);
|
?? [...this.players.playerMap.values()].find((player) => cleanId(player?._channelId) === cid);
|
||||||
if (!p) return msg.reply(embed(this.t(msg, "responses.forceleave.playerNotFound")));
|
if (!p) return msg.reply(this.t(msg, "responses.forceleave.playerNotFound"));
|
||||||
if (!p.connection) return msg.reply(embed(this.t(msg, "responses.forceleave.playerNotInit")));
|
if (!p.connection) return msg.reply(this.t(msg, "responses.forceleave.playerNotInit"));
|
||||||
await this.players.leave(msg, cid);
|
await this.players.leave(msg, cid);
|
||||||
}
|
}
|
||||||
+13
-2
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file invite command — Get the bot invite link and support server invite
|
||||||
|
* @module commands/invite
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -8,6 +13,12 @@ export const command = new CommandBuilder()
|
|||||||
.addAliases("addbot", "remix")
|
.addAliases("addbot", "remix")
|
||||||
.setCategory("util");
|
.setCategory("util");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the invite command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const description = this.t(message, "responses.invite.description");
|
const description = this.t(message, "responses.invite.description");
|
||||||
|
|
||||||
@@ -25,5 +36,5 @@ export async function run(message) {
|
|||||||
|
|
||||||
await message.reply({
|
await message.reply({
|
||||||
embeds: [embed]
|
embeds: [embed]
|
||||||
});
|
}).catch(() => {});
|
||||||
}
|
}
|
||||||
+29
-23
@@ -1,23 +1,23 @@
|
|||||||
|
/**
|
||||||
|
* @file join command — Make the bot join a voice channel and initialise a player
|
||||||
|
* @module commands/join
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/constants/Logger.mjs";
|
||||||
import Player from "../src/Player.mjs";
|
import Player from "../src/Player.mjs";
|
||||||
|
|
||||||
function getGuildId(message) {
|
|
||||||
return message?.channel?.guildId
|
|
||||||
?? message?.channel?.guild?.id
|
|
||||||
?? message?.message?.guildId
|
|
||||||
?? message?.message?.guild?.id
|
|
||||||
?? message?.channel?.server_id
|
|
||||||
?? message?.channel?.serverId
|
|
||||||
?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanId(value) {
|
|
||||||
return String(value ?? "").replace(/\D/g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Join a voice channel, create a Player, and register event listeners.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {string} cid - The voice channel ID to join
|
||||||
|
* @param {Function} [cb] - Callback invoked with the player on success
|
||||||
|
* @param {Function} [ecb] - Callback invoked on error
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
||||||
const cleanChannelId = cleanId(cid);
|
const cleanChannelId = cleanId(cid);
|
||||||
if (!this.client.channels.has(cleanChannelId)) {
|
if (!this.client.channels.has(cleanChannelId)) {
|
||||||
@@ -54,9 +54,9 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
p.on("autoleave", () => {
|
p.on("autoleave", () => {
|
||||||
const activeChannelId = String(p._channelId ?? cid).replace(/\D/g, "") || cid;
|
const activeChannelId = cleanId(p._channelId ?? cid) || cid;
|
||||||
const homeChannelId = String(p._home247Channel ?? activeChannelId).replace(/\D/g, "") || activeChannelId;
|
const homeChannelId = cleanId(p._home247Channel ?? activeChannelId) || activeChannelId;
|
||||||
const guildId = getGuildId(message);
|
const guildId = getMessageGuildId(message);
|
||||||
|
|
||||||
const is247 = (() => {
|
const is247 = (() => {
|
||||||
try {
|
try {
|
||||||
@@ -106,13 +106,13 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
p.on("message", m => {
|
p.on("message", m => {
|
||||||
const guildId = getGuildId(message);
|
const guildId = getMessageGuildId(message);
|
||||||
const raw = this.settingsMgr?.getServer?.(guildId)?.get("songAnnouncements");
|
const raw = this.settingsMgr?.getServer?.(guildId)?.get("songAnnouncements");
|
||||||
const disabled = raw === false || raw === 0 ||
|
const disabled = raw === false || raw === 0 ||
|
||||||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
|
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
|
||||||
if (disabled) return;
|
if (disabled) return;
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(m);
|
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(m);
|
||||||
message.channel.send({ embeds: [embed] });
|
message.channel.send({ embeds: [embed] }).catch(() => {});
|
||||||
});
|
});
|
||||||
|
|
||||||
this.players._pendingJoins.add(cleanChannelId);
|
this.players._pendingJoins.add(cleanChannelId);
|
||||||
@@ -147,6 +147,12 @@ export const command = new CommandBuilder()
|
|||||||
.setRequired(false)
|
.setRequired(false)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the join command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
|
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
|
||||||
|
|
||||||
@@ -160,7 +166,7 @@ export async function run(message, data) {
|
|||||||
} else if (idMatch) {
|
} else if (idMatch) {
|
||||||
resolvedId = idMatch[1];
|
resolvedId = idMatch[1];
|
||||||
} else {
|
} else {
|
||||||
const guildId = cleanId(getGuildId(message));
|
const guildId = cleanId(getMessageGuildId(message));
|
||||||
const allChannels = [
|
const allChannels = [
|
||||||
...(this.client?.channels?.values?.() ?? [])
|
...(this.client?.channels?.values?.() ?? [])
|
||||||
];
|
];
|
||||||
@@ -182,10 +188,10 @@ export async function run(message, data) {
|
|||||||
return this.players.initPlayer(message, resolvedId);
|
return this.players.initPlayer(message, resolvedId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const cid = this.players.checkVoiceChannels(message);
|
const { channelId: cid } = await this.players.checkVoiceChannels(message);
|
||||||
|
|
||||||
if (!cid) {
|
if (!cid) {
|
||||||
const prefix = this.handler.getPrefix(getGuildId(message));
|
const prefix = this.handler.getPrefix(getMessageGuildId(message));
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
||||||
.setDescription(this.t(message, "responses.join.noVoiceChannel", { prefix }));
|
.setDescription(this.t(message, "responses.join.noVoiceChannel", { prefix }));
|
||||||
return message.reply({ embeds: [embed] });
|
return message.reply({ embeds: [embed] });
|
||||||
@@ -197,4 +203,4 @@ export async function run(message, data) {
|
|||||||
export const exportDef = {
|
export const exportDef = {
|
||||||
name: "joinChannel",
|
name: "joinChannel",
|
||||||
object: joinChannel
|
object: joinChannel
|
||||||
};
|
};
|
||||||
+90
-78
@@ -1,10 +1,15 @@
|
|||||||
|
/**
|
||||||
|
* @file lastfm command — Link Last.fm accounts, scrobble, view profiles, leaderboards, and more
|
||||||
|
* @module commands/lastfm
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/Utils.mjs";
|
||||||
import { PROVIDER_CHOICES } from "../src/constants/providers.mjs";
|
import { PROVIDER_CHOICES } from "../src/constants/providers.mjs";
|
||||||
|
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
const EMOJI_REMOVE_TIMEOUT = 60_000;
|
|
||||||
|
|
||||||
const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"];
|
const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"];
|
||||||
|
|
||||||
@@ -46,7 +51,7 @@ export const command = new CommandBuilder()
|
|||||||
function notConfigured(ctx, msg) {
|
function notConfigured(ctx, msg) {
|
||||||
return {
|
return {
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor("#ff0000")
|
.setColor(ERROR_COLOR)
|
||||||
.setDescription(ctx.t(msg, "responses.lastfm.notConfigured"))]
|
.setDescription(ctx.t(msg, "responses.lastfm.notConfigured"))]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -113,7 +118,7 @@ async function getGuildLinkedUsers(guild) {
|
|||||||
if (userId && !m.user?.bot) memberIds.push(String(userId));
|
if (userId && !m.user?.bot) memberIds.push(String(userId));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch(e) { }
|
||||||
return memberIds;
|
return memberIds;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +147,8 @@ function extractPeriod(data, msg) {
|
|||||||
* Shared between `%lastfm play <cat>` and `%play lastfm:<cat>`.
|
* Shared between `%lastfm play <cat>` and `%play lastfm:<cat>`.
|
||||||
*
|
*
|
||||||
* @param {object} ctx - The command `this` context (has .lastfm, .getPlayer, .handler, .t)
|
* @param {object} ctx - The command `this` context (has .lastfm, .getPlayer, .handler, .t)
|
||||||
* @param {object} msg - The message object
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The message object
|
||||||
|
* @param {string} userId - The Discord user ID
|
||||||
* @param {string} category - "loved", "top", "recent", or "playlist"
|
* @param {string} category - "loved", "top", "recent", or "playlist"
|
||||||
* @param {object} [options]
|
* @param {object} [options]
|
||||||
* @param {string} [options.period] - Period for top tracks
|
* @param {string} [options.period] - Period for top tracks
|
||||||
@@ -161,7 +167,7 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
|||||||
const validCategories = [...SIMPLE_CATEGORIES, "playlist"];
|
const validCategories = [...SIMPLE_CATEGORIES, "playlist"];
|
||||||
if (!validCategories.includes(category)) {
|
if (!validCategories.includes(category)) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
`❌ Unknown category \`${category}\`. Use \`loved\`, \`top\`, \`recent\`, \`albums\`, \`artists\`, or \`playlist\`.`
|
`❌ Unknown category \`${category}\`. Use \`loved\`, \`top\`, \`recent\`, \`albums\`, \`artists\`, or \`playlist\`.`
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -169,7 +175,7 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
|||||||
|
|
||||||
if (category === "playlist" && !options.playlistId) {
|
if (category === "playlist" && !options.playlistId) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
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>\`.`
|
`❌ Specify a playlist number. Use \`${prefix}lastfm playlists\` to see your playlists, then \`${prefix}lastfm play playlist <number>\`.`
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -201,7 +207,7 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errMsg = err.message === "NOT_LINKED"
|
const errMsg = err.message === "NOT_LINKED"
|
||||||
? notLinked(ctx, msg, prefix)
|
? notLinked(ctx, msg, prefix)
|
||||||
: { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(ctx.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
: { 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));
|
if (statusMsg) statusMsg.edit(errMsg).catch(() => msg.reply(errMsg));
|
||||||
else msg.reply(errMsg);
|
else msg.reply(errMsg);
|
||||||
return;
|
return;
|
||||||
@@ -328,6 +334,12 @@ function parsePlayArgs(msg, data) {
|
|||||||
return { category: "" };
|
return { category: "" };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the lastfm command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const lastfm = this.lastfm;
|
const lastfm = this.lastfm;
|
||||||
if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(this, msg));
|
if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(this, msg));
|
||||||
@@ -353,7 +365,7 @@ export async function run(msg, data) {
|
|||||||
token = await lastfm.getAuthToken();
|
token = await lastfm.getAuthToken();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.tokenFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tokenFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -395,7 +407,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!tokenValue) {
|
if (!tokenValue) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.confirmUsage", { prefix }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmUsage", { prefix }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -404,7 +416,7 @@ export async function run(msg, data) {
|
|||||||
session = await lastfm.getSession(tokenValue);
|
session = await lastfm.getSession(tokenValue);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.confirmFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -453,7 +465,7 @@ export async function run(msg, data) {
|
|||||||
recentData = await lastfm.getRecentTracks(userId, 1);
|
recentData = await lastfm.getRecentTracks(userId, 1);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -484,7 +496,7 @@ export async function run(msg, data) {
|
|||||||
info = await lastfm.getUserInfo(profileUserId);
|
info = await lastfm.getUserInfo(profileUserId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -514,7 +526,7 @@ export async function run(msg, data) {
|
|||||||
playlists = await lastfm.getPlaylists(userId);
|
playlists = await lastfm.getPlaylists(userId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -546,7 +558,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (parsed.invalidCategory) {
|
if (parsed.invalidCategory) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
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}\``
|
`❌ \`${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}\``
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -557,7 +569,7 @@ export async function run(msg, data) {
|
|||||||
? `\n\n💡 \`${prefix}lastfm play ${parsed.resolveProvider}:<category>\` — Specify a category after the provider:`
|
? `\n\n💡 \`${prefix}lastfm play ${parsed.resolveProvider}:<category>\` — Specify a category after the provider:`
|
||||||
: "";
|
: "";
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription([
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([
|
||||||
`❌ Usage: \`${prefix}lastfm play <category>\``,
|
`❌ Usage: \`${prefix}lastfm play <category>\``,
|
||||||
``,
|
``,
|
||||||
`**Categories:**`,
|
`**Categories:**`,
|
||||||
@@ -607,7 +619,7 @@ export async function run(msg, data) {
|
|||||||
tracks = await lastfm.getLovedTracks(userId, 15);
|
tracks = await lastfm.getLovedTracks(userId, 15);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -631,7 +643,7 @@ export async function run(msg, data) {
|
|||||||
tracks = await lastfm.getTopTracks(userId, period, 15);
|
tracks = await lastfm.getTopTracks(userId, period, 15);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -652,7 +664,7 @@ export async function run(msg, data) {
|
|||||||
lb = await lastfm.getLeaderboard(0, 10);
|
lb = await lastfm.getLeaderboard(0, 10);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -693,7 +705,7 @@ export async function run(msg, data) {
|
|||||||
await replyMsg.message.removeAllReactions();
|
await replyMsg.message.removeAllReactions();
|
||||||
} catch {
|
} catch {
|
||||||
for (const emoji of navEmojis) {
|
for (const emoji of navEmojis) {
|
||||||
try { await replyMsg.message.removeReaction(emoji); } catch {}
|
try { await replyMsg.message.removeReaction(emoji); } catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -727,7 +739,7 @@ export async function run(msg, data) {
|
|||||||
try {
|
try {
|
||||||
lb = await lastfm.getLeaderboard(currentPage, 10);
|
lb = await lastfm.getLeaderboard(currentPage, 10);
|
||||||
} catch {
|
} catch {
|
||||||
/* keep previous data */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
||||||
@@ -746,7 +758,7 @@ export async function run(msg, data) {
|
|||||||
tracks = await lastfm.getRecentTracks(userId, 15);
|
tracks = await lastfm.getRecentTracks(userId, 15);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -770,7 +782,7 @@ export async function run(msg, data) {
|
|||||||
artists = await lastfm.getTopArtists(userId, period, 15);
|
artists = await lastfm.getTopArtists(userId, period, 15);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -809,7 +821,7 @@ export async function run(msg, data) {
|
|||||||
const track = pLove.queue?.getCurrent();
|
const track = pLove.queue?.getCurrent();
|
||||||
if (!track) {
|
if (!track) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.nothingPlayingLove"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingLove"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -823,7 +835,7 @@ export async function run(msg, data) {
|
|||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.loveFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.loveFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -837,7 +849,7 @@ export async function run(msg, data) {
|
|||||||
const track = pUnlove.queue?.getCurrent();
|
const track = pUnlove.queue?.getCurrent();
|
||||||
if (!track) {
|
if (!track) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.nothingPlayingUnlove"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingUnlove"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -851,7 +863,7 @@ export async function run(msg, data) {
|
|||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.unloveFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.unloveFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -875,7 +887,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!artistName) {
|
if (!artistName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.nothingPlayingNoArtist"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingNoArtist"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -895,7 +907,7 @@ export async function run(msg, data) {
|
|||||||
try {
|
try {
|
||||||
listeners = await lastfm.getWhoKnows(artistName, memberIds);
|
listeners = await lastfm.getWhoKnows(artistName, memberIds);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
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));
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
else msg.reply(errEmbed);
|
else msg.reply(errEmbed);
|
||||||
return;
|
return;
|
||||||
@@ -951,7 +963,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!artistName) {
|
if (!artistName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
this.t(msg, "responses.lastfm.noArtistSpecified")
|
this.t(msg, "responses.lastfm.noArtistSpecified")
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -962,13 +974,13 @@ export async function run(msg, data) {
|
|||||||
info = await lastfm.getArtistInfo(artistName, userId);
|
info = await lastfm.getArtistInfo(artistName, userId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!info) {
|
if (!info) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.artistNotFound", { artist: artistName }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.artistNotFound", { artist: artistName }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1043,7 +1055,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!albumName) {
|
if (!albumName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
this.t(msg, "responses.lastfm.noAlbumSpecified")
|
this.t(msg, "responses.lastfm.noAlbumSpecified")
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -1054,13 +1066,13 @@ export async function run(msg, data) {
|
|||||||
info = await lastfm.getAlbumInfo(artistName || "", albumName, userId);
|
info = await lastfm.getAlbumInfo(artistName || "", albumName, userId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!info) {
|
if (!info) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.albumNotFound", { album: albumName }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.albumNotFound", { album: albumName }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1132,13 +1144,13 @@ export async function run(msg, data) {
|
|||||||
artistName = searchResult.artist;
|
artistName = searchResult.artist;
|
||||||
trackName = searchResult.name;
|
trackName = searchResult.name;
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!artistName || !trackName) {
|
if (!artistName || !trackName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
this.t(msg, "responses.lastfm.noTrackSpecified")
|
this.t(msg, "responses.lastfm.noTrackSpecified")
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -1149,13 +1161,13 @@ export async function run(msg, data) {
|
|||||||
info = await lastfm.getTrackInfo(artistName, trackName, userId);
|
info = await lastfm.getTrackInfo(artistName, trackName, userId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!info) {
|
if (!info) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.trackNotFound", { track: trackName, artist: artistName }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.trackNotFound", { track: trackName, artist: artistName }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1215,7 +1227,7 @@ export async function run(msg, data) {
|
|||||||
let similarTracks = [];
|
let similarTracks = [];
|
||||||
try {
|
try {
|
||||||
similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 5);
|
similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 5);
|
||||||
} catch {}
|
} catch(e) { }
|
||||||
|
|
||||||
if (similarTracks.length) {
|
if (similarTracks.length) {
|
||||||
const simStr = similarTracks.map(t => {
|
const simStr = similarTracks.map(t => {
|
||||||
@@ -1242,7 +1254,7 @@ export async function run(msg, data) {
|
|||||||
albums = await lastfm.getTopAlbums(userId, period, 15);
|
albums = await lastfm.getTopAlbums(userId, period, 15);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1288,7 +1300,7 @@ export async function run(msg, data) {
|
|||||||
tags = await lastfm.getUserTopTags(userId, 20);
|
tags = await lastfm.getUserTopTags(userId, 20);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1319,7 +1331,7 @@ export async function run(msg, data) {
|
|||||||
const tagName = data.get("token")?.value;
|
const tagName = data.get("token")?.value;
|
||||||
if (!tagName) {
|
if (!tagName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
this.t(msg, "responses.lastfm.tagProvideName", { prefix })
|
this.t(msg, "responses.lastfm.tagProvideName", { prefix })
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -1337,13 +1349,13 @@ export async function run(msg, data) {
|
|||||||
]);
|
]);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!tagInfo) {
|
if (!tagInfo) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.tagNotFound", { tag: tagName }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tagNotFound", { tag: tagName }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1392,7 +1404,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!targetUserId) {
|
if (!targetUserId) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
this.t(msg, "responses.lastfm.compareSpecifyUser", { prefix })
|
this.t(msg, "responses.lastfm.compareSpecifyUser", { prefix })
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -1401,7 +1413,7 @@ export async function run(msg, data) {
|
|||||||
const targetUser = await lastfm.getUser(targetUserId);
|
const targetUser = await lastfm.getUser(targetUserId);
|
||||||
if (!targetUser) {
|
if (!targetUser) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
this.t(msg, "responses.lastfm.compareUserNotLinked")
|
this.t(msg, "responses.lastfm.compareUserNotLinked")
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -1412,13 +1424,13 @@ export async function run(msg, data) {
|
|||||||
comparison = await lastfm.compareUsers(userId, targetUserId);
|
comparison = await lastfm.compareUsers(userId, targetUserId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!comparison) {
|
if (!comparison) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.compareFailed"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.compareFailed"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1455,7 +1467,7 @@ export async function run(msg, data) {
|
|||||||
const current = extractCurrentTrack(pCover);
|
const current = extractCurrentTrack(pCover);
|
||||||
if (!current || !current.name) {
|
if (!current || !current.name) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.coverNothingPlaying"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.coverNothingPlaying"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1473,7 +1485,7 @@ export async function run(msg, data) {
|
|||||||
coverUrl = albumInfo.image;
|
coverUrl = albumInfo.image;
|
||||||
albumTitle = `${albumInfo.name} by ${albumInfo.artist}`;
|
albumTitle = `${albumInfo.name} by ${albumInfo.artist}`;
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!coverUrl) {
|
if (!coverUrl) {
|
||||||
@@ -1486,7 +1498,7 @@ export async function run(msg, data) {
|
|||||||
albumTitle = trackInfo.album.title;
|
albumTitle = trackInfo.album.title;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!coverUrl) {
|
if (!coverUrl) {
|
||||||
@@ -1509,7 +1521,7 @@ export async function run(msg, data) {
|
|||||||
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||||
if (!guild) {
|
if (!guild) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.refreshFailed"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.refreshFailed"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
let count = 0;
|
let count = 0;
|
||||||
@@ -1555,7 +1567,7 @@ export async function run(msg, data) {
|
|||||||
try {
|
try {
|
||||||
affinityResults = await lastfm.getAffinity(memberIds, 10);
|
affinityResults = await lastfm.getAffinity(memberIds, 10);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
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));
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
else msg.reply(errEmbed);
|
else msg.reply(errEmbed);
|
||||||
return;
|
return;
|
||||||
@@ -1606,7 +1618,7 @@ export async function run(msg, data) {
|
|||||||
try {
|
try {
|
||||||
crowns = await lastfm.getCrowns(userId, memberIds);
|
crowns = await lastfm.getCrowns(userId, memberIds);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
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));
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
else msg.reply(errEmbed);
|
else msg.reply(errEmbed);
|
||||||
return;
|
return;
|
||||||
@@ -1680,13 +1692,13 @@ export async function run(msg, data) {
|
|||||||
artistName = searchResult.artist;
|
artistName = searchResult.artist;
|
||||||
trackName = searchResult.name;
|
trackName = searchResult.name;
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!artistName || !trackName) {
|
if (!artistName || !trackName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1704,7 +1716,7 @@ export async function run(msg, data) {
|
|||||||
try {
|
try {
|
||||||
listeners = await lastfm.getWhoKnowsTrack(artistName, trackName, memberIds);
|
listeners = await lastfm.getWhoKnowsTrack(artistName, trackName, memberIds);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
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));
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
else msg.reply(errEmbed);
|
else msg.reply(errEmbed);
|
||||||
return;
|
return;
|
||||||
@@ -1767,7 +1779,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!albumName) {
|
if (!albumName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1785,7 +1797,7 @@ export async function run(msg, data) {
|
|||||||
try {
|
try {
|
||||||
listeners = await lastfm.getWhoKnowsAlbum(artistName || "", albumName, memberIds);
|
listeners = await lastfm.getWhoKnowsAlbum(artistName || "", albumName, memberIds);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
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));
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
else msg.reply(errEmbed);
|
else msg.reply(errEmbed);
|
||||||
return;
|
return;
|
||||||
@@ -1837,7 +1849,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!artistName) {
|
if (!artistName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1846,7 +1858,7 @@ export async function run(msg, data) {
|
|||||||
tags = await lastfm.getArtistTopTags(artistName, 15);
|
tags = await lastfm.getArtistTopTags(artistName, 15);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1897,7 +1909,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!albumName) {
|
if (!albumName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1906,7 +1918,7 @@ export async function run(msg, data) {
|
|||||||
tags = await lastfm.getAlbumTopTags(artistName || "", albumName, 15);
|
tags = await lastfm.getAlbumTopTags(artistName || "", albumName, 15);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1957,13 +1969,13 @@ export async function run(msg, data) {
|
|||||||
artistName = searchResult.artist;
|
artistName = searchResult.artist;
|
||||||
trackName = searchResult.name;
|
trackName = searchResult.name;
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!artistName || !trackName) {
|
if (!artistName || !trackName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1972,7 +1984,7 @@ export async function run(msg, data) {
|
|||||||
tags = await lastfm.getTrackTopTags(artistName, trackName, 15);
|
tags = await lastfm.getTrackTopTags(artistName, trackName, 15);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2008,7 +2020,7 @@ export async function run(msg, data) {
|
|||||||
friends = await lastfm.getUserFriends(userId, 20);
|
friends = await lastfm.getUserFriends(userId, 20);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2060,7 +2072,7 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2104,7 +2116,7 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2138,7 +2150,7 @@ export async function run(msg, data) {
|
|||||||
const tokenTextG = data.get("token")?.value?.trim() ?? "";
|
const tokenTextG = data.get("token")?.value?.trim() ?? "";
|
||||||
if (!tokenTextG) {
|
if (!tokenTextG) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Provide a query like \`artists <country>\` or \`tracks <country>\`. Example: \`${prefix}lastfm geo artists united states\`.`)]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a query like \`artists <country>\` or \`tracks <country>\`. Example: \`${prefix}lastfm geo artists united states\`.`)]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2156,7 +2168,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!country) {
|
if (!country) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Please specify a country name. Example: \`${prefix}lastfm geo artists united states\`.`)]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Please specify a country name. Example: \`${prefix}lastfm geo artists united states\`.`)]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2173,7 +2185,7 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2206,7 +2218,7 @@ export async function run(msg, data) {
|
|||||||
const tagName = data.get("token")?.value;
|
const tagName = data.get("token")?.value;
|
||||||
if (!tagName) {
|
if (!tagName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Provide a tag name via the token option. Example: \`${prefix}lastfm tagalbums rock\``)]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a tag name via the token option. Example: \`${prefix}lastfm tagalbums rock\``)]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2215,7 +2227,7 @@ export async function run(msg, data) {
|
|||||||
albums = await lastfm.getTagTopAlbums(tagName.trim(), 15);
|
albums = await lastfm.getTagTopAlbums(tagName.trim(), 15);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2265,7 +2277,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!artistName) {
|
if (!artistName) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2274,7 +2286,7 @@ export async function run(msg, data) {
|
|||||||
recentTracks = await lastfm.getRecentTracks(userId, 200);
|
recentTracks = await lastfm.getRecentTracks(userId, 200);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2311,7 +2323,7 @@ export async function run(msg, data) {
|
|||||||
const query = data.get("token")?.value;
|
const query = data.get("token")?.value;
|
||||||
if (!query) {
|
if (!query) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Provide a search query via the token option. Example: \`${prefix}lastfm search radiohead\``)]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a search query via the token option. Example: \`${prefix}lastfm search radiohead\``)]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2324,7 +2336,7 @@ export async function run(msg, data) {
|
|||||||
]);
|
]);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+22
-19
@@ -1,7 +1,11 @@
|
|||||||
|
/**
|
||||||
|
* @file leave.mjs — Leave the current voice channel and stop playback
|
||||||
|
* @module commands.leave
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/constants/Logger.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
|
||||||
import { get247ChannelMode } from "../src/constants/Helpers247.mjs";
|
import { get247ChannelMode } from "../src/constants/Helpers247.mjs";
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -15,13 +19,6 @@ export const command = new CommandBuilder()
|
|||||||
.setRequired(false)
|
.setRequired(false)
|
||||||
);
|
);
|
||||||
|
|
||||||
function embed(desc) {
|
|
||||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] };
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanId(value) {
|
|
||||||
return String(value ?? "").replace(/\D/g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolvePlayerGuildId(player, mapKey, client) {
|
function resolvePlayerGuildId(player, mapKey, client) {
|
||||||
const direct = cleanId(player?._guildId);
|
const direct = cleanId(player?._guildId);
|
||||||
@@ -32,6 +29,12 @@ function resolvePlayerGuildId(player, mapKey, client) {
|
|||||||
return cleanId(ch?.guildId ?? ch?.guild?.id ?? ch?.server_id ?? ch?.serverId);
|
return cleanId(ch?.guildId ?? ch?.guild?.id ?? ch?.server_id ?? ch?.serverId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the leave command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const guildId = msg.channel?.guild?.id
|
const guildId = msg.channel?.guild?.id
|
||||||
?? msg.channel?.guildId
|
?? msg.channel?.guildId
|
||||||
@@ -54,24 +57,24 @@ export async function run(msg, data) {
|
|||||||
if (specifiedChannel) {
|
if (specifiedChannel) {
|
||||||
targetChannelId = cleanId(specifiedChannel);
|
targetChannelId = cleanId(specifiedChannel);
|
||||||
} else {
|
} else {
|
||||||
const userChannelId = this.players.checkVoiceChannels(msg);
|
const { channelId: userChannelId } = await this.players.checkVoiceChannels(msg);
|
||||||
if (userChannelId) targetChannelId = cleanId(userChannelId);
|
if (userChannelId) targetChannelId = cleanId(userChannelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!targetChannelId) {
|
if (!targetChannelId) {
|
||||||
if (guildPlayers.length === 0) {
|
if (guildPlayers.length === 0) {
|
||||||
return msg.reply(embed(this.t(msg, "responses.leave.notInVoice")));
|
return msg.reply(this.t(msg, "responses.leave.notInVoice"));
|
||||||
}
|
}
|
||||||
const channelList = guildPlayers.map(([mapKey, p]) => {
|
const channelList = guildPlayers.map(([mapKey, p]) => {
|
||||||
const id = cleanId(p._channelId ?? mapKey);
|
const id = cleanId(p._channelId ?? mapKey);
|
||||||
return id ? `<#${id}>` : "`unknown`";
|
return id ? `<#${id}>` : "`unknown`";
|
||||||
});
|
});
|
||||||
return msg.reply(embed(
|
return msg.reply(
|
||||||
this.t(msg, "responses.leave.specifyChannel", {
|
this.t(msg, "responses.leave.specifyChannel", {
|
||||||
channels: channelList.map(c => `• ${c}`).join("\n"),
|
channels: channelList.map(c => `• ${c}`).join("\n"),
|
||||||
prefix: this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id)
|
prefix: this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id)
|
||||||
})
|
})
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const player = this.players.playerMap.get(targetChannelId)
|
const player = this.players.playerMap.get(targetChannelId)
|
||||||
@@ -82,21 +85,21 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!player) {
|
if (!player) {
|
||||||
if (guildPlayers.length === 0) {
|
if (guildPlayers.length === 0) {
|
||||||
return msg.reply(embed(this.t(msg, "responses.leave.notInVoice")));
|
return msg.reply(this.t(msg, "responses.leave.notInVoice"));
|
||||||
}
|
}
|
||||||
const channelList = guildPlayers.map(([mapKey, p]) => {
|
const channelList = guildPlayers.map(([mapKey, p]) => {
|
||||||
const id = cleanId(p._channelId ?? mapKey);
|
const id = cleanId(p._channelId ?? mapKey);
|
||||||
return id ? `<#${id}>` : "`unknown`";
|
return id ? `<#${id}>` : "`unknown`";
|
||||||
});
|
});
|
||||||
return msg.reply(embed(
|
return msg.reply(
|
||||||
this.t(msg, "responses.leave.noPlayerInChannel", {
|
this.t(msg, "responses.leave.noPlayerInChannel", {
|
||||||
channel: `<#${targetChannelId}>`,
|
channel: `<#${targetChannelId}>`,
|
||||||
channels: channelList.map(c => `• ${c}`).join("\n")
|
channels: channelList.map(c => `• ${c}`).join("\n")
|
||||||
})
|
})
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!player?.connection) return msg.reply(embed(this.t(msg, "responses.leave.playerNotInit")));
|
if (!player?.connection) return msg.reply(this.t(msg, "responses.leave.playerNotInit"));
|
||||||
|
|
||||||
const activeChannelId = cleanId(player._channelId) || targetChannelId;
|
const activeChannelId = cleanId(player._channelId) || targetChannelId;
|
||||||
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
|
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
|
||||||
@@ -134,7 +137,7 @@ export async function run(msg, data) {
|
|||||||
player.destroy();
|
player.destroy();
|
||||||
|
|
||||||
if (mode === "auto") {
|
if (mode === "auto") {
|
||||||
msg.reply(embed(this.t(msg, "responses.leave.leftRejoin247", { channel: targetChannelId, prefix })));
|
msg.reply(this.t(msg, "responses.leave.leftRejoin247", { channel: targetChannelId, prefix }));
|
||||||
const rejoinDelay = this.config?.timers?.leave247RejoinDelay ?? 5000;
|
const rejoinDelay = this.config?.timers?.leave247RejoinDelay ?? 5000;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (this._spawnPlayer) {
|
if (this._spawnPlayer) {
|
||||||
@@ -144,7 +147,7 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
}, rejoinDelay);
|
}, rejoinDelay);
|
||||||
} else {
|
} else {
|
||||||
msg.reply(embed(this.t(msg, "responses.leave.left247On", { prefix })));
|
msg.reply(this.t(msg, "responses.leave.left247On", { prefix }));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
await this.leaveChannel(activeChannelId, guildId, msg);
|
await this.leaveChannel(activeChannelId, guildId, msg);
|
||||||
|
|||||||
+13
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file list.mjs — Display the current song queue with pagination
|
||||||
|
* @module commands.list
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { QueuePaginator, getGlobalColor } from "../src/MessageHandler.mjs";
|
import { QueuePaginator, getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
@@ -16,6 +21,12 @@ export const command = new CommandBuilder()
|
|||||||
.setRequired(false)
|
.setRequired(false)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the list command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const p = await this.getPlayer(message);
|
const p = await this.getPlayer(message);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -85,5 +96,6 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
new QueuePaginator(message, this.messages, this.client)
|
new QueuePaginator(message, this.messages, this.client)
|
||||||
.setTimeout(SESSION_MS)
|
.setTimeout(SESSION_MS)
|
||||||
.send(buildEmbed, totalPages, startPage);
|
.send(buildEmbed, totalPages, startPage)
|
||||||
|
.catch(() => {});
|
||||||
}
|
}
|
||||||
+12
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file loop.mjs — Toggle loop mode for the queue or current track
|
||||||
|
* @module commands.loop
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -12,6 +17,12 @@ export const command = new CommandBuilder()
|
|||||||
.setDescription("Specifies what loop should be toggled.", "options.loop.type")
|
.setDescription("Specifies what loop should be toggled.", "options.loop.type")
|
||||||
.setRequired(true));
|
.setRequired(true));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the loop command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const p = await this.getPlayer(message);
|
const p = await this.getPlayer(message);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -20,5 +31,5 @@ export async function run(message, data) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(res)
|
.setDescription(res)
|
||||||
;
|
;
|
||||||
message.reply({ embeds: [embed] });
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+15
-5
@@ -1,8 +1,14 @@
|
|||||||
|
/**
|
||||||
|
* @file lyrics.mjs — Fetch and display lyrics for the current or specified song
|
||||||
|
* @module commands.lyrics
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/constants/Logger.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/Utils.mjs";
|
||||||
|
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("lyrics")
|
.setName("lyrics")
|
||||||
@@ -11,9 +17,13 @@ export const command = new CommandBuilder()
|
|||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
const LOADING_FRAMES = ["◐", "◓", "◑", "◒"];
|
const LOADING_FRAMES = ["◐", "◓", "◑", "◒"];
|
||||||
const EMOJI_REMOVE_TIMEOUT = 60_000;
|
|
||||||
const SESSION_MS = 180_000;
|
const SESSION_MS = 180_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the lyrics command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -28,7 +38,7 @@ export async function run(message) {
|
|||||||
const loadingMsg = await message.reply({ embeds: [
|
const loadingMsg = await message.reply({ embeds: [
|
||||||
new EmbedBuilder().setColor(getGlobalColor())
|
new EmbedBuilder().setColor(getGlobalColor())
|
||||||
.setDescription(`${LOADING_FRAMES[0]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) }))
|
.setDescription(`${LOADING_FRAMES[0]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) }))
|
||||||
|
|
||||||
] });
|
] });
|
||||||
|
|
||||||
const loadingInterval = setInterval(() => {
|
const loadingInterval = setInterval(() => {
|
||||||
@@ -36,7 +46,7 @@ export async function run(message) {
|
|||||||
loadingMsg.edit({ embeds: [
|
loadingMsg.edit({ embeds: [
|
||||||
new EmbedBuilder().setColor(getGlobalColor())
|
new EmbedBuilder().setColor(getGlobalColor())
|
||||||
.setDescription(`${LOADING_FRAMES[frame]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) }))
|
.setDescription(`${LOADING_FRAMES[frame]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) }))
|
||||||
|
|
||||||
] }).catch(() => {});
|
] }).catch(() => {});
|
||||||
}, 800);
|
}, 800);
|
||||||
|
|
||||||
@@ -54,7 +64,7 @@ export async function run(message) {
|
|||||||
] });
|
] });
|
||||||
}
|
}
|
||||||
|
|
||||||
try { await loadingMsg.message.delete(); } catch {}
|
try { await loadingMsg.message.delete(); } catch(e) { }
|
||||||
|
|
||||||
const syncIndicator = result.synced ? this.t(message, "responses.lyrics.syncedBadge") : "";
|
const syncIndicator = result.synced ? this.t(message, "responses.lyrics.syncedBadge") : "";
|
||||||
const displayTitle = Utils.cleanTitle(current.title);
|
const displayTitle = Utils.cleanTitle(current.title);
|
||||||
@@ -189,4 +199,4 @@ export async function run(message) {
|
|||||||
logger.error("[Lyrics Command] Error:", err);
|
logger.error("[Lyrics Command] Error:", err);
|
||||||
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.lyrics.error", { error: Utils.truncate(err.message, 100) }))] }).catch(() => {});
|
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.lyrics.error", { error: Utils.truncate(err.message, 100) }))] }).catch(() => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+14
-3
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file move.mjs — Move a track from one position to another in the queue
|
||||||
|
* @module commands.move
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -16,13 +21,19 @@ export const command = new CommandBuilder()
|
|||||||
.setRequired(true)
|
.setRequired(true)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the move command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const from = data.get("from")?.value;
|
const from = data.get("from")?.value;
|
||||||
const to = data.get("to")?.value;
|
const to = data.get("to")?.value;
|
||||||
if (from == null || from < 1) return message.replyEmbed("Source position must be 1 or greater.");
|
if (from == null || from < 1) return message.replyEmbed("Source position must be 1 or greater.").catch(() => {});
|
||||||
if (to == null || to < 1) return message.replyEmbed("Target position must be 1 or greater.");
|
if (to == null || to < 1) return message.replyEmbed("Target position must be 1 or greater.").catch(() => {});
|
||||||
const res = p.move(from, to);
|
const res = p.move(from, to);
|
||||||
message.replyEmbed(res);
|
message.replyEmbed(res).catch(() => {});
|
||||||
}
|
}
|
||||||
+24
-7
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file np.mjs — Show now-playing information for the current track
|
||||||
|
* @module commands.np
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -7,6 +12,11 @@ export const command = new CommandBuilder()
|
|||||||
.setDescription("Request the name and url of the currently playing song.", "commands.np")
|
.setDescription("Request the name and url of the currently playing song.", "commands.np")
|
||||||
.addAliases("current", "nowplaying");
|
.addAliases("current", "nowplaying");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the np command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg) {
|
export async function run(msg) {
|
||||||
const p = await this.getPlayer(msg);
|
const p = await this.getPlayer(msg);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -17,12 +27,19 @@ export async function run(msg) {
|
|||||||
;
|
;
|
||||||
const loadingMsg = await msg.reply({ embeds: [loadingEmbed] });
|
const loadingMsg = await msg.reply({ embeds: [loadingEmbed] });
|
||||||
|
|
||||||
const data = await p.nowPlaying();
|
try {
|
||||||
|
const data = await p.nowPlaying();
|
||||||
|
if (!data?.msg) {
|
||||||
|
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses._common.nothingPlaying"))] }).catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setDescription(data.msg);
|
||||||
|
if (data.image) embed.setThumbnail(data.image);
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
loadingMsg.edit({ embeds: [embed] }).catch(() => {});
|
||||||
.setColor(getGlobalColor())
|
} catch (e) {
|
||||||
.setDescription(data.msg);
|
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses._common.nothingPlaying"))] }).catch(() => {});
|
||||||
if (data.image) embed.setThumbnail(data.image);
|
}
|
||||||
|
|
||||||
loadingMsg.edit({ embeds: [embed] }).catch(() => {});
|
|
||||||
}
|
}
|
||||||
+11
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file pause.mjs — Pause the current playback
|
||||||
|
* @module commands.pause
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -7,6 +12,11 @@ export const command = new CommandBuilder()
|
|||||||
.setDescription("Pause the playback in your voice channel", "commands.pause")
|
.setDescription("Pause the playback in your voice channel", "commands.pause")
|
||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the pause command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message);
|
const p = await this.getPlayer(message);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -15,5 +25,5 @@ export async function run(message) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(res)
|
.setDescription(res)
|
||||||
;
|
;
|
||||||
message.reply({ embeds: [embed] });
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+24
-21
@@ -1,16 +1,22 @@
|
|||||||
|
/**
|
||||||
|
* @file play.mjs — Play a song, playlist, or Last.fm URL — the main music command with provider selection
|
||||||
|
* @module commands.play
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { PROVIDER_CHOICES } from "../src/constants/providers.mjs";
|
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs";
|
||||||
import { playLastFmCategory } from "./lastfm.mjs";
|
import { playLastFmCategory } from "./lastfm.mjs";
|
||||||
|
import { ERROR_COLOR } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse a Last.fm music URL and extract artist and track info.
|
* Parse a Last.fm music URL and extract artist and track info.
|
||||||
* Supports:
|
* Supports:
|
||||||
* https:
|
* https://www.last.fm/music/Artist
|
||||||
* https:
|
* https://www.last.fm/music/Artist/Track
|
||||||
* https:
|
* https://www.last.fm/music/Artist/Album/Track
|
||||||
* https:
|
* https://www.last.fm/music/Artist/_/Track
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @returns {{ artist: string, track: string|null, album: string|null, url: string } | null}
|
* @returns {{ artist: string, track: string|null, album: string|null, url: string } | null}
|
||||||
@@ -106,15 +112,6 @@ function parseLastFmSubProvider(query) {
|
|||||||
return { category: lower, resolveProvider: null };
|
return { category: lower, resolveProvider: null };
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseInlineProvider(raw) {
|
|
||||||
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
|
|
||||||
if (!match) return { provider: null, query: raw.trim() };
|
|
||||||
const maybeProvider = match[1].toLowerCase();
|
|
||||||
if (PROVIDER_CHOICES.includes(maybeProvider)) {
|
|
||||||
return { provider: maybeProvider, query: match[2].trim() };
|
|
||||||
}
|
|
||||||
return { provider: null, query: raw.trim() };
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseLastFmTrackQuery(raw) {
|
function parseLastFmTrackQuery(raw) {
|
||||||
const value = String(raw ?? "").trim();
|
const value = String(raw ?? "").trim();
|
||||||
@@ -179,6 +176,12 @@ export const command = new CommandBuilder()
|
|||||||
, true)
|
, true)
|
||||||
.addAlias("p");
|
.addAlias("p");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the play command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const rawQuery = data.get("query").value;
|
const rawQuery = data.get("query").value;
|
||||||
const flagProvider = data.get("provider")?.value;
|
const flagProvider = data.get("provider")?.value;
|
||||||
@@ -204,7 +207,7 @@ export async function run(message, data) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(message, "responses.play.searching"));
|
.setDescription(this.t(message, "responses.play.searching"));
|
||||||
let statusMsg = null;
|
let statusMsg = null;
|
||||||
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch {}
|
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { }
|
||||||
|
|
||||||
const playQuery = `${parsed.track} ${parsed.artist}`.trim();
|
const playQuery = `${parsed.track} ${parsed.artist}`.trim();
|
||||||
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider, lastfmTrackMeta);
|
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider, lastfmTrackMeta);
|
||||||
@@ -224,7 +227,7 @@ export async function run(message, data) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(message, "responses.play.searching"));
|
.setDescription(this.t(message, "responses.play.searching"));
|
||||||
let statusMsg = null;
|
let statusMsg = null;
|
||||||
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch {}
|
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { }
|
||||||
|
|
||||||
const playQuery = parsed.artist;
|
const playQuery = parsed.artist;
|
||||||
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider);
|
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider);
|
||||||
@@ -244,7 +247,7 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
if (parsed.invalidCategory) {
|
if (parsed.invalidCategory) {
|
||||||
return message.reply({
|
return message.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
`❌ \`${resolveProvider}:${parsed.invalidCategory}\` is not valid. Non-Last.fm providers only support \`top\`.\nUse \`lastfm:${resolveProvider}\` or \`lastfm:${resolveProvider}:top\` instead.\nFor other categories, use Last.fm as the resolve provider: \`lastfm:lf:${parsed.invalidCategory}\``
|
`❌ \`${resolveProvider}:${parsed.invalidCategory}\` is not valid. Non-Last.fm providers only support \`top\`.\nUse \`lastfm:${resolveProvider}\` or \`lastfm:${resolveProvider}:top\` instead.\nFor other categories, use Last.fm as the resolve provider: \`lastfm:lf:${parsed.invalidCategory}\``
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
@@ -252,7 +255,7 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
if (!lowerQuery && resolveProvider && (resolveProvider === "lf" || resolveProvider === "lastfm")) {
|
if (!lowerQuery && resolveProvider && (resolveProvider === "lf" || resolveProvider === "lastfm")) {
|
||||||
return message.reply({
|
return message.reply({
|
||||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription([
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([
|
||||||
`❌ Specify a Last.fm category after \`lf:\``,
|
`❌ Specify a Last.fm category after \`lf:\``,
|
||||||
``,
|
``,
|
||||||
`**Available categories:**`,
|
`**Available categories:**`,
|
||||||
@@ -295,14 +298,14 @@ export async function run(message, data) {
|
|||||||
`🔍 Searching Last.fm for **${query}**...`
|
`🔍 Searching Last.fm for **${query}**...`
|
||||||
)]
|
)]
|
||||||
});
|
});
|
||||||
} catch {}
|
} catch(e) { }
|
||||||
|
|
||||||
try {
|
try {
|
||||||
searchResult = await lastfm.searchTrack(query);
|
searchResult = await lastfm.searchTrack(query);
|
||||||
} catch {}
|
} catch(e) { }
|
||||||
|
|
||||||
if (!searchResult) {
|
if (!searchResult) {
|
||||||
const noResult = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
const noResult = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
`❌ No results found on Last.fm for **${query}**.`
|
`❌ No results found on Last.fm for **${query}**.`
|
||||||
)] };
|
)] };
|
||||||
if (statusMsg) statusMsg.edit(noResult).catch(() => message.reply(noResult));
|
if (statusMsg) statusMsg.edit(noResult).catch(() => message.reply(noResult));
|
||||||
|
|||||||
+22
-21
@@ -1,7 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* @file player.mjs — Interactive player control panel with playback buttons and now-playing display
|
||||||
|
* @module commands.player
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/Utils.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
|
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("player")
|
.setName("player")
|
||||||
@@ -38,8 +44,12 @@ const PROGRESS = {
|
|||||||
end: "▕"
|
end: "▕"
|
||||||
};
|
};
|
||||||
|
|
||||||
const EMOJI_REMOVE_TIMEOUT = 60000;
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the player command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg) {
|
export async function run(msg) {
|
||||||
const player = await this.getPlayer(msg, false, false, false);
|
const player = await this.getPlayer(msg, false, false, false);
|
||||||
if (!player) return;
|
if (!player) return;
|
||||||
@@ -68,17 +78,8 @@ export async function run(msg) {
|
|||||||
? (current.duration.seconds ?? 0) * 1000
|
? (current.duration.seconds ?? 0) * 1000
|
||||||
: current.duration;
|
: current.duration;
|
||||||
|
|
||||||
const progress = Math.min(elapsed / totalMs, 1);
|
const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled);
|
||||||
const barLength = 20;
|
progressBar = PROGRESS.start + bar + PROGRESS.end;
|
||||||
const filled = Math.floor(progress * barLength);
|
|
||||||
const position = Math.min(Math.max(filled, 0), barLength - 1);
|
|
||||||
const emptyCount = Math.max(barLength - position - 1, 0);
|
|
||||||
|
|
||||||
progressBar = PROGRESS.start +
|
|
||||||
PROGRESS.filled.repeat(position) +
|
|
||||||
(isPlaying ? PROGRESS.indicator : PROGRESS.filled) +
|
|
||||||
PROGRESS.empty.repeat(emptyCount) +
|
|
||||||
PROGRESS.end;
|
|
||||||
|
|
||||||
const elapsedStr = Utils.prettifyMS(elapsed);
|
const elapsedStr = Utils.prettifyMS(elapsed);
|
||||||
const totalStr = Utils.prettifyMS(totalMs);
|
const totalStr = Utils.prettifyMS(totalMs);
|
||||||
@@ -147,7 +148,7 @@ export async function run(msg) {
|
|||||||
try {
|
try {
|
||||||
await message.message.react(control.emoji);
|
await message.message.react(control.emoji);
|
||||||
await Utils.sleep(50);
|
await Utils.sleep(50);
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,7 +168,7 @@ export async function run(msg) {
|
|||||||
for (const emoji of controlEmojis) {
|
for (const emoji of controlEmojis) {
|
||||||
try {
|
try {
|
||||||
await message.message.removeReaction(emoji);
|
await message.message.removeReaction(emoji);
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -190,7 +191,7 @@ export async function run(msg) {
|
|||||||
for (const emoji of ["⬅️", "➡️", "❌"]) {
|
for (const emoji of ["⬅️", "➡️", "❌"]) {
|
||||||
try {
|
try {
|
||||||
await lyricsMsg.message.removeReaction(emoji);
|
await lyricsMsg.message.removeReaction(emoji);
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -233,9 +234,9 @@ export async function run(msg) {
|
|||||||
const closedEmbed = buildEmbed({
|
const closedEmbed = buildEmbed({
|
||||||
message: this.t(msg, "responses.player.sessionClosed", { reason: reason !== "timeout" ? ` • ${reason}` : "" })
|
message: this.t(msg, "responses.player.sessionClosed", { reason: reason !== "timeout" ? ` • ${reason}` : "" })
|
||||||
});
|
});
|
||||||
closedEmbed.color = getGlobalColor();
|
closedEmbed.setColor(getGlobalColor());
|
||||||
closedEmbed.footer = { text: this.t(msg, "responses._common.sessionEnded") };
|
closedEmbed.setFooter({ text: this.t(msg, "responses._common.sessionEnded") });
|
||||||
closedEmbed.title = this.t(msg, "responses.player.inactiveTitle");
|
closedEmbed.setTitle(this.t(msg, "responses.player.inactiveTitle"));
|
||||||
|
|
||||||
await message.edit({
|
await message.edit({
|
||||||
embeds: [closedEmbed],
|
embeds: [closedEmbed],
|
||||||
@@ -301,7 +302,7 @@ export async function run(msg) {
|
|||||||
if (player.paused) {
|
if (player.paused) {
|
||||||
reply = player.resume();
|
reply = player.resume();
|
||||||
} else if (!player.queue.getCurrent() && !player.queue.isEmpty()) {
|
} else if (!player.queue.getCurrent() && !player.queue.isEmpty()) {
|
||||||
player.playNext();
|
player.playNext().catch(() => {});
|
||||||
reply = this.t(msg, "responses.player.startingPlayback");
|
reply = this.t(msg, "responses.player.startingPlayback");
|
||||||
} else {
|
} else {
|
||||||
reply = this.t(msg, "responses.player.alreadyPlaying");
|
reply = this.t(msg, "responses.player.alreadyPlaying");
|
||||||
@@ -360,7 +361,7 @@ export async function run(msg) {
|
|||||||
shouldUpdate = true;
|
shouldUpdate = true;
|
||||||
try {
|
try {
|
||||||
const { run: runFilter } = await import("./filter.mjs");
|
const { run: runFilter } = await import("./filter.mjs");
|
||||||
runFilter.call(this, msg);
|
await runFilter.call(this, msg);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
reply = this.t(msg, "responses.player.filterError", { error: Utils.truncate(err.message, 50) });
|
reply = this.t(msg, "responses.player.filterError", { error: Utils.truncate(err.message, 50) });
|
||||||
}
|
}
|
||||||
@@ -499,4 +500,4 @@ export async function run(msg) {
|
|||||||
|
|
||||||
resetTimeout();
|
resetTimeout();
|
||||||
resetEmojiTimer();
|
resetEmojiTimer();
|
||||||
}
|
}
|
||||||
+19
-11
@@ -1,17 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* @file playnext.mjs — Add a song to the top of the queue (play next)
|
||||||
|
* @module commands.playnext
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { PROVIDER_CHOICES } from "../src/constants/providers.mjs";
|
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs";
|
||||||
|
|
||||||
function parseInlineProvider(raw) {
|
|
||||||
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
|
|
||||||
if (!match) return { provider: null, query: raw.trim() };
|
|
||||||
const maybeProvider = match[1].toLowerCase();
|
|
||||||
if (PROVIDER_CHOICES.includes(maybeProvider)) {
|
|
||||||
return { provider: maybeProvider, query: match[2].trim() };
|
|
||||||
}
|
|
||||||
return { provider: null, query: raw.trim() };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("playnext")
|
.setName("playnext")
|
||||||
@@ -37,6 +33,12 @@ export const command = new CommandBuilder()
|
|||||||
, true)
|
, true)
|
||||||
.addAlias("pn");
|
.addAlias("pn");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the playnext command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const p = await this.getPlayer(message, true, true, true);
|
const p = await this.getPlayer(message, true, true, true);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -50,7 +52,13 @@ export async function run(message, data) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(message, "responses.playnext.searching"))
|
.setDescription(this.t(message, "responses.playnext.searching"))
|
||||||
;
|
;
|
||||||
const statusMsg = await message.reply({ embeds: [searchEmbed] });
|
|
||||||
|
let statusMsg;
|
||||||
|
try {
|
||||||
|
statusMsg = await message.reply({ embeds: [searchEmbed] });
|
||||||
|
} catch (_e) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const messages = p.playFirst(query, provider);
|
const messages = p.playFirst(query, provider);
|
||||||
messages.on("message", d => {
|
messages.on("message", d => {
|
||||||
|
|||||||
+18
-16
@@ -1,17 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* @file radio.mjs — Play a radio stream or search for radio stations
|
||||||
|
* @module commands.radio
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
|
import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
const NUMBER_EMOJIS = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"];
|
|
||||||
const CANCEL_EMOJI = "❌";
|
|
||||||
const PREV_EMOJI = "⬅️";
|
|
||||||
const NEXT_EMOJI = "➡️";
|
|
||||||
|
|
||||||
function mkEmbed(desc, title) {
|
|
||||||
const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
|
|
||||||
if (title) b.setTitle(title);
|
|
||||||
return { embeds: [b] };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const command = function() {
|
export const command = function() {
|
||||||
if (!this.config.radio?.length) return null;
|
if (!this.config.radio?.length) return null;
|
||||||
@@ -27,9 +23,15 @@ export const command = function() {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the radio command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const radios = this.config.radio;
|
const radios = this.config.radio;
|
||||||
if (!radios?.length) return msg.reply(mkEmbed(this.t(msg, "responses.radio.noStations")));
|
if (!radios?.length) return msg.reply(this.t(msg, "responses.radio.noStations"));
|
||||||
|
|
||||||
const input = (data.get("station")?.value ?? "").trim().toLowerCase();
|
const input = (data.get("station")?.value ?? "").trim().toLowerCase();
|
||||||
|
|
||||||
@@ -49,7 +51,7 @@ export async function run(msg, data) {
|
|||||||
});
|
});
|
||||||
desc += `⬅️ Previous ➡️ Next ❌ Cancel`;
|
desc += `⬅️ Previous ➡️ Next ❌ Cancel`;
|
||||||
|
|
||||||
return { payload: mkEmbed(desc), pickable };
|
return { payload: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }, pickable };
|
||||||
};
|
};
|
||||||
|
|
||||||
let { payload, pickable } = buildPage();
|
let { payload, pickable } = buildPage();
|
||||||
@@ -67,7 +69,7 @@ export async function run(msg, data) {
|
|||||||
await rawMsg.removeAllReactions();
|
await rawMsg.removeAllReactions();
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
for (const emoji of baseEmojis) {
|
for (const emoji of baseEmojis) {
|
||||||
try { await rawMsg.removeReaction(emoji); } catch (_) {}
|
try { await rawMsg.removeReaction(emoji); } catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -77,7 +79,7 @@ export async function run(msg, data) {
|
|||||||
settled = true;
|
settled = true;
|
||||||
unobserve();
|
unobserve();
|
||||||
clearReactions().catch(() => {});
|
clearReactions().catch(() => {});
|
||||||
listMsg.edit(mkEmbed(this.t(msg, "responses.radio.timedOut"))).catch(() => {});
|
listMsg.edit(this.t(msg, "responses.radio.timedOut")).catch(() => {});
|
||||||
}, 60_000);
|
}, 60_000);
|
||||||
|
|
||||||
const normalize = (s) => s.replace(/\uFE0F/g, "");
|
const normalize = (s) => s.replace(/\uFE0F/g, "");
|
||||||
@@ -91,7 +93,7 @@ export async function run(msg, data) {
|
|||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
unobserve();
|
unobserve();
|
||||||
await clearReactions();
|
await clearReactions();
|
||||||
listMsg.edit(mkEmbed(this.t(msg, "responses.radio.cancelled"))).catch(() => {});
|
listMsg.edit(this.t(msg, "responses.radio.cancelled")).catch(() => {});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (emoji === normalize(NEXT_EMOJI)) page = (page + 1) % totalPages;
|
if (emoji === normalize(NEXT_EMOJI)) page = (page + 1) % totalPages;
|
||||||
@@ -120,7 +122,7 @@ export async function run(msg, data) {
|
|||||||
const radio = radios.find(r => r.name.toLowerCase() === input);
|
const radio = radios.find(r => r.name.toLowerCase() === input);
|
||||||
if (!radio) {
|
if (!radio) {
|
||||||
const names = radios.map(r => `\`${r.name}\``).join(", ");
|
const names = radios.map(r => `\`${r.name}\``).join(", ");
|
||||||
return msg.reply(mkEmbed(this.t(msg, "responses.radio.unknownStation", { station: input, stations: names })));
|
return msg.reply(this.t(msg, "responses.radio.unknownStation", { station: input, stations: names }));
|
||||||
}
|
}
|
||||||
return playStation(this, msg, radio);
|
return playStation(this, msg, radio);
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-11
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file reload.mjs — Hot-reload commands without restarting the bot (owner-only)
|
||||||
|
* @module commands.reload
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -16,9 +21,6 @@ export const command = new CommandBuilder()
|
|||||||
)
|
)
|
||||||
.setRequirement(r => r.setOwnerOnly(true));
|
.setRequirement(r => r.setOwnerOnly(true));
|
||||||
|
|
||||||
function embed(desc) {
|
|
||||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] };
|
|
||||||
}
|
|
||||||
|
|
||||||
const __dirname = path.dirname(new URL(import.meta.url).pathname);
|
const __dirname = path.dirname(new URL(import.meta.url).pathname);
|
||||||
const ROOT = path.resolve(__dirname, "..");
|
const ROOT = path.resolve(__dirname, "..");
|
||||||
@@ -88,17 +90,17 @@ async function showPaged(msg, title, lines, pageSize = 14) {
|
|||||||
const arrows = ["⬅️", "➡️"];
|
const arrows = ["⬅️", "➡️"];
|
||||||
const curr = { n: 0 };
|
const curr = { n: 0 };
|
||||||
|
|
||||||
const mkEmbed = (n) => ({
|
const buildPageEmbed = (n) => ({
|
||||||
embeds: [
|
embeds: [
|
||||||
new EmbedBuilder()
|
new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(title)
|
.setTitle(title)
|
||||||
.setDescription(pages[n].join("\n") + (pages.length > 1 ? `\n\nPage **${n + 1}** / **${pages.length}**` : ""))
|
.setDescription(pages[n].join("\n") + (pages.length > 1 ? `\n\nPage **${n + 1}** / **${pages.length}**` : ""))
|
||||||
|
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
const m = await msg.reply(mkEmbed(0));
|
const m = await msg.reply(buildPageEmbed(0));
|
||||||
if (!m || pages.length <= 1) return;
|
if (!m || pages.length <= 1) return;
|
||||||
|
|
||||||
m.message.react(arrows[0]).catch(() => {});
|
m.message.react(arrows[0]).catch(() => {});
|
||||||
@@ -107,7 +109,7 @@ async function showPaged(msg, title, lines, pageSize = 14) {
|
|||||||
const unsub = m.onReaction(arrows, (e) => {
|
const unsub = m.onReaction(arrows, (e) => {
|
||||||
if (e.emoji_id === arrows[0]) curr.n = Math.max(0, curr.n - 1);
|
if (e.emoji_id === arrows[0]) curr.n = Math.max(0, curr.n - 1);
|
||||||
else curr.n = Math.min(pages.length - 1, curr.n + 1);
|
else curr.n = Math.min(pages.length - 1, curr.n + 1);
|
||||||
m.edit(mkEmbed(curr.n)).catch(() => {});
|
m.edit(buildPageEmbed(curr.n)).catch(() => {});
|
||||||
});
|
});
|
||||||
|
|
||||||
setTimeout(() => { unsub?.(); }, 5 * 60_000);
|
setTimeout(() => { unsub?.(); }, 5 * 60_000);
|
||||||
@@ -120,6 +122,12 @@ async function showResults(msg, results, label) {
|
|||||||
await showPaged(msg, `🔄 Reload — ${label}`, [header, "", ...results.map(r => r.msg)]);
|
await showPaged(msg, `🔄 Reload — ${label}`, [header, "", ...results.map(r => r.msg)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the reload command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const target = (data.get("target")?.value ?? "").trim().toLowerCase();
|
const target = (data.get("target")?.value ?? "").trim().toLowerCase();
|
||||||
|
|
||||||
@@ -178,7 +186,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (this.handler.commands.some(c => c.name === target)) {
|
if (this.handler.commands.some(c => c.name === target)) {
|
||||||
const res = await reloadCommand(this, msg, target);
|
const res = await reloadCommand(this, msg, target);
|
||||||
return msg.reply(embed(res.msg));
|
return msg.reply(res.msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
const allMods = [...allModuleFiles("src"), ...allModuleFiles("audio")];
|
const allMods = [...allModuleFiles("src"), ...allModuleFiles("audio")];
|
||||||
@@ -189,10 +197,10 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (mod) {
|
if (mod) {
|
||||||
const res = await reloadModule(this, msg, mod.file, mod.label);
|
const res = await reloadModule(this, msg, mod.file, mod.label);
|
||||||
return msg.reply(embed(res.msg));
|
return msg.reply(res.msg);
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg.reply(embed(
|
return msg.reply(
|
||||||
this.t(msg, "responses.reload.unknownTarget", { target })
|
this.t(msg, "responses.reload.unknownTarget", { target })
|
||||||
));
|
);
|
||||||
}
|
}
|
||||||
+13
-2
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file remove.mjs — Remove a specific song from the queue by position
|
||||||
|
* @module commands.remove
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -9,11 +14,17 @@ export const command = new CommandBuilder()
|
|||||||
.setDescription("The position of the song in the queue. You can view the indices with the 'list' command", "options.remove.index")
|
.setDescription("The position of the song in the queue. You can view the indices with the 'list' command", "options.remove.index")
|
||||||
.setRequired(true));
|
.setRequired(true));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the remove command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const index = data.get("index")?.value;
|
const index = data.get("index")?.value;
|
||||||
if (index == null || index < 1) return message.replyEmbed("Queue position must be 1 or greater.");
|
if (index == null || index < 1) return message.replyEmbed("Queue position must be 1 or greater.").catch(() => {});
|
||||||
const res = p.remove(index - 1);
|
const res = p.remove(index - 1);
|
||||||
message.replyEmbed(res);
|
message.replyEmbed(res).catch(() => {});
|
||||||
}
|
}
|
||||||
+11
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file resume.mjs — Resume paused playback
|
||||||
|
* @module commands.resume
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -7,6 +12,11 @@ export const command = new CommandBuilder()
|
|||||||
.setDescription("Resume the playback in your voice channel", "commands.resume")
|
.setDescription("Resume the playback in your voice channel", "commands.resume")
|
||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the resume command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message, false, true, false);
|
const p = await this.getPlayer(message, false, true, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -15,5 +25,5 @@ export async function run(message) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(res)
|
.setDescription(res)
|
||||||
;
|
;
|
||||||
message.reply({ embeds: [embed] });
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+14
-14
@@ -1,19 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* @file search.mjs — Search for songs with interactive selection menu
|
||||||
|
* @module commands.search
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { Message, getGlobalColor } from "../src/MessageHandler.mjs";
|
import { Message, getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { PROVIDER_CHOICES, PROVIDER_NAMES } from "../src/constants/providers.mjs";
|
import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/constants/providers.mjs";
|
||||||
|
import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/constants/UI.mjs";
|
||||||
const NUMBER_EMOJIS = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"];
|
|
||||||
const CANCEL_EMOJI = "❌";
|
|
||||||
|
|
||||||
function parseInlineProvider(raw) {
|
|
||||||
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
|
|
||||||
if (!match) return { provider: null, query: raw.trim() };
|
|
||||||
const maybeProvider = match[1].toLowerCase();
|
|
||||||
if (PROVIDER_CHOICES.includes(maybeProvider))
|
|
||||||
return { provider: maybeProvider, query: match[2].trim() };
|
|
||||||
return { provider: null, query: raw.trim() };
|
|
||||||
}
|
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("search")
|
.setName("search")
|
||||||
@@ -41,6 +35,12 @@ export const command = new CommandBuilder()
|
|||||||
.setRequired(true)
|
.setRequired(true)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the search command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const p = await this.getPlayer(msg, true, true, true);
|
const p = await this.getPlayer(msg, true, true, true);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -115,7 +115,7 @@ export async function run(msg, data) {
|
|||||||
const clearReactions = async () => {
|
const clearReactions = async () => {
|
||||||
try {
|
try {
|
||||||
await rawMsg.removeAllReactions();
|
await rawMsg.removeAllReactions();
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
};
|
};
|
||||||
|
|
||||||
const wrapped = new Message(rawMsg, this.messages);
|
const wrapped = new Message(rawMsg, this.messages);
|
||||||
|
|||||||
+23
-49
@@ -1,6 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* @file seek.mjs — Seek to a specific position in the current track
|
||||||
|
* @module commands.seek
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
|
import { Utils } from "../src/Utils.mjs";
|
||||||
|
import { ERROR_COLOR } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("seek")
|
.setName("seek")
|
||||||
@@ -12,6 +19,12 @@ export const command = new CommandBuilder()
|
|||||||
.setRequired(true)
|
.setRequired(true)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the seek command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const positionInput = data.get("position")?.value;
|
const positionInput = data.get("position")?.value;
|
||||||
|
|
||||||
@@ -19,73 +32,34 @@ export async function run(msg, data) {
|
|||||||
if (!p) return;
|
if (!p) return;
|
||||||
|
|
||||||
if (!p.queue?.getCurrent()) {
|
if (!p.queue?.getCurrent()) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.nothingPlaying"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.nothingPlaying"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (p._paused) {
|
if (p._paused) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.paused"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.paused"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
let seekMs = parseSeekPosition(positionInput);
|
let seekMs = Utils.parseDuration(positionInput);
|
||||||
if (seekMs === null || seekMs < 0) {
|
if (!seekMs || seekMs < 0) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.invalidFormat"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.invalidFormat"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const trackDuration = p._getTrackDurationMs(p.queue.getCurrent());
|
const trackDuration = p._getTrackDurationMs(p.queue.getCurrent());
|
||||||
|
|
||||||
if (trackDuration > 0 && seekMs >= trackDuration) {
|
if (trackDuration > 0 && seekMs >= trackDuration) {
|
||||||
const maxStr = formatDuration(trackDuration);
|
const maxStr = Utils.prettifyMS(trackDuration);
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.exceedsDuration", { duration: maxStr }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.exceedsDuration", { duration: maxStr }))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await p.seekToPosition(seekMs);
|
const result = await p.seekToPosition(seekMs);
|
||||||
if (result) {
|
if (result) {
|
||||||
const seekStr = formatDuration(seekMs);
|
const seekStr = Utils.prettifyMS(seekMs);
|
||||||
const totalStr = trackDuration > 0 ? formatDuration(trackDuration) : "∞";
|
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.seek.seeked", { position: seekStr }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.seek.seeked", { position: seekStr }))] });
|
||||||
} else {
|
} else {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.notSupported"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.notSupported"))] });
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.failed", { error: err.message }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.failed", { error: err.message }))] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseSeekPosition(str) {
|
|
||||||
if (!str || typeof str !== "string") return null;
|
|
||||||
str = str.trim();
|
|
||||||
|
|
||||||
if (/^\d+$/.test(str)) {
|
|
||||||
return parseInt(str, 10) * 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
const parts = str.split(":").map(Number);
|
|
||||||
if (parts.some(isNaN)) return null;
|
|
||||||
|
|
||||||
if (parts.length === 2) {
|
|
||||||
const [minutes, seconds] = parts;
|
|
||||||
if (seconds >= 60) return null;
|
|
||||||
return (minutes * 60 + seconds) * 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (parts.length === 3) {
|
|
||||||
const [hours, minutes, seconds] = parts;
|
|
||||||
if (minutes >= 60 || seconds >= 60) return null;
|
|
||||||
return (hours * 3600 + minutes * 60 + seconds) * 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatDuration(ms) {
|
|
||||||
const totalSeconds = Math.floor(ms / 1000);
|
|
||||||
const hours = Math.floor(totalSeconds / 3600);
|
|
||||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
||||||
const seconds = totalSeconds % 60;
|
|
||||||
|
|
||||||
if (hours > 0) {
|
|
||||||
return `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
|
|
||||||
}
|
|
||||||
return `${minutes}:${String(seconds).padStart(2, "0")}`;
|
|
||||||
}
|
|
||||||
+13
-3
@@ -1,6 +1,12 @@
|
|||||||
|
/**
|
||||||
|
* @file servers.mjs — List servers the bot is currently in (owner-only)
|
||||||
|
* @module commands.servers
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
|
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("servers")
|
.setName("servers")
|
||||||
@@ -8,8 +14,12 @@ export const command = new CommandBuilder()
|
|||||||
.setRequirement(r => r.setOwnerOnly(true))
|
.setRequirement(r => r.setOwnerOnly(true))
|
||||||
.setCategory("util");
|
.setCategory("util");
|
||||||
|
|
||||||
const EMOJI_REMOVE_TIMEOUT = 60000;
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the servers command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg) {
|
export async function run(msg) {
|
||||||
const guilds = [...this.client.guilds.values()];
|
const guilds = [...this.client.guilds.values()];
|
||||||
|
|
||||||
@@ -86,7 +96,7 @@ export async function run(msg) {
|
|||||||
for (const emoji of navEmojis) {
|
for (const emoji of navEmojis) {
|
||||||
try {
|
try {
|
||||||
await replyMsg.message.removeReaction(emoji);
|
await replyMsg.message.removeReaction(emoji);
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -113,4 +123,4 @@ export async function run(msg) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
resetTimer();
|
resetTimer();
|
||||||
}
|
}
|
||||||
+24
-27
@@ -1,6 +1,11 @@
|
|||||||
|
/**
|
||||||
|
* @file settings.mjs — Configure server settings — prefix, volume, 24/7 mode, DJ role, locale, and more
|
||||||
|
* @module commands.settings
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs";
|
||||||
import runnables from "../settings/runnables.mjs";
|
import runnables from "../settings/runnables.mjs";
|
||||||
|
|
||||||
function embed(desc, opts = {}) {
|
function embed(desc, opts = {}) {
|
||||||
@@ -50,10 +55,6 @@ const VOLUME_MIN = 1;
|
|||||||
const VOLUME_MAX = 200;
|
const VOLUME_MAX = 200;
|
||||||
const MAX_247_CHANNELS = 10;
|
const MAX_247_CHANNELS = 10;
|
||||||
|
|
||||||
/** Extract clean numeric channel ID from any format */
|
|
||||||
function cleanId(raw) {
|
|
||||||
return String(raw).replace(/\D/g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate that a value looks like a real Fluxer ID.
|
* Validate that a value looks like a real Fluxer ID.
|
||||||
@@ -62,7 +63,7 @@ function cleanId(raw) {
|
|||||||
* (which would be garbage like "3", "42", "move", etc.).
|
* (which would be garbage like "3", "42", "move", etc.).
|
||||||
*/
|
*/
|
||||||
function isValidFluxerId(id) {
|
function isValidFluxerId(id) {
|
||||||
const cleaned = String(id).replace(/\D/g, "");
|
const cleaned = cleanId(id);
|
||||||
return cleaned.length >= 15 && cleaned.length <= 22;
|
return cleaned.length >= 15 && cleaned.length <= 22;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,16 +82,6 @@ function displayValue(key, value) {
|
|||||||
return `\`${value}\``;
|
return `\`${value}\``;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Resolve guild ID from a message context */
|
|
||||||
function getGuildId(message) {
|
|
||||||
return message.message?.guildId
|
|
||||||
?? message.message?.guild?.id
|
|
||||||
?? message.channel?.guildId
|
|
||||||
?? message.channel?.guild?.id
|
|
||||||
?? message.channel?.server_id
|
|
||||||
?? message.channel?.serverId
|
|
||||||
?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Resolve guild name from a message context */
|
/** Resolve guild name from a message context */
|
||||||
function getGuildName(message) {
|
function getGuildName(message) {
|
||||||
@@ -192,7 +183,7 @@ function resolveChannelName(client, channelId) {
|
|||||||
try {
|
try {
|
||||||
const ch = client?.channels?.get?.(channelId);
|
const ch = client?.channels?.get?.(channelId);
|
||||||
if (ch?.name) return ch.name;
|
if (ch?.name) return ch.name;
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -406,7 +397,7 @@ function prettifySettingLabel(key, t, guildId) {
|
|||||||
|
|
||||||
async function handle247(ctx, message, value) {
|
async function handle247(ctx, message, value) {
|
||||||
const set = ctx.getSettings(message);
|
const set = ctx.getSettings(message);
|
||||||
const guildId = getGuildId(message);
|
const guildId = getMessageGuildId(message);
|
||||||
const mode = value.toLowerCase().trim();
|
const mode = value.toLowerCase().trim();
|
||||||
|
|
||||||
const resolved = mode === "true" ? "auto" : mode === "false" ? "off" : mode;
|
const resolved = mode === "true" ? "auto" : mode === "false" ? "off" : mode;
|
||||||
@@ -420,7 +411,7 @@ async function handle247(ctx, message, value) {
|
|||||||
if (resolved === "off") {
|
if (resolved === "off") {
|
||||||
if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer")));
|
if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer")));
|
||||||
|
|
||||||
const channelId = ctx.players.checkVoiceChannels(message);
|
const { channelId } = await ctx.players.checkVoiceChannels(message);
|
||||||
const channels = get247Channels(set);
|
const channels = get247Channels(set);
|
||||||
|
|
||||||
if (channelId) {
|
if (channelId) {
|
||||||
@@ -474,7 +465,7 @@ async function handle247(ctx, message, value) {
|
|||||||
|
|
||||||
if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer")));
|
if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer")));
|
||||||
|
|
||||||
const userChannelId = ctx.players.checkVoiceChannels(message);
|
const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message);
|
||||||
if (!userChannelId) {
|
if (!userChannelId) {
|
||||||
return message.reply(embed(
|
return message.reply(embed(
|
||||||
ctx.t(message, "responses.settings.noVoice247", { mode: resolved, prefix: ctx.handler.getPrefix(guildId) })
|
ctx.t(message, "responses.settings.noVoice247", { mode: resolved, prefix: ctx.handler.getPrefix(guildId) })
|
||||||
@@ -554,7 +545,7 @@ async function applySet(ctx, message, set, key, rawValue) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
set.set(key, rawValue);
|
set.set(key, rawValue);
|
||||||
const guildId = getGuildId(message);
|
const guildId = getMessageGuildId(message);
|
||||||
if (guildId) ctx.locale.invalidateCache(guildId);
|
if (guildId) ctx.locale.invalidateCache(guildId);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -583,7 +574,7 @@ async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
|||||||
if (valueTokens.length === 0) {
|
if (valueTokens.length === 0) {
|
||||||
if (settingKey === "stay_247") {
|
if (settingKey === "stay_247") {
|
||||||
const t247 = ctx.locale?.translate?.bind(ctx.locale);
|
const t247 = ctx.locale?.translate?.bind(ctx.locale);
|
||||||
return message.reply(build247StatusPanel(set, ctx, message, t247, getGuildId(message)));
|
return message.reply(build247StatusPanel(set, ctx, message, t247, getMessageGuildId(message)));
|
||||||
}
|
}
|
||||||
const val = set.get(settingKey);
|
const val = set.get(settingKey);
|
||||||
return message.reply(embed(`\`${settingKey}\` → ${displayValue(settingKey, val)}`));
|
return message.reply(embed(`\`${settingKey}\` → ${displayValue(settingKey, val)}`));
|
||||||
@@ -695,6 +686,12 @@ export const command = function() {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the settings command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const set = this.getSettings(message);
|
const set = this.getSettings(message);
|
||||||
const cmd = data.commandId || "getSettings";
|
const cmd = data.commandId || "getSettings";
|
||||||
@@ -744,11 +741,11 @@ export async function run(message, data) {
|
|||||||
if (settingKey) {
|
if (settingKey) {
|
||||||
if (settingKey === "stay_247") {
|
if (settingKey === "stay_247") {
|
||||||
const t247 = this.locale?.translate?.bind(this.locale);
|
const t247 = this.locale?.translate?.bind(this.locale);
|
||||||
return message.reply(build247StatusPanel(set, this, message, t247, getGuildId(message)));
|
return message.reply(build247StatusPanel(set, this, message, t247, getMessageGuildId(message)));
|
||||||
}
|
}
|
||||||
const val = set.get(settingKey);
|
const val = set.get(settingKey);
|
||||||
const description = this.settingsMgr.descriptions?.[settingKey];
|
const description = this.settingsMgr.descriptions?.[settingKey];
|
||||||
const prefix = ctx.handler.getPrefix(guildId);
|
const prefix = this.handler.getPrefix(guildId);
|
||||||
const resolvedDesc = description ? description.replace(/\$prefix/gi, prefix) : null;
|
const resolvedDesc = description ? description.replace(/\$prefix/gi, prefix) : null;
|
||||||
let reply = `**${prettifySettingLabel(settingKey)}**\nValue: ${displayValue(settingKey, val)}`;
|
let reply = `**${prettifySettingLabel(settingKey)}**\nValue: ${displayValue(settingKey, val)}`;
|
||||||
if (resolvedDesc) reply += `\n\n*${resolvedDesc}*`;
|
if (resolvedDesc) reply += `\n\n*${resolvedDesc}*`;
|
||||||
@@ -766,7 +763,7 @@ export async function run(message, data) {
|
|||||||
.filter(([k]) => k !== "stay_247_mode")
|
.filter(([k]) => k !== "stay_247_mode")
|
||||||
.map(([k]) => {
|
.map(([k]) => {
|
||||||
if (k === "stay_247") {
|
if (k === "stay_247") {
|
||||||
return `• **24/7 mode** — ${format247Status(set, this.locale?.translate?.bind(this.locale), getGuildId(message))}`;
|
return `• **24/7 mode** — ${format247Status(set, this.locale?.translate?.bind(this.locale), getMessageGuildId(message))}`;
|
||||||
}
|
}
|
||||||
return `• **${prettifySettingLabel(k)}** — ${displayValue(k, d[k])}`;
|
return `• **${prettifySettingLabel(k)}** — ${displayValue(k, d[k])}`;
|
||||||
});
|
});
|
||||||
@@ -784,7 +781,7 @@ export async function run(message, data) {
|
|||||||
}
|
}
|
||||||
set.reset(settingKey);
|
set.reset(settingKey);
|
||||||
if (settingKey === "locale") {
|
if (settingKey === "locale") {
|
||||||
const guildId = getGuildId(message);
|
const guildId = getMessageGuildId(message);
|
||||||
if (guildId) this.locale.invalidateCache(guildId);
|
if (guildId) this.locale.invalidateCache(guildId);
|
||||||
}
|
}
|
||||||
const def = set.get(settingKey);
|
const def = set.get(settingKey);
|
||||||
@@ -827,7 +824,7 @@ export async function run(message, data) {
|
|||||||
return message.reply(embed(
|
return message.reply(embed(
|
||||||
`**⚙️ Setting: \`${settingKey}\`**\n\n` +
|
`**⚙️ Setting: \`${settingKey}\`**\n\n` +
|
||||||
`${description}${extra}\n\n` +
|
`${description}${extra}\n\n` +
|
||||||
`**Current value:** ${settingKey === "stay_247" ? format247Status(set, this.locale?.translate?.bind(this.locale), getGuildId(message)) : displayValue(settingKey, currentVal)}\n` +
|
`**Current value:** ${settingKey === "stay_247" ? format247Status(set, this.locale?.translate?.bind(this.locale), getMessageGuildId(message)) : displayValue(settingKey, currentVal)}\n` +
|
||||||
`**Default:** ${displayValue(settingKey, defaultVal)}`,
|
`**Default:** ${displayValue(settingKey, defaultVal)}`,
|
||||||
{ title: `⚙️ ${settingKey}` }
|
{ title: `⚙️ ${settingKey}` }
|
||||||
));
|
));
|
||||||
|
|||||||
+11
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file shuffle.mjs — Shuffle the current queue
|
||||||
|
* @module commands.shuffle
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -7,6 +12,11 @@ export const command = new CommandBuilder()
|
|||||||
.setDescription("Re-orders the queue randomly.", "commands.shuffle")
|
.setDescription("Re-orders the queue randomly.", "commands.shuffle")
|
||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the shuffle command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message, false, true, false);
|
const p = await this.getPlayer(message, false, true, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -15,5 +25,5 @@ export async function run(message) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(res)
|
.setDescription(res)
|
||||||
;
|
;
|
||||||
message.reply({ embeds: [embed] });
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+11
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file skip.mjs — Skip the currently playing song
|
||||||
|
* @module commands.skip
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -8,6 +13,11 @@ export const command = new CommandBuilder()
|
|||||||
.addAliases("s")
|
.addAliases("s")
|
||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the skip command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message);
|
const p = await this.getPlayer(message);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -30,5 +40,5 @@ export async function run(message) {
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(desc)
|
.setDescription(desc)
|
||||||
;
|
;
|
||||||
message.reply({ embeds: [embed] });
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+12
-1
@@ -1,7 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* @file stats.mjs — Display bot statistics — uptime, servers, users, and memory usage
|
||||||
|
* @module commands.stats
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/Utils.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
|
import { logger } from "../src/constants/Logger.mjs";
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("stats")
|
.setName("stats")
|
||||||
@@ -162,6 +168,11 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
|
|||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the stats command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const lastfm = this.lastfm;
|
const lastfm = this.lastfm;
|
||||||
const lastfmEnabled = lastfm?.enabled ?? false;
|
const lastfmEnabled = lastfm?.enabled ?? false;
|
||||||
@@ -199,5 +210,5 @@ export async function run(message) {
|
|||||||
|
|
||||||
await msg.edit({
|
await msg.edit({
|
||||||
embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, guildCount, userCount: users, scrobbleCount, linkedUsers, ping, loading: false })]
|
embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, guildCount, userCount: users, scrobbleCount, linkedUsers, ping, loading: false })]
|
||||||
}).catch((err) => console.error("[stats] editEmbed failed:", err));
|
}).catch((err) => logger.error("[stats] editEmbed failed:", err));
|
||||||
}
|
}
|
||||||
+11
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file support.mjs — Show support server invite link
|
||||||
|
* @module commands.support
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -8,6 +13,11 @@ export const command = new CommandBuilder()
|
|||||||
.addAliases("server")
|
.addAliases("server")
|
||||||
.setCategory("util");
|
.setCategory("util");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* run function.
|
||||||
|
* @param {{*}} msg
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
export function run(msg) {
|
export function run(msg) {
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
@@ -16,5 +26,5 @@ export function run(msg) {
|
|||||||
this.t(msg, "responses.support.description")
|
this.t(msg, "responses.support.description")
|
||||||
)
|
)
|
||||||
;
|
;
|
||||||
msg.reply({ embeds: [embed] });
|
msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+13
-2
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file test.mjs — Test/debug command for voice channel user detection
|
||||||
|
* @module commands.test
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -7,6 +12,12 @@ export const command = new CommandBuilder()
|
|||||||
.setDescription("Shows how many people are in each voice channel.")
|
.setDescription("Shows how many people are in each voice channel.")
|
||||||
.setRequirement(r => r.setOwnerOnly(true));
|
.setRequirement(r => r.setOwnerOnly(true));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the test command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const guild = msg.channel?.channel?.guild ?? msg.message?.guild;
|
const guild = msg.channel?.channel?.guild ?? msg.message?.guild;
|
||||||
if (!guild) {
|
if (!guild) {
|
||||||
@@ -56,7 +67,7 @@ export async function run(msg, data) {
|
|||||||
try {
|
try {
|
||||||
const fetched = await this.client.channels.fetch(channelId);
|
const fetched = await this.client.channels.fetch(channelId);
|
||||||
if (fetched?.name) return fetched.name;
|
if (fetched?.name) return fetched.name;
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
return `Unknown (${channelId})`;
|
return `Unknown (${channelId})`;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -73,5 +84,5 @@ export async function run(msg, data) {
|
|||||||
.setTitle(this.t(msg, "responses.test.title"))
|
.setTitle(this.t(msg, "responses.test.title"))
|
||||||
.setDescription(desc.trim().slice(0, 4096))
|
.setDescription(desc.trim().slice(0, 4096))
|
||||||
;
|
;
|
||||||
msg.reply({ embeds: [embed] });
|
msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+11
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file thumbnail.mjs — Get the thumbnail image for the current or specified track
|
||||||
|
* @module commands.thumbnail
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
@@ -8,6 +13,11 @@ export const command = new CommandBuilder()
|
|||||||
.addAliases("thumb")
|
.addAliases("thumb")
|
||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the thumbnail command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg) {
|
export async function run(msg) {
|
||||||
const p = await this.getPlayer(msg);
|
const p = await this.getPlayer(msg);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -18,5 +28,5 @@ export async function run(msg) {
|
|||||||
.setDescription(data.msg);
|
.setDescription(data.msg);
|
||||||
if (data.image) embed.setImage(data.image);
|
if (data.image) embed.setImage(data.image);
|
||||||
|
|
||||||
msg.reply({ embeds: [embed] });
|
msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+64
-61
@@ -1,7 +1,14 @@
|
|||||||
|
/**
|
||||||
|
* @file trackopt.mjs — Manage per-track options — auto-seek start position and end-time timer
|
||||||
|
* @module commands.trackopt
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
|
import { Utils } from "../src/Utils.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/constants/Logger.mjs";
|
||||||
|
import { ERROR_COLOR } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
const DEFAULT_ALIAS = "default";
|
const DEFAULT_ALIAS = "default";
|
||||||
|
|
||||||
@@ -51,35 +58,6 @@ export const command = new CommandBuilder()
|
|||||||
)
|
)
|
||||||
.addAlias("to");
|
.addAlias("to");
|
||||||
|
|
||||||
function parseTimeInput(str) {
|
|
||||||
if (!str || typeof str !== "string") return null;
|
|
||||||
str = str.trim();
|
|
||||||
if (/^\d+$/.test(str)) return parseInt(str, 10) * 1000;
|
|
||||||
const parts = str.split(":").map(Number);
|
|
||||||
if (parts.some(isNaN)) return null;
|
|
||||||
if (parts.length === 2) {
|
|
||||||
const [minutes, seconds] = parts;
|
|
||||||
if (seconds >= 60) return null;
|
|
||||||
return (minutes * 60 + seconds) * 1000;
|
|
||||||
}
|
|
||||||
if (parts.length === 3) {
|
|
||||||
const [hours, minutes, seconds] = parts;
|
|
||||||
if (minutes >= 60 || seconds >= 60) return null;
|
|
||||||
return (hours * 3600 + minutes * 60 + seconds) * 1000;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatMs(ms) {
|
|
||||||
if (ms == null || ms < 0) return "0:00";
|
|
||||||
const totalSeconds = Math.floor(ms / 1000);
|
|
||||||
const hours = Math.floor(totalSeconds / 3600);
|
|
||||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
|
||||||
const seconds = totalSeconds % 60;
|
|
||||||
if (hours > 0) return `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
|
|
||||||
return `${minutes}:${String(seconds).padStart(2, "0")}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function extractAlias(parts) {
|
function extractAlias(parts) {
|
||||||
for (let i = 0; i < parts.length; i++) {
|
for (let i = 0; i < parts.length; i++) {
|
||||||
if (parts[i].toLowerCase().startsWith("alias:")) {
|
if (parts[i].toLowerCase().startsWith("alias:")) {
|
||||||
@@ -91,10 +69,16 @@ function extractAlias(parts) {
|
|||||||
return DEFAULT_ALIAS;
|
return DEFAULT_ALIAS;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the trackopt command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const trackOpts = this.trackOptions;
|
const trackOpts = this.trackOptions;
|
||||||
if (!trackOpts) {
|
if (!trackOpts) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.notAvailable"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notAvailable"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const subCommand = data.command.name || data.commandId || "get";
|
const subCommand = data.command.name || data.commandId || "get";
|
||||||
@@ -104,12 +88,12 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
const current = p.queue?.getCurrent();
|
const current = p.queue?.getCurrent();
|
||||||
if (!current && subCommand !== "list") {
|
if (!current && subCommand !== "list") {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.nothingPlaying"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.nothingPlaying"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const userId = msg.message?.author?.id ?? msg.author?.id;
|
const userId = msg.message?.author?.id ?? msg.author?.id;
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses._common.noVoiceChannel"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses._common.noVoiceChannel"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const prefix = this.handler.getPrefix(msg.message?.guildId);
|
const prefix = this.handler.getPrefix(msg.message?.guildId);
|
||||||
@@ -117,49 +101,57 @@ export async function run(msg, data) {
|
|||||||
if (subCommand === "set") {
|
if (subCommand === "set") {
|
||||||
const timesRaw = data.get("times")?.value;
|
const timesRaw = data.get("times")?.value;
|
||||||
if (!timesRaw) {
|
if (!timesRaw) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const parts = timesRaw.trim().split(/\s+/);
|
const parts = timesRaw.trim().split(/\s+/);
|
||||||
const aliasRaw = extractAlias(parts);
|
const aliasRaw = extractAlias(parts);
|
||||||
|
|
||||||
const startMs = parseTimeInput(parts[0]);
|
const startMs = Utils.parseDuration(parts[0]);
|
||||||
if (startMs === null || startMs < 0) {
|
if (!startMs || startMs < 0) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
let endMs = 0;
|
let endMs = 0;
|
||||||
if (parts.length > 1) {
|
if (parts.length > 1) {
|
||||||
endMs = parseTimeInput(parts[1]);
|
endMs = Utils.parseDuration(parts[1]);
|
||||||
if (endMs === null || endMs <= 0) {
|
if (!endMs || endMs <= 0) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] });
|
||||||
}
|
}
|
||||||
if (endMs <= startMs) {
|
if (endMs <= startMs) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidEndAfterStart"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidEndAfterStart"))] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const trackDuration = p._getTrackDurationMs(current);
|
const trackDuration = p._getTrackDurationMs(current);
|
||||||
if (trackDuration > 0) {
|
if (trackDuration > 0) {
|
||||||
if (startMs >= trackDuration) {
|
if (startMs >= trackDuration) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.startExceedsDuration", { duration: formatMs(trackDuration) }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.startExceedsDuration", { duration: Utils.prettifyMS(trackDuration) }))] });
|
||||||
}
|
}
|
||||||
if (endMs > 0 && endMs > trackDuration) {
|
if (endMs > 0 && endMs > trackDuration) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.endExceedsDuration", { duration: formatMs(trackDuration) }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.endExceedsDuration", { duration: Utils.prettifyMS(trackDuration) }))] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await trackOpts.set(userId, current, startMs, endMs, aliasRaw);
|
const result = await trackOpts.set(userId, current, startMs, endMs, aliasRaw);
|
||||||
if (!result) {
|
if (!result) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.saveFailed"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.saveFailed"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const endLabel = endMs > 0 ? formatMs(endMs) : "full track";
|
if (result.alias === DEFAULT_ALIAS && p.connection && !p._paused && startMs > 0) {
|
||||||
|
try {
|
||||||
|
await p.applyTrackOption({ startMs, endMs, alias: result.alias, userId });
|
||||||
|
} catch (applyErr) {
|
||||||
|
logger.warn("[trackopt] Auto-apply after set failed:", applyErr.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const endLabel = endMs > 0 ? Utils.prettifyMS(endMs) : "full track";
|
||||||
let desc;
|
let desc;
|
||||||
if (result.alias === DEFAULT_ALIAS) {
|
if (result.alias === DEFAULT_ALIAS) {
|
||||||
desc = this.t(msg, "responses.trackopt.saved", { title: current.title, aliasLabel: "", start: formatMs(startMs), end: endLabel });
|
desc = this.t(msg, "responses.trackopt.saved", { title: current.title, aliasLabel: "", start: Utils.prettifyMS(startMs), end: endLabel });
|
||||||
} else {
|
} else {
|
||||||
desc = this.t(msg, "responses.trackopt.savedAlias", { title: current.title, alias: result.alias, start: formatMs(startMs), end: endLabel, prefix });
|
desc = this.t(msg, "responses.trackopt.savedAlias", { title: current.title, alias: result.alias, start: Utils.prettifyMS(startMs), end: endLabel, prefix });
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
|
||||||
@@ -168,15 +160,15 @@ export async function run(msg, data) {
|
|||||||
if (subCommand === "get") {
|
if (subCommand === "get") {
|
||||||
const rows = await trackOpts.getAllForTrack(userId, current);
|
const rows = await trackOpts.getAllForTrack(userId, current);
|
||||||
if (!rows || rows.length === 0) {
|
if (!rows || rows.length === 0) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.notSet", { title: current.title }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notSet", { title: current.title }))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
let desc = this.t(msg, "responses.trackopt.current", { title: current.title, count: rows.length }) + "\n\n";
|
let desc = this.t(msg, "responses.trackopt.current", { title: current.title, count: rows.length }) + "\n\n";
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
const aliasLabel = row.alias === DEFAULT_ALIAS ? "default" : row.alias;
|
const aliasLabel = row.alias === DEFAULT_ALIAS ? "default" : row.alias;
|
||||||
const endStr = row.end_ms > 0 ? formatMs(row.end_ms) : "end";
|
const endStr = row.end_ms > 0 ? Utils.prettifyMS(row.end_ms) : "end";
|
||||||
const autoTag = row.alias === DEFAULT_ALIAS ? " ← auto" : "";
|
const autoTag = row.alias === DEFAULT_ALIAS ? " ← auto" : "";
|
||||||
desc += this.t(msg, "responses.trackopt.currentEntry", { alias: aliasLabel, start: formatMs(row.start_ms), end: endStr, autoTag }) + "\n";
|
desc += this.t(msg, "responses.trackopt.currentEntry", { alias: aliasLabel, start: Utils.prettifyMS(row.start_ms), end: endStr, autoTag }) + "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
|
||||||
@@ -185,12 +177,12 @@ export async function run(msg, data) {
|
|||||||
if (subCommand === "play") {
|
if (subCommand === "play") {
|
||||||
const aliasRaw = data.get("alias")?.value;
|
const aliasRaw = data.get("alias")?.value;
|
||||||
if (!aliasRaw) {
|
if (!aliasRaw) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.provideAlias", { prefix }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.provideAlias", { prefix }))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const safeAlias = aliasRaw.toLowerCase().replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 32);
|
const safeAlias = aliasRaw.toLowerCase().replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 32);
|
||||||
if (!safeAlias) {
|
if (!safeAlias) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidAlias"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidAlias"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await trackOpts.get(userId, current, safeAlias);
|
const result = await trackOpts.get(userId, current, safeAlias);
|
||||||
@@ -198,26 +190,26 @@ export async function run(msg, data) {
|
|||||||
const allAliases = await trackOpts.getAllForTrack(userId, current);
|
const allAliases = await trackOpts.getAllForTrack(userId, current);
|
||||||
if (allAliases.length > 0) {
|
if (allAliases.length > 0) {
|
||||||
const names = allAliases.map(r => r.alias === DEFAULT_ALIAS ? "default" : r.alias).join(", ");
|
const names = allAliases.map(r => r.alias === DEFAULT_ALIAS ? "default" : r.alias).join(", ");
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.aliasNotFound", { alias: safeAlias, title: current.title, names }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.aliasNotFound", { alias: safeAlias, title: current.title, names }))] });
|
||||||
}
|
}
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.notFound", { title: current.title }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notFound", { title: current.title }))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!p.connection || p._paused) {
|
if (!p.connection || p._paused) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.mustBePlaying"))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.mustBePlaying"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const applied = await p.applyTrackOption(result);
|
const applied = await p.applyTrackOption(result);
|
||||||
if (!applied) {
|
if (!applied) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: "Unknown error" }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: "Unknown error" }))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const aliasLabel = safeAlias === DEFAULT_ALIAS ? "default" : safeAlias;
|
const aliasLabel = safeAlias === DEFAULT_ALIAS ? "default" : safeAlias;
|
||||||
const endStr = result.endMs > 0 ? formatMs(result.endMs) : "end";
|
const endStr = result.endMs > 0 ? Utils.prettifyMS(result.endMs) : "end";
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.applied", { alias: aliasLabel, start: formatMs(result.startMs), end: endStr }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.applied", { alias: aliasLabel, start: Utils.prettifyMS(result.startMs), end: endStr }))] });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: e.message }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: e.message }))] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -225,7 +217,18 @@ export async function run(msg, data) {
|
|||||||
const aliasRaw = data.get("alias")?.value;
|
const aliasRaw = data.get("alias")?.value;
|
||||||
const removed = await trackOpts.remove(userId, current, aliasRaw || null);
|
const removed = await trackOpts.remove(userId, current, aliasRaw || null);
|
||||||
if (!removed) {
|
if (!removed) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.notFound", { title: current.title }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notFound", { title: current.title }))] });
|
||||||
|
}
|
||||||
|
if (p._activeTrackOpt) {
|
||||||
|
const removeDefault = !aliasRaw || aliasRaw.toLowerCase() === DEFAULT_ALIAS;
|
||||||
|
const activeIsDefault = p._activeTrackOpt.alias === DEFAULT_ALIAS;
|
||||||
|
if (removeDefault && activeIsDefault) {
|
||||||
|
p._activeTrackOpt = null;
|
||||||
|
p._clearTrackEndTimer();
|
||||||
|
} else if (aliasRaw && p._activeTrackOpt.alias === aliasRaw.toLowerCase()) {
|
||||||
|
p._activeTrackOpt = null;
|
||||||
|
p._clearTrackEndTimer();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (aliasRaw) {
|
if (aliasRaw) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.removedAlias", { alias: aliasRaw, title: current.title }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.removedAlias", { alias: aliasRaw, title: current.title }))] });
|
||||||
@@ -244,14 +247,14 @@ export async function run(msg, data) {
|
|||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
const title = row.track_title || row.track_identifier;
|
const title = row.track_title || row.track_identifier;
|
||||||
const aliasLabel = row.alias === DEFAULT_ALIAS ? "default" : row.alias;
|
const aliasLabel = row.alias === DEFAULT_ALIAS ? "default" : row.alias;
|
||||||
const endStr = row.end_ms > 0 ? formatMs(row.end_ms) : "end";
|
const endStr = row.end_ms > 0 ? Utils.prettifyMS(row.end_ms) : "end";
|
||||||
if (title !== lastTrack) {
|
if (title !== lastTrack) {
|
||||||
if (lastTrack) desc += "\n";
|
if (lastTrack) desc += "\n";
|
||||||
desc += `🎵 **${title}**\n`;
|
desc += `🎵 **${title}**\n`;
|
||||||
lastTrack = title;
|
lastTrack = title;
|
||||||
}
|
}
|
||||||
const autoTag = row.alias === DEFAULT_ALIAS ? " ← auto" : "";
|
const autoTag = row.alias === DEFAULT_ALIAS ? " ← auto" : "";
|
||||||
desc += ` • ${aliasLabel}: ${formatMs(row.start_ms)} → ${endStr}${autoTag}\n`;
|
desc += ` • ${aliasLabel}: ${Utils.prettifyMS(row.start_ms)} → ${endStr}${autoTag}\n`;
|
||||||
}
|
}
|
||||||
desc += "\n" + this.t(msg, "responses.trackopt.listHint", { prefix });
|
desc += "\n" + this.t(msg, "responses.trackopt.listHint", { prefix });
|
||||||
|
|
||||||
|
|||||||
+13
-2
@@ -1,8 +1,13 @@
|
|||||||
|
/**
|
||||||
|
* @file volume.mjs — Set or view the playback volume
|
||||||
|
* @module commands.volume
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
|
import { MAX_VOLUME } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
const MAX_VOLUME = 200;
|
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("volume")
|
.setName("volume")
|
||||||
@@ -15,6 +20,12 @@ export const command = new CommandBuilder()
|
|||||||
)
|
)
|
||||||
.addAliases("v", "vol");
|
.addAliases("v", "vol");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the volume command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -37,5 +48,5 @@ export async function run(message, data) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
message.reply({ embeds: [embed] });
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,14 @@
|
|||||||
|
/**
|
||||||
|
* @file volumedefault.mjs — Set the default volume for the server
|
||||||
|
* @module commands.volumedefault
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { PermissionFlags } from "@fluxerjs/core";
|
import { PermissionFlags } from "@fluxerjs/core";
|
||||||
|
import { MAX_VOLUME } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
const MAX_VOLUME = 200;
|
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("volumedefault")
|
.setName("volumedefault")
|
||||||
@@ -16,6 +21,12 @@ export const command = new CommandBuilder()
|
|||||||
)
|
)
|
||||||
.addAliases("vd");
|
.addAliases("vd");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the volumedefault command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
@@ -61,5 +72,5 @@ export async function run(message, data) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
message.reply({ embeds: [embed] });
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+23
-12
@@ -1,10 +1,15 @@
|
|||||||
|
/**
|
||||||
|
* @file vote.mjs — Skip-vote system — start a vote to skip the current track
|
||||||
|
* @module commands.vote
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/Utils.mjs";
|
||||||
import { FLUXERLIST, buildVoteLink } from "../src/constants/API.mjs";
|
import { FLUXERLIST, buildVoteLink } from "../src/constants/API.mjs";
|
||||||
|
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||||
|
|
||||||
const EMOJI_REMOVE_TIMEOUT = 60_000;
|
|
||||||
|
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("vote")
|
.setName("vote")
|
||||||
@@ -37,7 +42,7 @@ export const command = new CommandBuilder()
|
|||||||
function notConfigured(prefix, t, guildId) {
|
function notConfigured(prefix, t, guildId) {
|
||||||
return {
|
return {
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor("#ff0000")
|
.setColor(ERROR_COLOR)
|
||||||
.setDescription(t(guildId, "responses.vote.notConfigured"))]
|
.setDescription(t(guildId, "responses.vote.notConfigured"))]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -45,7 +50,7 @@ function notConfigured(prefix, t, guildId) {
|
|||||||
function noResourceId(type, prefix, t, guildId) {
|
function noResourceId(type, prefix, t, guildId) {
|
||||||
return {
|
return {
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor("#ff0000")
|
.setColor(ERROR_COLOR)
|
||||||
.setDescription(t(guildId, "responses.vote.noResourceId", { type, prefix }))]
|
.setDescription(t(guildId, "responses.vote.noResourceId", { type, prefix }))]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -94,6 +99,12 @@ function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired
|
|||||||
return { embeds: [embed] };
|
return { embeds: [embed] };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute the vote command.
|
||||||
|
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||||
|
* @param {Map<string, {value: *}>>} data - Slash-command options map
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const fluxerlist = this.fluxerlist;
|
const fluxerlist = this.fluxerlist;
|
||||||
const prefix = this.handler.getPrefix(msg.message?.guildId);
|
const prefix = this.handler.getPrefix(msg.message?.guildId);
|
||||||
@@ -157,7 +168,7 @@ export async function run(msg, data) {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor("#ff0000")
|
.setColor(ERROR_COLOR)
|
||||||
.setDescription(this.t(msg, "responses.vote.fetchVotersFailed", { error: err.message }))]
|
.setDescription(this.t(msg, "responses.vote.fetchVotersFailed", { error: err.message }))]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -179,11 +190,11 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
let currentPage = voterData.page;
|
let currentPage = voterData.page;
|
||||||
|
|
||||||
const buildPage = (pageIdx, expired = false) => {
|
const buildPage = (pageIdx, data, expired = false) => {
|
||||||
return buildVotersEmbed(voterData.voters, voterData.total, pageIdx, 20, resolvedType, id, expired, t, guildId);
|
return buildVotersEmbed(data.voters, data.total, pageIdx, 20, resolvedType, id, expired, t, guildId);
|
||||||
};
|
};
|
||||||
|
|
||||||
const replyMsg = await msg.reply(buildPage(currentPage));
|
const replyMsg = await msg.reply(buildPage(currentPage, voterData));
|
||||||
if (!replyMsg?.message) return;
|
if (!replyMsg?.message) return;
|
||||||
|
|
||||||
const navEmojis = ["\u25C0\uFE0F", "\u25B6\uFE0F", "\u274C"];
|
const navEmojis = ["\u25C0\uFE0F", "\u25B6\uFE0F", "\u274C"];
|
||||||
@@ -196,18 +207,18 @@ export async function run(msg, data) {
|
|||||||
await replyMsg.message.removeAllReactions();
|
await replyMsg.message.removeAllReactions();
|
||||||
} catch {
|
} catch {
|
||||||
for (const emoji of navEmojis) {
|
for (const emoji of navEmojis) {
|
||||||
try { await replyMsg.message.removeReaction(emoji); } catch {}
|
try { await replyMsg.message.removeReaction(emoji); } catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let emojiTimeout;
|
let emojiTimeout = null;
|
||||||
const resetTimer = () => {
|
const resetTimer = () => {
|
||||||
clearTimeout(emojiTimeout);
|
clearTimeout(emojiTimeout);
|
||||||
emojiTimeout = setTimeout(async () => {
|
emojiTimeout = setTimeout(async () => {
|
||||||
unobserve?.();
|
unobserve?.();
|
||||||
await clearReactions();
|
await clearReactions();
|
||||||
await replyMsg.edit(buildPage(currentPage, true)).catch(() => {});
|
await replyMsg.edit(buildPage(currentPage, voterData, true)).catch(() => {});
|
||||||
}, EMOJI_REMOVE_TIMEOUT);
|
}, EMOJI_REMOVE_TIMEOUT);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -230,10 +241,10 @@ export async function run(msg, data) {
|
|||||||
try {
|
try {
|
||||||
voterData = await fluxerlist.getVoters(resolvedType, id, { page: currentPage, limit: 20 });
|
voterData = await fluxerlist.getVoters(resolvedType, id, { page: currentPage, limit: 20 });
|
||||||
} catch {
|
} catch {
|
||||||
/* keep previous data */
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
await replyMsg.edit(buildPage(currentPage, voterData)).catch(() => {});
|
||||||
});
|
});
|
||||||
|
|
||||||
resetTimer();
|
resetTimer();
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file index.mjs — Fluxer Remix bot — main entry point; initializes client, voice, commands, players, and event handlers
|
||||||
|
* @module index
|
||||||
|
*/
|
||||||
|
|
||||||
import * as fs from "fs";
|
import * as fs from "fs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import { initLogger, logger, _wsErrorCooldown } from "./src/constants/Logger.mjs";
|
import { initLogger, logger, _wsErrorCooldown } from "./src/constants/Logger.mjs";
|
||||||
@@ -5,6 +10,7 @@ import { Client, Events, EmbedBuilder } from "@fluxerjs/core";
|
|||||||
import { get247ChannelMode, remove247ChannelMode } from "./src/constants/Helpers247.mjs";
|
import { get247ChannelMode, remove247ChannelMode } from "./src/constants/Helpers247.mjs";
|
||||||
import { CommandHandler, CommandLoader, PrefixManager } from "./src/CommandHandler.mjs";
|
import { CommandHandler, CommandLoader, PrefixManager } from "./src/CommandHandler.mjs";
|
||||||
import { MessageHandler, PageBuilder, HelpCommand, setGlobalColor, getGlobalColor } from "./src/MessageHandler.mjs";
|
import { MessageHandler, PageBuilder, HelpCommand, setGlobalColor, getGlobalColor } from "./src/MessageHandler.mjs";
|
||||||
|
import { cleanId } from "./src/Utils.mjs";
|
||||||
import { RemoteSettingsManager } from "./src/Settings.mjs";
|
import { RemoteSettingsManager } from "./src/Settings.mjs";
|
||||||
import { PlayerManager } from "./src/PlayerManager.mjs";
|
import { PlayerManager } from "./src/PlayerManager.mjs";
|
||||||
import childProcess from "node:child_process";
|
import childProcess from "node:child_process";
|
||||||
@@ -44,11 +50,10 @@ function createBotView(voiceCache) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Helper — build a plain embed payload from a description string */
|
|
||||||
function mkEmbed(desc) {
|
|
||||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] };
|
|
||||||
}
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remix class.
|
||||||
|
*/
|
||||||
export class Remix {
|
export class Remix {
|
||||||
constructor() {
|
constructor() {
|
||||||
let config;
|
let config;
|
||||||
@@ -94,10 +99,10 @@ export class Remix {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const client = new Client({
|
const client = new Client({
|
||||||
intents: 0,
|
|
||||||
suppressIntentWarning: true,
|
suppressIntentWarning: true,
|
||||||
waitForGuilds: true,
|
waitForGuilds: true,
|
||||||
...config["fluxer.js"],
|
...config["fluxer.js"],
|
||||||
|
intents: 1 << 7,
|
||||||
presence: (() => {
|
presence: (() => {
|
||||||
if (presenceContents.length === 0) return undefined;
|
if (presenceContents.length === 0) return undefined;
|
||||||
const entry = presenceContents[0];
|
const entry = presenceContents[0];
|
||||||
@@ -218,7 +223,7 @@ export class Remix {
|
|||||||
if (!val || val === "none") continue;
|
if (!val || val === "none") continue;
|
||||||
const rawArr = Array.isArray(val) ? val : [val];
|
const rawArr = Array.isArray(val) ? val : [val];
|
||||||
const cleaned = rawArr
|
const cleaned = rawArr
|
||||||
.map(id => String(id).replace(/\D/g, ""))
|
.map(id => cleanId(id))
|
||||||
.filter(id => id.length >= 15 && id.length <= 22);
|
.filter(id => id.length >= 15 && id.length <= 22);
|
||||||
const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val);
|
const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val);
|
||||||
if (needsSave || !Array.isArray(val)) {
|
if (needsSave || !Array.isArray(val)) {
|
||||||
@@ -327,15 +332,14 @@ export class Remix {
|
|||||||
if (player._isJoining) continue;
|
if (player._isJoining) continue;
|
||||||
|
|
||||||
channelId = player._channelId ?? mapKey;
|
channelId = player._channelId ?? mapKey;
|
||||||
const cleanChanId = String(channelId).replace(/\D/g, "");
|
const cleanChanId = cleanId(channelId);
|
||||||
if (!cleanChanId) continue;
|
if (!cleanChanId) continue;
|
||||||
|
|
||||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
const cleanGuildId = cleanId(guildId);
|
||||||
const channelGuildId = String(
|
const channelGuildId = cleanId(
|
||||||
this.client?.channels?.get?.(channelId)?.guildId ??
|
this.client?.channels?.get?.(channelId)?.guildId ??
|
||||||
this.client?.channels?.get?.(channelId)?.guild_id ??
|
this.client?.channels?.get?.(channelId)?.guild_id
|
||||||
""
|
);
|
||||||
).replace(/\D/g, "");
|
|
||||||
if (channelGuildId && channelGuildId !== cleanGuildId) {
|
if (channelGuildId && channelGuildId !== cleanGuildId) {
|
||||||
logger.warn(`[AloneCheck] Skipping inconsistent player state channel=${channelId} playerGuild=${guildId} channelGuild=${channelGuildId}`);
|
logger.warn(`[AloneCheck] Skipping inconsistent player state channel=${channelId} playerGuild=${guildId} channelGuild=${channelGuildId}`);
|
||||||
continue;
|
continue;
|
||||||
@@ -356,7 +360,7 @@ export class Remix {
|
|||||||
? [...voiceStates.values()]
|
? [...voiceStates.values()]
|
||||||
: Object.values(voiceStates);
|
: Object.values(voiceStates);
|
||||||
for (const state of entries) {
|
for (const state of entries) {
|
||||||
const stateChannel = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
const stateChannel = cleanId(state?.channelId ?? state?.channel_id);
|
||||||
if (stateChannel === cleanChanId) {
|
if (stateChannel === cleanChanId) {
|
||||||
const stateUserId = state?.userId ?? state?.user_id ?? state?.id;
|
const stateUserId = state?.userId ?? state?.user_id ?? state?.id;
|
||||||
const member = guild?.members?.get?.(stateUserId);
|
const member = guild?.members?.get?.(stateUserId);
|
||||||
@@ -371,7 +375,7 @@ export class Remix {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hasHuman) {
|
if (!hasHuman) {
|
||||||
@@ -381,7 +385,7 @@ export class Remix {
|
|||||||
hasHuman = true;
|
hasHuman = true;
|
||||||
logger.aloneCheck(`[AloneCheck] Found ${room.remoteParticipants.size} LiveKit remote participant(s) in ${channelId}`);
|
logger.aloneCheck(`[AloneCheck] Found ${room.remoteParticipants.size} LiveKit remote participant(s) in ${channelId}`);
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.aloneCheck(`[AloneCheck] channel=${channelId} guild=${guildId} hasHuman=${hasHuman} paused=${player._paused}`);
|
logger.aloneCheck(`[AloneCheck] channel=${channelId} guild=${guildId} hasHuman=${hasHuman} paused=${player._paused}`);
|
||||||
@@ -405,7 +409,7 @@ export class Remix {
|
|||||||
}, ALONE_CHECK_INTERVAL);
|
}, ALONE_CHECK_INTERVAL);
|
||||||
|
|
||||||
const self = this;
|
const self = this;
|
||||||
this.players.checkVoiceChannels = function (message) {
|
this.players.checkVoiceChannels = async function (message) {
|
||||||
const userId = message?.author?.id ?? message?.message?.author?.id;
|
const userId = message?.author?.id ?? message?.message?.author?.id;
|
||||||
const guildId =
|
const guildId =
|
||||||
message?.channel?.guildId ??
|
message?.channel?.guildId ??
|
||||||
@@ -419,92 +423,108 @@ export class Remix {
|
|||||||
message?.message?.channel?.server_id ??
|
message?.message?.channel?.server_id ??
|
||||||
message?.message?.channel?.serverId;
|
message?.message?.channel?.serverId;
|
||||||
|
|
||||||
logger.voice(`[checkVC] userId=${userId} guildId=${guildId}`);
|
const _empty = { channelId: null, alreadyInVoice: false, hasHumans: false };
|
||||||
logger.voice(`[checkVC] channel keys: ${Object.keys(message?.channel ?? {}).join(",")}`);
|
|
||||||
logger.voice(`[checkVC] voiceCache humans=${self.voiceCache.observedVoiceUsersSize} bots=${self.voiceCache.observedVoiceBotsSize}`);
|
|
||||||
|
|
||||||
if (!userId || !guildId) {
|
if (!userId || !guildId) {
|
||||||
logger.voice(`[checkVC] BAIL — missing userId or guildId`);
|
logger.voice(`[checkVC] BAIL — missing userId or guildId`);
|
||||||
return null;
|
return _empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
const cleanGuild = cleanId(guildId);
|
||||||
|
|
||||||
const seed = (channelId) => {
|
const makeResult = (channelId) => {
|
||||||
|
const cId = cleanId(channelId);
|
||||||
|
return {
|
||||||
|
channelId: cId,
|
||||||
|
alreadyInVoice: self.players.playerMap.has(cId),
|
||||||
|
hasHumans: self.voiceCache.hasHumansInChannel(cleanGuild, cId),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const seedCache = (channelId) => {
|
||||||
if (!self.voiceCache.hasHumanUser(userId, cleanGuild)) {
|
if (!self.voiceCache.hasHumanUser(userId, cleanGuild)) {
|
||||||
self.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false });
|
self.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false });
|
||||||
}
|
}
|
||||||
return self.voiceCache.getUserChannel(cleanGuild, userId) ?? channelId;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
logger.voice(`[checkVC] userId=${userId} guildId=${guildId} cleanGuild=${cleanGuild}`);
|
||||||
|
|
||||||
const observed = self.voiceCache.getUserLocation(cleanGuild, userId);
|
const observed = self.voiceCache.getUserLocation(cleanGuild, userId);
|
||||||
logger.voice(`[checkVC] observed=${JSON.stringify(observed)} cleanGuild=${cleanGuild}`);
|
|
||||||
if (observed && observed.channelId) {
|
if (observed && observed.channelId) {
|
||||||
logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`);
|
logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`);
|
||||||
return observed.channelId;
|
return makeResult(observed.channelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const vm = getVoiceManager(client);
|
const vm = getVoiceManager(client);
|
||||||
const channelId = vm?.getVoiceChannelId?.(guildId, userId);
|
const channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? vm?.getVoiceChannelId?.(cleanGuild, userId);
|
||||||
logger.voice(`[checkVC] vm.getVoiceChannelId → ${channelId}`);
|
logger.voice(`[checkVC] vm.getVoiceChannelId → ${channelId}`);
|
||||||
if (channelId) return seed(channelId);
|
if (channelId) {
|
||||||
|
seedCache(channelId);
|
||||||
|
return makeResult(channelId);
|
||||||
|
}
|
||||||
} catch (e) { logger.voice(`[checkVC] vm error: ${e.message}`); }
|
} catch (e) { logger.voice(`[checkVC] vm error: ${e.message}`); }
|
||||||
|
|
||||||
const memberVoice =
|
|
||||||
message?.member?.voice?.channelId ??
|
|
||||||
message?.message?.member?.voice?.channelId ??
|
|
||||||
null;
|
|
||||||
logger.voice(`[checkVC] memberVoice=${memberVoice}`);
|
|
||||||
if (memberVoice) return seed(memberVoice);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild);
|
const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild);
|
||||||
logger.voice(`[checkVC] guild=${guild?.id ?? guild?._id ?? "null"}`);
|
|
||||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
||||||
logger.voice(`[checkVC] voiceStates=${Array.isArray(voiceStates) ? "array["+voiceStates.length+"]" : typeof voiceStates}`);
|
|
||||||
if (voiceStates) {
|
if (voiceStates) {
|
||||||
if (!Array.isArray(voiceStates) && typeof voiceStates === "object") {
|
|
||||||
const direct = voiceStates[userId];
|
|
||||||
logger.voice(`[checkVC] direct lookup voiceStates[userId]=${JSON.stringify(direct)}`);
|
|
||||||
if (direct) {
|
|
||||||
const sch = typeof direct === "string" ? direct
|
|
||||||
: direct?.channelId ?? direct?.channel_id ?? null;
|
|
||||||
if (sch) { logger.voice(`[checkVC] HIT direct obj lookup → ${sch}`); return seed(sch); }
|
|
||||||
}
|
|
||||||
const firstKey = Object.keys(voiceStates)[0];
|
|
||||||
if (firstKey) {
|
|
||||||
logger.voice(`[checkVC] shape sample: key=${firstKey} val=${JSON.stringify(voiceStates[firstKey])}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const entries = Array.isArray(voiceStates)
|
const entries = Array.isArray(voiceStates)
|
||||||
? voiceStates
|
? voiceStates
|
||||||
: typeof voiceStates.values === "function"
|
: typeof voiceStates.values === "function"
|
||||||
? voiceStates.values()
|
? [...voiceStates.values()]
|
||||||
: Object.values(voiceStates);
|
: Object.values(voiceStates);
|
||||||
for (const state of entries) {
|
for (const state of entries) {
|
||||||
const sid = state?.userId ?? state?.user_id ?? state?.id;
|
const sid = state?.userId ?? state?.user_id ?? state?.id;
|
||||||
const sch = state?.channelId ?? state?.channel_id;
|
const sch = state?.channelId ?? state?.channel_id;
|
||||||
const sgid = String(state?.guildId ?? state?.guild_id ?? guildId).replace(/\D/g, "");
|
if ((sid === userId || sid === cleanId(userId)) && sch) {
|
||||||
logger.voice(`[checkVC] state: sid=${sid} sch=${sch} sgid=${sgid}`);
|
logger.voice(`[checkVC] HIT guild.voice_states → ${sch}`);
|
||||||
if (sid === userId && sgid === cleanGuild && sch) {
|
seedCache(sch);
|
||||||
logger.voice(`[checkVC] HIT guild.voice_states iterate → ${sch}`);
|
return makeResult(sch);
|
||||||
return seed(sch);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); }
|
} catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); }
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const loc = self.voiceCache.getHumanUser(userId);
|
const loc = self.voiceCache.getHumanUser(userId, cleanGuild);
|
||||||
if (loc && String(loc.guildId ?? "").replace(/\D/g, "") === cleanGuild) {
|
if (loc && loc.channelId) {
|
||||||
logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`);
|
logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`);
|
||||||
return loc.channelId;
|
return makeResult(loc.channelId);
|
||||||
}
|
}
|
||||||
} catch (e) { logger.voice(`[checkVC] last-resort error: ${e.message}`); }
|
} catch (e) { logger.voice(`[checkVC] scan error: ${e.message}`); }
|
||||||
|
|
||||||
logger.voice(`[checkVC] MISS — returning null`);
|
try {
|
||||||
return null;
|
const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild);
|
||||||
|
if (guild && typeof guild.fetchMember === "function") {
|
||||||
|
logger.voice(`[checkVC] Trying REST fetchMember fallback for user ${userId}`);
|
||||||
|
const member = await guild.fetchMember(userId);
|
||||||
|
const voiceState = member?.voice ?? member?.voiceState ?? null;
|
||||||
|
const restChannelId = voiceState?.channelId ?? voiceState?.channel_id ?? null;
|
||||||
|
if (restChannelId) {
|
||||||
|
logger.voice(`[checkVC] HIT REST member.voice → ${restChannelId}`);
|
||||||
|
seedCache(restChannelId);
|
||||||
|
return makeResult(restChannelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { logger.voice(`[checkVC] REST fallback error: ${e.message}`); }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild);
|
||||||
|
if (guild && typeof client.rest?.get === "function") {
|
||||||
|
logger.voice(`[checkVC] Trying raw REST /guilds/${cleanGuild}/members/${userId}`);
|
||||||
|
const memberData = await client.rest.get(`/guilds/${cleanGuild}/members/${userId}`);
|
||||||
|
const restChannelId = memberData?.voice_state?.channel_id ?? memberData?.channel_id ?? null;
|
||||||
|
if (restChannelId) {
|
||||||
|
logger.voice(`[checkVC] HIT raw REST → ${restChannelId}`);
|
||||||
|
seedCache(restChannelId);
|
||||||
|
return makeResult(restChannelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { logger.voice(`[checkVC] raw REST error: ${e.message}`); }
|
||||||
|
|
||||||
|
logger.voice(`[checkVC] MISS — returning empty`);
|
||||||
|
return _empty;
|
||||||
};
|
};
|
||||||
|
|
||||||
const __dirname = import.meta.dirname;
|
const __dirname = import.meta.dirname;
|
||||||
@@ -641,13 +661,13 @@ export class Remix {
|
|||||||
}
|
}
|
||||||
|
|
||||||
markIntentionalLeave(channelId, ttlMs = null) {
|
markIntentionalLeave(channelId, ttlMs = null) {
|
||||||
const clean = String(channelId).replace(/\D/g, "");
|
const cleanChId = cleanId(channelId);
|
||||||
if (!clean) return;
|
if (!cleanChId) return;
|
||||||
if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000;
|
if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000;
|
||||||
const existing = this.intentionalLeaves.get(clean);
|
const existing = this.intentionalLeaves.get(cleanChId);
|
||||||
if (existing) clearTimeout(existing);
|
if (existing) clearTimeout(existing);
|
||||||
this.intentionalLeaves.set(clean, setTimeout(() => {
|
this.intentionalLeaves.set(cleanChId, setTimeout(() => {
|
||||||
this.intentionalLeaves.delete(clean);
|
this.intentionalLeaves.delete(cleanChId);
|
||||||
}, ttlMs));
|
}, ttlMs));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -660,8 +680,8 @@ export class Remix {
|
|||||||
* @returns {Promise<Player>} The created player
|
* @returns {Promise<Player>} The created player
|
||||||
*/
|
*/
|
||||||
async _spawnPlayer(guildId, channelId) {
|
async _spawnPlayer(guildId, channelId) {
|
||||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
const cleanGuildId = cleanId(guildId);
|
||||||
const cleanChannelId = String(channelId).replace(/\D/g, "");
|
const cleanChannelId = cleanId(channelId);
|
||||||
|
|
||||||
if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId");
|
if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId");
|
||||||
|
|
||||||
@@ -717,8 +737,8 @@ export class Remix {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const activeChId = String(player._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId;
|
const activeChId = cleanId(player._channelId ?? cleanChannelId) || cleanChannelId;
|
||||||
const homeChId = String(player._home247Channel ?? activeChId).replace(/\D/g, "") || activeChId;
|
const homeChId = cleanId(player._home247Channel ?? activeChId) || activeChId;
|
||||||
this.players.playerMap.delete(activeChId);
|
this.players.playerMap.delete(activeChId);
|
||||||
this.players._unindexPlayer?.(cleanGuildId, activeChId);
|
this.players._unindexPlayer?.(cleanGuildId, activeChId);
|
||||||
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId);
|
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId);
|
||||||
@@ -740,7 +760,7 @@ export class Remix {
|
|||||||
if (!ch || typeof ch.send !== "function") {
|
if (!ch || typeof ch.send !== "function") {
|
||||||
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
|
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
|
||||||
if (savedAnnChId) {
|
if (savedAnnChId) {
|
||||||
ch = this.client?.channels?.get?.(String(savedAnnChId).replace(/\D/g, "")) ?? null;
|
ch = this.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!ch || typeof ch.send !== "function") {
|
if (!ch || typeof ch.send !== "function") {
|
||||||
@@ -764,12 +784,14 @@ export class Remix {
|
|||||||
|
|
||||||
if (!player.textChannel) player.textChannel = ch;
|
if (!player.textChannel) player.textChannel = ch;
|
||||||
|
|
||||||
ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)).catch(err => {
|
ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)] }).catch(err => {
|
||||||
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||||
logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`);
|
logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (_) {}
|
} catch(e) {
|
||||||
|
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (this.players._pendingJoins) {
|
if (this.players._pendingJoins) {
|
||||||
@@ -798,34 +820,34 @@ export class Remix {
|
|||||||
this.players._pendingJoins.delete(cleanChannelId);
|
this.players._pendingJoins.delete(cleanChannelId);
|
||||||
}
|
}
|
||||||
this.players.playerMap.delete(cleanChannelId);
|
this.players.playerMap.delete(cleanChannelId);
|
||||||
try { player.destroy(); } catch (_) {}
|
try { player.destroy(); } catch(e) { }
|
||||||
logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message);
|
logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async leaveChannel(channelId, guildId, message, force = false) {
|
async leaveChannel(channelId, guildId, message, force = false) {
|
||||||
const cleanId = String(channelId).replace(/\D/g, "");
|
const cleanChId = cleanId(channelId);
|
||||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
const cleanGuildId = cleanId(guildId);
|
||||||
const set = this.settingsMgr.getServer(cleanGuildId);
|
const set = this.settingsMgr.getServer(cleanGuildId);
|
||||||
const raw = set?.get("stay_247");
|
const raw = set?.get("stay_247");
|
||||||
|
|
||||||
const channels = (!raw || raw === "none")
|
const channels = (!raw || raw === "none")
|
||||||
? new Set()
|
? new Set()
|
||||||
: Array.isArray(raw)
|
: Array.isArray(raw)
|
||||||
? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean))
|
? new Set(raw.map(id => cleanId(id)).filter(Boolean))
|
||||||
: new Set([String(raw).replace(/\D/g, "")]);
|
: new Set([cleanId(raw)]);
|
||||||
|
|
||||||
const channelMode = channels.has(cleanId) ? get247ChannelMode(set, cleanId) : "off";
|
const channelMode = channels.has(cleanChId) ? get247ChannelMode(set, cleanChId) : "off";
|
||||||
|
|
||||||
if (channels.has(cleanId) && !force) {
|
if (channels.has(cleanChId) && !force) {
|
||||||
if (channelMode === "auto") {
|
if (channelMode === "auto") {
|
||||||
if (message) {
|
if (message) {
|
||||||
const prefix = this.handler.getPrefix(cleanGuildId);
|
const prefix = this.handler.getPrefix(cleanGuildId);
|
||||||
const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId;
|
const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId;
|
||||||
message.replyEmbed(
|
message.replyEmbed(
|
||||||
this.locale.translate(guildIdForLocale, "responses.leave.autoRejoinHint", {
|
this.locale.translate(guildIdForLocale, "responses.leave.autoRejoinHint", {
|
||||||
channel: cleanId,
|
channel: cleanChId,
|
||||||
prefix
|
prefix
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
@@ -834,20 +856,20 @@ export class Remix {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (channels.has(cleanId)) {
|
if (channels.has(cleanChId)) {
|
||||||
channels.delete(cleanId);
|
channels.delete(cleanChId);
|
||||||
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
|
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
|
||||||
remove247ChannelMode(set, cleanId, channels);
|
remove247ChannelMode(set, cleanChId, channels);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.markIntentionalLeave(cleanId);
|
this.markIntentionalLeave(cleanChId);
|
||||||
|
|
||||||
const player = this.players.playerMap.get(cleanId);
|
const player = this.players.playerMap.get(cleanChId);
|
||||||
if (player) {
|
if (player) {
|
||||||
this.players.playerMap.delete(cleanId);
|
this.players.playerMap.delete(cleanChId);
|
||||||
this.players._unindexPlayer(player._guildId, cleanId);
|
this.players._unindexPlayer(player._guildId, cleanChId);
|
||||||
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanId);
|
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChId);
|
||||||
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanId); }
|
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChId); }
|
||||||
await player.leave().catch(() => {});
|
await player.leave().catch(() => {});
|
||||||
player.destroy();
|
player.destroy();
|
||||||
}
|
}
|
||||||
@@ -907,7 +929,7 @@ export class Remix {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!isMember) {
|
if (!isMember) {
|
||||||
const cleanGuildId = String(guild.id).replace(/\D/g, "");
|
const cleanGuildId = cleanId(guild.id);
|
||||||
const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id);
|
const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id);
|
||||||
if (userLoc) isMember = true;
|
if (userLoc) isMember = true;
|
||||||
}
|
}
|
||||||
@@ -916,7 +938,7 @@ export class Remix {
|
|||||||
try {
|
try {
|
||||||
const member = await guild.members.fetch(user.id).catch(() => null);
|
const member = await guild.members.fetch(user.id).catch(() => null);
|
||||||
if (member) isMember = true;
|
if (member) isMember = true;
|
||||||
} catch (_) { /* not a member or fetch failed */ }
|
} catch (_) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isMember) continue;
|
if (!isMember) continue;
|
||||||
|
|||||||
+1
-4
@@ -7,16 +7,13 @@
|
|||||||
"@fluxerjs/core": "^1.3.1",
|
"@fluxerjs/core": "^1.3.1",
|
||||||
"@fluxerjs/voice": "^1.3.1",
|
"@fluxerjs/voice": "^1.3.1",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"express": "^5.2.1",
|
|
||||||
"ffmpeg-static": "^5.3.0",
|
"ffmpeg-static": "^5.3.0",
|
||||||
"ffprobe-static": "^3.1.0",
|
"ffprobe-static": "^3.1.0",
|
||||||
"follow-redirects": "^1.16.0",
|
"follow-redirects": "^1.16.0",
|
||||||
"genius-lyrics": "^4.4.7",
|
|
||||||
"moonlink.js": "^5.2.0",
|
"moonlink.js": "^5.2.0",
|
||||||
"mysql2": "^3.9.0",
|
"mysql2": "^3.9.0",
|
||||||
"redis": "^5.12.1",
|
"redis": "^5.12.1",
|
||||||
"revoice.js": "^0.2.1696",
|
"revoice.js": "^0.2.1696"
|
||||||
"ws": "^8.20.0"
|
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "node --inspect index.mjs --trace-warnings",
|
"dev": "node --inspect index.mjs --trace-warnings",
|
||||||
|
|||||||
+9
-289
@@ -1,290 +1,10 @@
|
|||||||
import { EventEmitter } from "node:events";
|
/**
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
* @file Settings.mjs — Dashboard Settings — server-side settings manager for the web dashboard
|
||||||
import * as fs from "node:fs";
|
* @module settings.Settings
|
||||||
import * as mysql from "mysql2";
|
*/
|
||||||
|
|
||||||
export class ServerSettings {
|
/**
|
||||||
/** @type {string} */
|
* Re-exports from src/Settings.mjs for backward compatibility.
|
||||||
id;
|
* The canonical definitions now live in src/Settings.mjs.
|
||||||
/** @type {SettingsManager} */
|
*/
|
||||||
manager;
|
export { SettingsManager, ServerSettings, RemoteSettingsManager } from "../src/Settings.mjs";
|
||||||
data = {};
|
|
||||||
|
|
||||||
constructor(id, mgr) {
|
|
||||||
this.id = id; this.manager = mgr;
|
|
||||||
this.loadDefaults();
|
|
||||||
}
|
|
||||||
set(key, value) { this.data[key] = value; this.manager.update(this, key); }
|
|
||||||
get(key) { return this.data[key]; }
|
|
||||||
reset(key) { return this.set(key, this.manager.defaults[key]); }
|
|
||||||
getAll() { return this.data; }
|
|
||||||
loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } }
|
|
||||||
checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
|
|
||||||
deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } }
|
|
||||||
get serializationData() { return { ...this.data, id: this.id }; }
|
|
||||||
serialize() { return this.serializationData; }
|
|
||||||
serializeObject() { return this.serializationData; }
|
|
||||||
}
|
|
||||||
|
|
||||||
export class SettingsManager extends EventEmitter {
|
|
||||||
/** @abstract @type {Object} */
|
|
||||||
defaults;
|
|
||||||
/** @abstract */
|
|
||||||
update(server, key) { }
|
|
||||||
/** @abstract @returns {ServerSettings} */
|
|
||||||
getServer(id) { }
|
|
||||||
/** @abstract @returns {boolean} */
|
|
||||||
hasServer(id) { }
|
|
||||||
/** @abstract @returns {boolean} */
|
|
||||||
isOption(key) { }
|
|
||||||
}
|
|
||||||
|
|
||||||
export class MySqlSettingsManager extends SettingsManager {
|
|
||||||
guilds = new Map();
|
|
||||||
descriptions = {};
|
|
||||||
defaults = {};
|
|
||||||
db = null;
|
|
||||||
/** @type {string|null} Bot user ID — used to isolate rows per-bot in shared databases */
|
|
||||||
botId = null;
|
|
||||||
/** @type {boolean} Whether the bot_id column exists in the settings table */
|
|
||||||
_hasBotIdColumn = false;
|
|
||||||
/** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */
|
|
||||||
_loadPromise = null;
|
|
||||||
_debounceTimers = new Map();
|
|
||||||
|
|
||||||
constructor(config, defaultsPath, botId = null) {
|
|
||||||
super();
|
|
||||||
this.botId = botId;
|
|
||||||
this.db = mysql.createPool({ connectionLimit: 15, ...config });
|
|
||||||
this.db.on("error", (err) => {
|
|
||||||
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
|
|
||||||
});
|
|
||||||
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
|
|
||||||
this._loadPromise = this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check whether the `bot_id` column exists in the settings table AND is
|
|
||||||
* part of the primary key. If the column is missing, auto-migrate by
|
|
||||||
* adding it (NOT NULL DEFAULT '') and updating the primary key to (id, bot_id).
|
|
||||||
* If the column exists but isn't in the PK (previous failed migration),
|
|
||||||
* fix the NULL values and retry the PK update.
|
|
||||||
*
|
|
||||||
* Key detail: MySQL primary key columns CANNOT be NULL. The previous version
|
|
||||||
* used DEFAULT NULL which caused ALTER TABLE ... ADD PRIMARY KEY to fail
|
|
||||||
* silently, leaving the PK as just (id) and producing ER_DUP_ENTRY errors
|
|
||||||
* when two bots tried to INSERT rows for the same guild.
|
|
||||||
*/
|
|
||||||
async _ensureBotIdColumn() {
|
|
||||||
if (this._hasBotIdColumn) return;
|
|
||||||
|
|
||||||
const res = await this.query(
|
|
||||||
`SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS `
|
|
||||||
+ `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'`
|
|
||||||
);
|
|
||||||
|
|
||||||
if (res.error) {
|
|
||||||
logger.error("[Settings] Failed to check bot_id column:", res.error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (res.results.length === 0) {
|
|
||||||
logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table...");
|
|
||||||
|
|
||||||
const alterRes = await this.query(
|
|
||||||
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`
|
|
||||||
);
|
|
||||||
if (alterRes.error) {
|
|
||||||
logger.error("[Settings] Failed to add bot_id column:", alterRes.error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.botId) {
|
|
||||||
await this.query(
|
|
||||||
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const pkRes = await this.query(
|
|
||||||
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
|
||||||
);
|
|
||||||
if (pkRes.error) {
|
|
||||||
logger.error("[Settings] Failed to update primary key:", pkRes.error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this._hasBotIdColumn = true;
|
|
||||||
logger.settings("[Settings] Auto-migration complete: bot_id column added.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const colInfo = res.results[0];
|
|
||||||
const isNullable = colInfo.IS_NULLABLE === 'YES';
|
|
||||||
const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI';
|
|
||||||
|
|
||||||
if (isPrimaryKey) {
|
|
||||||
this._hasBotIdColumn = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.settings("[Settings] Fixing bot_id column: adding to primary key...");
|
|
||||||
|
|
||||||
if (isNullable) {
|
|
||||||
await this.query(`UPDATE settings SET bot_id = '' WHERE bot_id IS NULL`);
|
|
||||||
await this.query(`ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.botId) {
|
|
||||||
await this.query(
|
|
||||||
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const pkRes = await this.query(
|
|
||||||
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
|
||||||
);
|
|
||||||
if (pkRes.error) {
|
|
||||||
logger.error("[Settings] Failed to update primary key:", pkRes.error);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this._hasBotIdColumn = true;
|
|
||||||
logger.settings("[Settings] Fix complete: bot_id column added to primary key.");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set or update the bot ID used for database row isolation.
|
|
||||||
* Ensures the bot_id column exists (auto-migrates if needed), claims any
|
|
||||||
* unclaimed legacy rows, then reloads guild data filtered by the bot's ID.
|
|
||||||
* @param {string} id
|
|
||||||
*/
|
|
||||||
async setBotId(id) {
|
|
||||||
const changed = this.botId !== id;
|
|
||||||
this.botId = id;
|
|
||||||
if (changed) {
|
|
||||||
if (this._loadPromise) await this._loadPromise;
|
|
||||||
await this._ensureBotIdColumn();
|
|
||||||
|
|
||||||
if (this._hasBotIdColumn && this.botId) {
|
|
||||||
const claimRes = await this.query(
|
|
||||||
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
|
|
||||||
);
|
|
||||||
if (claimRes.results?.affectedRows > 0) {
|
|
||||||
logger.settings(`[Settings] Claimed ${claimRes.results.affectedRows} legacy row(s) for bot ${this.botId}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.guilds.clear();
|
|
||||||
this._loadPromise = this.load();
|
|
||||||
await this._loadPromise;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_botIdWhere() {
|
|
||||||
if (!this.botId || !this._hasBotIdColumn) return "";
|
|
||||||
return ` AND bot_id = ${mysql.escape(String(this.botId))}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
_botIdInsert() {
|
|
||||||
if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" };
|
|
||||||
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch a single guild's settings row from the database, filtered by bot_id.
|
|
||||||
* @param {string} guildId
|
|
||||||
* @returns {Promise<{error: object|null, results: Array, fields: Array}>}
|
|
||||||
*/
|
|
||||||
selectGuild(guildId) {
|
|
||||||
const escapedId = mysql.escape(String(guildId));
|
|
||||||
return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`);
|
|
||||||
}
|
|
||||||
query(query) {
|
|
||||||
return new Promise(res => {
|
|
||||||
this.db.query(query, (error, results, fields) => { res({ error, results, fields }); });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
async load() {
|
|
||||||
const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`);
|
|
||||||
if (res.error) {
|
|
||||||
this._loadAttempts = (this._loadAttempts || 0) + 1;
|
|
||||||
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000);
|
|
||||||
logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error);
|
|
||||||
return new Promise((resolve) => { setTimeout(() => { this.load().then(resolve).catch(resolve); }, delay); });
|
|
||||||
}
|
|
||||||
this._loadAttempts = 0;
|
|
||||||
res.results.forEach((r) => {
|
|
||||||
try {
|
|
||||||
const server = new ServerSettings(r.id, this);
|
|
||||||
const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data;
|
|
||||||
server.deserialize(parsed);
|
|
||||||
server.checkDefaults(this.defaults);
|
|
||||||
this.guilds.set(server.id, server);
|
|
||||||
} catch (e) {
|
|
||||||
logger.error("[Settings] Failed to parse settings for server", r.id, ":", e.message);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
this.emit("ready");
|
|
||||||
}
|
|
||||||
async remoteUpdate(server, key) {
|
|
||||||
const val = server.data[key];
|
|
||||||
if (Array.isArray(val) || (typeof val === "object" && val !== null)) {
|
|
||||||
return this.remoteSave(server);
|
|
||||||
}
|
|
||||||
const escapedKey = mysql.escape(`$.${key}`);
|
|
||||||
const escapedVal = (typeof val === "boolean" || typeof val === "number")
|
|
||||||
? mysql.escape(val)
|
|
||||||
: mysql.escape(String(val));
|
|
||||||
const escapedId = mysql.escape(server.id);
|
|
||||||
const r = await this.query(
|
|
||||||
`UPDATE settings SET data = JSON_SET(data, ${escapedKey}, ${escapedVal}) WHERE id=${escapedId}${this._botIdWhere()}`
|
|
||||||
);
|
|
||||||
if (r.error) logger.error("[Settings] remoteUpdate error:", r.error);
|
|
||||||
}
|
|
||||||
async remoteSave(server) {
|
|
||||||
const escapedData = mysql.escape(JSON.stringify(server.data));
|
|
||||||
const escapedId = mysql.escape(server.id);
|
|
||||||
const r = await this.query(
|
|
||||||
`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}`
|
|
||||||
);
|
|
||||||
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
|
|
||||||
}
|
|
||||||
loadDefaultsSync(filePath) {
|
|
||||||
try {
|
|
||||||
const d = fs.readFileSync(filePath, "utf8");
|
|
||||||
const parsed = JSON.parse(d);
|
|
||||||
this.descriptions = parsed.descriptions;
|
|
||||||
this.defaults = parsed.values;
|
|
||||||
} catch (e) {
|
|
||||||
logger.error("[Settings] Failed to load defaults from", filePath, ":", e.message);
|
|
||||||
this.descriptions = {};
|
|
||||||
this.defaults = {};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
async saveAsync() {
|
|
||||||
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v)));
|
|
||||||
}
|
|
||||||
async create(id, server) {
|
|
||||||
const escapedId = mysql.escape(id);
|
|
||||||
const escapedData = mysql.escape(JSON.stringify(server.data));
|
|
||||||
const bi = this._botIdInsert();
|
|
||||||
const r = await this.query(
|
|
||||||
`INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})`
|
|
||||||
);
|
|
||||||
if (r.error) logger.error("[Settings] create error:", r.error);
|
|
||||||
}
|
|
||||||
update(server, key) {
|
|
||||||
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); }
|
|
||||||
const s = this.guilds.get(server.id);
|
|
||||||
s.data[key] = server.data[key];
|
|
||||||
const existing = this._debounceTimers.get(server.id);
|
|
||||||
if (existing) clearTimeout(existing);
|
|
||||||
this._debounceTimers.set(server.id, setTimeout(() => {
|
|
||||||
this._debounceTimers.delete(server.id);
|
|
||||||
this.remoteSave(s);
|
|
||||||
}, 80));
|
|
||||||
}
|
|
||||||
isOption(key) { return key in this.defaults; }
|
|
||||||
hasServer(id) { return this.guilds.has(id); }
|
|
||||||
getServer(id) { return (!this.guilds.has(id)) ? new ServerSettings(id, this) : this.guilds.get(id); }
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,9 @@
|
|||||||
import { SettingsManager, RemoteSettingsManager } from "../src/Settings.mjs";
|
/**
|
||||||
|
* @file migrate.mjs — Migration script — migrates settings and 24/7 channel data between Redis and SQLite backends
|
||||||
|
* @module settings.migrate
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { RemoteSettingsManager } from "../src/Settings.mjs";
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/constants/Logger.mjs";
|
||||||
|
|
||||||
|
|||||||
+35
-5
@@ -1,14 +1,44 @@
|
|||||||
|
/**
|
||||||
|
* @file runnables.mjs — Runnable validators — server-side validation functions for settings values (prefix, volume, 24/7 mode, etc.)
|
||||||
|
* @module settings.runnables
|
||||||
|
*/
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
prefix: function(value, data) {
|
/**
|
||||||
|
* Validate a prefix setting value.
|
||||||
|
* @param {string} value - The proposed prefix
|
||||||
|
* @param {object} _data - Additional context (reserved for future use)
|
||||||
|
* @returns {true|string} True if valid, error message string if invalid
|
||||||
|
*/
|
||||||
|
prefix(value, _data) {
|
||||||
|
if (!value || typeof value !== "string") return "Prefix must be a non-empty string.";
|
||||||
|
if (value.length > 10) return "Prefix must be 10 characters or fewer.";
|
||||||
|
if (/\s/.test(value)) return "Prefix must not contain whitespace.";
|
||||||
|
return true;
|
||||||
},
|
},
|
||||||
|
|
||||||
pfp: function(value, data) {
|
/**
|
||||||
|
* Validate a profile picture setting value.
|
||||||
|
* @param {string} value - The proposed pfp value
|
||||||
|
* @param {object} _data - Additional context (reserved for future use)
|
||||||
|
* @returns {true|string} True if valid, error message string if invalid
|
||||||
|
*/
|
||||||
|
pfp(value, _data) {
|
||||||
if (value !== "default") {
|
if (value !== "default") {
|
||||||
return "Profile picture customisation is not supported on Fluxer.";
|
return "Profile picture customisation is not supported on Fluxer.";
|
||||||
}
|
}
|
||||||
|
return true;
|
||||||
},
|
},
|
||||||
|
|
||||||
stay_247: function(value, data) {
|
/**
|
||||||
return false;
|
* Validate the 24/7 stay mode setting.
|
||||||
|
* @param {string|boolean} value - The proposed stay_247 value
|
||||||
|
* @param {object} _data - Additional context (reserved for future use)
|
||||||
|
* @returns {true|string} True if valid, error message string if invalid
|
||||||
|
*/
|
||||||
|
stay_247(value, _data) {
|
||||||
|
if (value === true || value === false || value === "true" || value === "false") return true;
|
||||||
|
if (typeof value === "string" && value.length > 0) return true;
|
||||||
|
return "Invalid value for 24/7 mode.";
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
+31
-2
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file CommandHandler.mjs — CommandHandler — registers, resolves, and dispatches slash and prefix commands with option parsing and requirements
|
||||||
|
* @module src.CommandHandler
|
||||||
|
*/
|
||||||
|
|
||||||
import { pathToFileURL } from "node:url";
|
import { pathToFileURL } from "node:url";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
import { Utils } from "./Utils.mjs";
|
import { Utils } from "./Utils.mjs";
|
||||||
@@ -8,6 +13,9 @@ import { SettingsManager } from "./Settings.mjs";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import * as fs from "node:fs";
|
import * as fs from "node:fs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CommandBuilder class.
|
||||||
|
*/
|
||||||
export class CommandBuilder {
|
export class CommandBuilder {
|
||||||
constructor() {
|
constructor() {
|
||||||
this.name = null;
|
this.name = null;
|
||||||
@@ -52,6 +60,9 @@ export class CommandBuilder {
|
|||||||
addExamples(...examples) { this.examples.push(...examples); return this; }
|
addExamples(...examples) { this.examples.push(...examples); return this; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CommandRequirement class.
|
||||||
|
*/
|
||||||
export class CommandRequirement {
|
export class CommandRequirement {
|
||||||
ownerOnly = false;
|
ownerOnly = false;
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -69,6 +80,9 @@ export class CommandRequirement {
|
|||||||
setPermissionError(e) { this.permissionError = e; return this; }
|
setPermissionError(e) { this.permissionError = e; return this; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Option class.
|
||||||
|
*/
|
||||||
export class Option {
|
export class Option {
|
||||||
static THRESHOLD = 10;
|
static THRESHOLD = 10;
|
||||||
static COLS_PER_LINE = 5;
|
static COLS_PER_LINE = 5;
|
||||||
@@ -231,6 +245,9 @@ export class Option {
|
|||||||
set typeError(e) { this.tError = e; }
|
set typeError(e) { this.tError = e; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flag class.
|
||||||
|
*/
|
||||||
export class Flag extends Option {
|
export class Flag extends Option {
|
||||||
constructor(type = "string") {
|
constructor(type = "string") {
|
||||||
if (type === "text") throw new Error("Flags can't be of type 'text'!");
|
if (type === "text") throw new Error("Flags can't be of type 'text'!");
|
||||||
@@ -238,6 +255,9 @@ export class Flag extends Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PrefixManager class.
|
||||||
|
*/
|
||||||
export class PrefixManager {
|
export class PrefixManager {
|
||||||
/** @type {SettingsManager} */
|
/** @type {SettingsManager} */
|
||||||
settings;
|
settings;
|
||||||
@@ -250,6 +270,9 @@ export class PrefixManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HelpHandler class.
|
||||||
|
*/
|
||||||
export class HelpHandler {
|
export class HelpHandler {
|
||||||
/** @type {CommandHandler} */
|
/** @type {CommandHandler} */
|
||||||
commands;
|
commands;
|
||||||
@@ -386,6 +409,9 @@ export class HelpHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CommandHandler class.
|
||||||
|
*/
|
||||||
export class CommandHandler extends EventEmitter {
|
export class CommandHandler extends EventEmitter {
|
||||||
onPing = null;
|
onPing = null;
|
||||||
pingPrefix = true;
|
pingPrefix = true;
|
||||||
@@ -547,7 +573,7 @@ export class CommandHandler extends EventEmitter {
|
|||||||
try {
|
try {
|
||||||
const names = botPermResult.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
const names = botPermResult.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
||||||
msg.message?.reply?.("I'm missing critical permissions: **" + names.join("**, **") + "**. Ask an admin to fix this.", { ping: false });
|
msg.message?.reply?.("I'm missing critical permissions: **" + names.join("**, **") + "**. Ask an admin to fix this.", { ping: false });
|
||||||
} catch (__) { /* completely blocked */ }
|
} catch (__) { }
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -775,6 +801,9 @@ export class CommandHandler extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CommandLoader class.
|
||||||
|
*/
|
||||||
export class CommandLoader {
|
export class CommandLoader {
|
||||||
/** @type {CommandHandler} */
|
/** @type {CommandHandler} */
|
||||||
commands;
|
commands;
|
||||||
@@ -861,4 +890,4 @@ export class CommandLoader {
|
|||||||
});
|
});
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file FluxerListManager.mjs — FluxerListManager — FluxerList bot listing API client for vote checking and server stats
|
||||||
|
* @module src.FluxerListManager
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* FluxerListManager.mjs — FluxerList API client for voter data queries.
|
* FluxerListManager.mjs — FluxerList API client for voter data queries.
|
||||||
*
|
*
|
||||||
@@ -7,7 +12,7 @@
|
|||||||
* - In-memory response caching with configurable TTL
|
* - In-memory response caching with configurable TTL
|
||||||
* - Graceful error handling (401/403 auth errors, network failures)
|
* - Graceful error handling (401/403 auth errors, network failures)
|
||||||
*
|
*
|
||||||
* FluxerList API docs: https:
|
* FluxerList API docs: https://fluxerlist.com/api/v1
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
@@ -18,6 +23,9 @@ import {
|
|||||||
buildFluxerListUrl,
|
buildFluxerListUrl,
|
||||||
} from "./constants/API.mjs";
|
} from "./constants/API.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FluxerListManager class.
|
||||||
|
*/
|
||||||
export class FluxerListManager {
|
export class FluxerListManager {
|
||||||
/**
|
/**
|
||||||
* @param {object} config - The `fluxerlist` section from config.json
|
* @param {object} config - The `fluxerlist` section from config.json
|
||||||
|
|||||||
+433
-395
File diff suppressed because it is too large.
Load diff
+16
-12
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file LastFmManager.mjs — LastFmManager — Last.fm API integration for scrobbling, now-playing, loved tracks, top tracks, and track recommendations
|
||||||
|
* @module src.LastFmManager
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* LastFmManager.mjs — Last.fm API client for scrobbling, auth, and user data.
|
* LastFmManager.mjs — Last.fm API client for scrobbling, auth, and user data.
|
||||||
*
|
*
|
||||||
@@ -8,26 +13,22 @@
|
|||||||
* - Fetch loved / top / recent tracks for %play lastfm loved/top/recent
|
* - Fetch loved / top / recent tracks for %play lastfm loved/top/recent
|
||||||
* - Per-user session key storage in MySQL table `lastfm_users`
|
* - Per-user session key storage in MySQL table `lastfm_users`
|
||||||
*
|
*
|
||||||
* Last.fm API docs: https:
|
* Last.fm API docs: https://www.last.fm/api
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import crypto from "node:crypto";
|
import crypto from "node:crypto";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
|
import { Utils } from "./Utils.mjs";
|
||||||
|
|
||||||
const BASE_URL = "https://ws.audioscrobbler.com/2.0/";
|
const BASE_URL = "https://ws.audioscrobbler.com/2.0/";
|
||||||
|
|
||||||
function normalizeTrackText(value) {
|
function normalizeTrackText(value) {
|
||||||
return String(value ?? "")
|
return Utils.normalizeText(value);
|
||||||
.normalize("NFKD")
|
|
||||||
.replace(/[^\w\s]+/g, " ")
|
|
||||||
.replace(/\s+/g, " ")
|
|
||||||
.trim()
|
|
||||||
.toLowerCase();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build the API signature required by Last.fm for authenticated calls.
|
* Build the API signature required by Last.fm for authenticated calls.
|
||||||
* See: https:
|
* See: https://www.last.fm/api/authentication
|
||||||
*/
|
*/
|
||||||
function buildSignature(params, apiSecret) {
|
function buildSignature(params, apiSecret) {
|
||||||
const sorted = Object.keys(params).sort();
|
const sorted = Object.keys(params).sort();
|
||||||
@@ -70,6 +71,9 @@ async function apiCall(params, apiSecret, post = false) {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LastFmManager class.
|
||||||
|
*/
|
||||||
export class LastFmManager {
|
export class LastFmManager {
|
||||||
/**
|
/**
|
||||||
* @param {object} config - The `lastfm` section from config.json
|
* @param {object} config - The `lastfm` section from config.json
|
||||||
@@ -1261,10 +1265,10 @@ export class LastFmManager {
|
|||||||
/**
|
/**
|
||||||
* Parse a Last.fm music URL and extract artist and track info.
|
* Parse a Last.fm music URL and extract artist and track info.
|
||||||
* Supports:
|
* Supports:
|
||||||
* https:
|
* https://www.last.fm/music/Artist
|
||||||
* https:
|
* https://www.last.fm/music/Artist/Track
|
||||||
* https:
|
* https://www.last.fm/music/Artist/Album/Track
|
||||||
* https:
|
* https://www.last.fm/music/Artist/_/Track
|
||||||
*
|
*
|
||||||
* @param {string} url
|
* @param {string} url
|
||||||
* @returns {{ artist: string, track: string|null, album: string|null, url: string } | null}
|
* @returns {{ artist: string, track: string|null, album: string|null, url: string } | null}
|
||||||
|
|||||||
+56
-4
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file MessageHandler.mjs — MessageHandler — wraps Fluxer messages with reply helpers, embed builders, permission checks, and voice state utilities
|
||||||
|
* @module src.MessageHandler
|
||||||
|
*/
|
||||||
|
|
||||||
import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
|
import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
import { Utils } from "./Utils.mjs";
|
import { Utils } from "./Utils.mjs";
|
||||||
@@ -38,9 +43,44 @@ export function parseColor(value, fallback = 0xe9196c) {
|
|||||||
|
|
||||||
/** Global embed color — set once at startup from config */
|
/** Global embed color — set once at startup from config */
|
||||||
let _globalColor = 0xe9196c;
|
let _globalColor = 0xe9196c;
|
||||||
|
/**
|
||||||
|
* setGlobalColor function.
|
||||||
|
* @param {{*}} value
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
export function setGlobalColor(value) { _globalColor = parseColor(value); }
|
export function setGlobalColor(value) { _globalColor = parseColor(value); }
|
||||||
|
/**
|
||||||
|
* getGlobalColor function.
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
export function getGlobalColor() { return _globalColor; }
|
export function getGlobalColor() { return _globalColor; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strip non-digit characters from a value, returning a clean ID string.
|
||||||
|
* Re-exported from Utils.mjs for backward compatibility.
|
||||||
|
*/
|
||||||
|
export { cleanId } from "./Utils.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a guild ID from various message-like shapes.
|
||||||
|
* @param {object} message
|
||||||
|
* @returns {string|null}
|
||||||
|
*/
|
||||||
|
export function getMessageGuildId(message) {
|
||||||
|
return message?.channel?.guildId ??
|
||||||
|
message?.channel?.guild?.id ??
|
||||||
|
message?.message?.guildId ??
|
||||||
|
message?.message?.guild?.id ??
|
||||||
|
message?.channel?.server_id ??
|
||||||
|
message?.channel?.serverId ??
|
||||||
|
message?.message?.server_id ??
|
||||||
|
message?.message?.serverId ??
|
||||||
|
null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MessageHandler class.
|
||||||
|
*/
|
||||||
export class MessageHandler {
|
export class MessageHandler {
|
||||||
/**
|
/**
|
||||||
* Fluxer.js client instance
|
* Fluxer.js client instance
|
||||||
@@ -205,7 +245,7 @@ export class MessageHandler {
|
|||||||
async assertPermissions(permissions, message) {
|
async assertPermissions(permissions, message) {
|
||||||
const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId);
|
const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId);
|
||||||
if (guild && !guild.members?.me) {
|
if (guild && !guild.members?.me) {
|
||||||
try { await guild.members.fetchMe(); } catch (_) { /* fetch failed, checkPermissions will warn */ }
|
try { await guild.members.fetchMe(); } catch (_) { }
|
||||||
}
|
}
|
||||||
const missing = this.checkPermissions(permissions, message.channel ?? message.channel?.channel);
|
const missing = this.checkPermissions(permissions, message.channel ?? message.channel?.channel);
|
||||||
if (missing.length === 0) return true;
|
if (missing.length === 0) return true;
|
||||||
@@ -230,7 +270,7 @@ export class MessageHandler {
|
|||||||
try {
|
try {
|
||||||
const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
||||||
await message.reply(this.t(message.guildId, "responses.messages.needPermsFallback", { perms: names.join("** **") }), { ping: false });
|
await message.reply(this.t(message.guildId, "responses.messages.needPermsFallback", { perms: names.join("** **") }), { ping: false });
|
||||||
} catch (_) { /* completely blocked */ }
|
} catch (_) { }
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -543,6 +583,9 @@ export class MessageHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Channel class.
|
||||||
|
*/
|
||||||
export class Channel {
|
export class Channel {
|
||||||
/**
|
/**
|
||||||
* The actual underlying fluxer.js channel instance
|
* The actual underlying fluxer.js channel instance
|
||||||
@@ -640,6 +683,9 @@ export class Channel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Message class.
|
||||||
|
*/
|
||||||
export class Message {
|
export class Message {
|
||||||
/**
|
/**
|
||||||
* The actual underlying message instance
|
* The actual underlying message instance
|
||||||
@@ -733,6 +779,9 @@ export class Message {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PageBuilder class.
|
||||||
|
*/
|
||||||
export class PageBuilder {
|
export class PageBuilder {
|
||||||
form = "";
|
form = "";
|
||||||
maxLinesPerPage = 2;
|
maxLinesPerPage = 2;
|
||||||
@@ -942,7 +991,7 @@ export class RichPaginator {
|
|||||||
for (const emoji of allReactions) {
|
for (const emoji of allReactions) {
|
||||||
try {
|
try {
|
||||||
await rawMsg.removeReaction(emoji);
|
await rawMsg.removeReaction(emoji);
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1041,7 +1090,7 @@ export class QueuePaginator {
|
|||||||
for (const emoji of [prev, next]) {
|
for (const emoji of [prev, next]) {
|
||||||
try {
|
try {
|
||||||
await rawMsg.removeReaction(emoji);
|
await rawMsg.removeReaction(emoji);
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1159,6 +1208,9 @@ function _helpBuildCategoryPages(tab, allCmds, prefix) {
|
|||||||
return pages;
|
return pages;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HelpCommand class.
|
||||||
|
*/
|
||||||
export class HelpCommand {
|
export class HelpCommand {
|
||||||
/**
|
/**
|
||||||
* @param {import("./CommandHandler.mjs").CommandHandler} commandHandler
|
* @param {import("./CommandHandler.mjs").CommandHandler} commandHandler
|
||||||
|
|||||||
+14
-6
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file MoonlinkManager.mjs — MoonlinkManager — wraps moonlink.js for track search, session management, and voice packet forwarding to NodeLink
|
||||||
|
* @module src.MoonlinkManager
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* MoonlinkManager.mjs
|
* MoonlinkManager.mjs
|
||||||
*
|
*
|
||||||
@@ -9,6 +14,9 @@ import { logger, _wsErrorCooldown } from "./constants/Logger.mjs";
|
|||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
import { Events } from "@fluxerjs/core";
|
import { Events } from "@fluxerjs/core";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MoonlinkManager class.
|
||||||
|
*/
|
||||||
export class MoonlinkManager extends EventEmitter {
|
export class MoonlinkManager extends EventEmitter {
|
||||||
/** @type {Manager} */
|
/** @type {Manager} */
|
||||||
manager = null;
|
manager = null;
|
||||||
@@ -102,7 +110,7 @@ export class MoonlinkManager extends EventEmitter {
|
|||||||
if (node.sessionId) return node.sessionId;
|
if (node.sessionId) return node.sessionId;
|
||||||
if (node.ws?.sessionId) return node.ws.sessionId;
|
if (node.ws?.sessionId) return node.ws.sessionId;
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Moonlink] getLiveSessionId:", e?.message); }
|
||||||
return this.sessionId;
|
return this.sessionId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -205,7 +213,7 @@ export class MoonlinkManager extends EventEmitter {
|
|||||||
this._rawWsObj.off("message", this._rawWsMessageListener ?? this._rawWsHandler);
|
this._rawWsObj.off("message", this._rawWsMessageListener ?? this._rawWsHandler);
|
||||||
this._rawWsObj.off("error", this._rawWsErrorHandler);
|
this._rawWsObj.off("error", this._rawWsErrorHandler);
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Moonlink] Raw WS listener cleanup:", e?.message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (wsObj === this._rawWsObj) return;
|
if (wsObj === this._rawWsObj) return;
|
||||||
@@ -221,7 +229,7 @@ export class MoonlinkManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
this.manager.packetUpdate(payload);
|
this.manager.packetUpdate(payload);
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Moonlink] Raw WS message parse error:", e?.message); }
|
||||||
};
|
};
|
||||||
|
|
||||||
this._rawWsErrorHandler = (errOrEvent) => {
|
this._rawWsErrorHandler = (errOrEvent) => {
|
||||||
@@ -254,7 +262,7 @@ export class MoonlinkManager extends EventEmitter {
|
|||||||
|
|
||||||
async init(clientId) {
|
async init(clientId) {
|
||||||
this.setMaxListeners(50);
|
this.setMaxListeners(50);
|
||||||
try { this.manager.setMaxListeners?.(50); } catch (_) {}
|
try { this.manager.setMaxListeners?.(50); } catch(e) { logger.warn("[Moonlink] init setMaxListeners:", e?.message); }
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
|
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
|
||||||
@@ -266,7 +274,7 @@ export class MoonlinkManager extends EventEmitter {
|
|||||||
sock.removeAllListeners("message");
|
sock.removeAllListeners("message");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Moonlink] init socket cleanup:", e?.message); }
|
||||||
|
|
||||||
await this.manager.init(clientId);
|
await this.manager.init(clientId);
|
||||||
}
|
}
|
||||||
@@ -288,6 +296,6 @@ export class MoonlinkManager extends EventEmitter {
|
|||||||
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
|
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
|
||||||
node.socket?.close?.();
|
node.socket?.close?.();
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Moonlink] destroy:", e?.message); }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+184
-219
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file Player.mjs — Core Player class — manages voice connections, audio streaming, queue, and playback lifecycle via FluxerRevoice/LiveKit
|
||||||
|
* @module src.Player
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Player.mjs — FluxerRevoice edition
|
* Player.mjs — FluxerRevoice edition
|
||||||
*
|
*
|
||||||
@@ -28,15 +33,12 @@ import { getGlobalColor } from "./MessageHandler.mjs";
|
|||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
import { get247ChannelMode } from "./constants/Helpers247.mjs";
|
import { get247ChannelMode } from "./constants/Helpers247.mjs";
|
||||||
import { PROVIDER_NAMES } from "./constants/providers.mjs";
|
import { PROVIDER_NAMES } from "./constants/providers.mjs";
|
||||||
|
import { cleanId } from "./Utils.mjs";
|
||||||
/** Emit a plain embed payload so listeners can send it directly */
|
import { hasHumansInChannel } from "./constants/VoiceStateResolver.mjs";
|
||||||
function mkEmbed(desc) {
|
|
||||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] };
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/** NodeLink default password — centralised so it doesn't need to be hardcoded in two places. */
|
/** NodeLink default password — centralised so it doesn't need to be hardcoded in two places. */
|
||||||
const NL_DEFAULT_PASSWORD = "youshallnotpass";
|
export const NL_DEFAULT_PASSWORD = "youshallnotpass";
|
||||||
|
|
||||||
const _sanitizeCache = new Map();
|
const _sanitizeCache = new Map();
|
||||||
|
|
||||||
@@ -129,7 +131,7 @@ class PlayerWorkerPool {
|
|||||||
cb.reject(new Error(String(data)));
|
cb.reject(new Error(String(data)));
|
||||||
this._drain();
|
this._drain();
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Player] Worker message handler error:", e?.message); }
|
||||||
});
|
});
|
||||||
|
|
||||||
worker.on("error", (err) => {
|
worker.on("error", (err) => {
|
||||||
@@ -195,6 +197,9 @@ class PlayerWorkerPool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Queue class.
|
||||||
|
*/
|
||||||
export class Queue extends EventEmitter {
|
export class Queue extends EventEmitter {
|
||||||
data = [];
|
data = [];
|
||||||
current = null;
|
current = null;
|
||||||
@@ -338,8 +343,16 @@ export default class Player extends EventEmitter {
|
|||||||
activeFilter = null;
|
activeFilter = null;
|
||||||
activeFilterPayload = null;
|
activeFilterPayload = null;
|
||||||
|
|
||||||
|
static INACTIVITY_DEFAULT_MS = 3 * 60 * 1000;
|
||||||
|
static TRACK_MOSTLY_FINISHED_RATIO = 0.85;
|
||||||
|
static TRACK_MOSTLY_FINISHED_FLOOR_MS = 15_000;
|
||||||
|
static RADIO_SAFETY_TIMEOUT_MS = 20 * 60 * 1000;
|
||||||
|
static PUBLISH_MAX_RETRIES = 3;
|
||||||
|
static PUBLISH_BASE_RETRY_MS = 3_000;
|
||||||
|
static CONNECTION_WAIT_MS = 3_000;
|
||||||
|
|
||||||
_inactivityTimer = null;
|
_inactivityTimer = null;
|
||||||
_inactivityLimit = 3 * 60 * 1000;
|
_inactivityLimit = Player.INACTIVITY_DEFAULT_MS;
|
||||||
_pendingInactivityCheck = false;
|
_pendingInactivityCheck = false;
|
||||||
|
|
||||||
_isJoining = false;
|
_isJoining = false;
|
||||||
@@ -421,33 +434,26 @@ export default class Player extends EventEmitter {
|
|||||||
*/
|
*/
|
||||||
_get247Mode() {
|
_get247Mode() {
|
||||||
if (!this._guildId) return "off";
|
if (!this._guildId) return "off";
|
||||||
|
const serverSettings = this.settingsMgr?.getServer?.(this._guildId)
|
||||||
|
?? this.settings
|
||||||
|
?? this.client?.settings?.getServer?.(this._guildId);
|
||||||
|
if (!serverSettings?.get) return "off";
|
||||||
|
|
||||||
const checkSettings = (set) => {
|
const channelId = cleanId(this._home247Channel ?? this._channelId ?? "");
|
||||||
if (!set?.get) return "off";
|
if (!channelId) return "off";
|
||||||
const raw = set.get("stay_247");
|
|
||||||
if (!raw || raw === "none") return "off";
|
|
||||||
|
|
||||||
|
|
||||||
|
const raw = serverSettings.get("stay_247");
|
||||||
|
if (raw && raw !== "none") {
|
||||||
const channels = Array.isArray(raw)
|
const channels = Array.isArray(raw)
|
||||||
? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)
|
? raw.map(id => cleanId(id)).filter(Boolean)
|
||||||
: [String(raw).replace(/\D/g, "")];
|
: [cleanId(raw)].filter(Boolean);
|
||||||
|
if (!channels.includes(channelId)) return "off";
|
||||||
|
} else {
|
||||||
|
return "off";
|
||||||
|
}
|
||||||
|
|
||||||
const homeChannel = this._home247Channel
|
return get247ChannelMode(serverSettings, channelId);
|
||||||
? String(this._home247Channel).replace(/\D/g, "")
|
|
||||||
: null;
|
|
||||||
const currentChannel = String(this._channelId ?? "").replace(/\D/g, "");
|
|
||||||
|
|
||||||
const matchChannel = channels.includes(homeChannel) ? homeChannel
|
|
||||||
: channels.includes(currentChannel) ? currentChannel
|
|
||||||
: null;
|
|
||||||
if (!matchChannel) return "off";
|
|
||||||
|
|
||||||
return get247ChannelMode(set, matchChannel);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (this.settingsMgr?.getServer) return checkSettings(this.settingsMgr.getServer(this._guildId));
|
|
||||||
if (this.settings?.get) return checkSettings(this.settings);
|
|
||||||
if (this.client?.settings?.getServer) return checkSettings(this.client.settings.getServer(this._guildId));
|
|
||||||
return "off";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -457,7 +463,7 @@ export default class Player extends EventEmitter {
|
|||||||
* @returns {string|null}
|
* @returns {string|null}
|
||||||
*/
|
*/
|
||||||
_resolveGuildId() {
|
_resolveGuildId() {
|
||||||
const cleanGuild = String(this._guildId ?? "").replace(/\D/g, "");
|
const cleanGuild = cleanId(this._guildId ?? "");
|
||||||
if (cleanGuild) return cleanGuild;
|
if (cleanGuild) return cleanGuild;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -465,9 +471,9 @@ export default class Player extends EventEmitter {
|
|||||||
if (channelId) {
|
if (channelId) {
|
||||||
const ch = this.client?.channels?.get?.(channelId);
|
const ch = this.client?.channels?.get?.(channelId);
|
||||||
const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null;
|
const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null;
|
||||||
if (fromChannel) return String(fromChannel).replace(/\D/g, "");
|
if (fromChannel) return cleanId(fromChannel);
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Player] Guild resolution failed:", e?.message); }
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -498,67 +504,15 @@ export default class Player extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_hasHumansInChannel() {
|
_hasHumansInChannel() {
|
||||||
if (!this._channelId || !this._guildId) return false;
|
return hasHumansInChannel({
|
||||||
const cleanChan = String(this._channelId).replace(/\D/g, "");
|
guildId: cleanId(this._guildId ?? ""),
|
||||||
const cleanGuild = String(this._guildId).replace(/\D/g, "");
|
channelId: cleanId(this._channelId ?? ""),
|
||||||
|
client: this.client,
|
||||||
if (this._voiceCache && this._voiceCache.hasHumansInChannel(cleanGuild, cleanChan)) {
|
voiceCache: this._voiceCache,
|
||||||
return true;
|
observedVoiceUsers: this._observedVoiceUsers,
|
||||||
}
|
room: this.connection?.room,
|
||||||
|
botId: this.client?.user?.id,
|
||||||
try {
|
});
|
||||||
const voiceUsers = this._observedVoiceUsers;
|
|
||||||
if (voiceUsers && typeof voiceUsers.iterateHumanUsers === "function") {
|
|
||||||
for (const [, info] of voiceUsers.iterateHumanUsers()) {
|
|
||||||
if (
|
|
||||||
String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild &&
|
|
||||||
String(info.channelId ?? "").replace(/\D/g, "") === cleanChan
|
|
||||||
) return true;
|
|
||||||
}
|
|
||||||
} else if (voiceUsers) {
|
|
||||||
for (const [, info] of voiceUsers) {
|
|
||||||
if (
|
|
||||||
String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild &&
|
|
||||||
String(info.channelId ?? "").replace(/\D/g, "") === cleanChan
|
|
||||||
) return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
try {
|
|
||||||
const guild = this.client?.guilds?.get?.(this._guildId);
|
|
||||||
const voiceStates = guild?.voice_states;
|
|
||||||
if (voiceStates) {
|
|
||||||
const entries = Array.isArray(voiceStates)
|
|
||||||
? voiceStates
|
|
||||||
: typeof voiceStates.values === "function"
|
|
||||||
? voiceStates.values()
|
|
||||||
: Object.values(voiceStates);
|
|
||||||
for (const state of entries) {
|
|
||||||
const stateChannelId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
|
||||||
if (stateChannelId === cleanChan) {
|
|
||||||
const userId = String(state?.userId ?? state?.user_id ?? "");
|
|
||||||
const member = guild?.members?.get?.(userId);
|
|
||||||
const isBot = member?.user?.bot ?? false;
|
|
||||||
if (!isBot) return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const room = this.connection?.room;
|
|
||||||
if (room?.isConnected && room.remoteParticipants) {
|
|
||||||
const botId = this.client?.user?.id;
|
|
||||||
for (const [, participant] of room.remoteParticipants) {
|
|
||||||
const pId = participant?.identity || participant?.sid;
|
|
||||||
if (pId && pId !== botId) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
_startInactivityTimer() {
|
_startInactivityTimer() {
|
||||||
@@ -633,10 +587,10 @@ export default class Player extends EventEmitter {
|
|||||||
logger.mediaplayer("[Player] Existing MediaPlayer unhealthy, cleaning up...");
|
logger.mediaplayer("[Player] Existing MediaPlayer unhealthy, cleaning up...");
|
||||||
try {
|
try {
|
||||||
if (this._mediaPlayer.fProc) {
|
if (this._mediaPlayer.fProc) {
|
||||||
try { this._mediaPlayer.fProc.removeAllListeners(); } catch (_) {}
|
try { this._mediaPlayer.fProc.removeAllListeners(); } catch(e) { }
|
||||||
}
|
}
|
||||||
await this._mediaPlayer.stop();
|
await this._mediaPlayer.stop();
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Player] MediaPlayer stop error:", e?.message); }
|
||||||
this._mediaPlayer = null;
|
this._mediaPlayer = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -647,8 +601,8 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
if (this._destroyed) return false;
|
if (this._destroyed) return false;
|
||||||
|
|
||||||
const MAX_PUBLISH_RETRIES = 3;
|
const MAX_PUBLISH_RETRIES = Player.PUBLISH_MAX_RETRIES;
|
||||||
const BASE_RETRY_DELAY_MS = 3_000;
|
const BASE_RETRY_DELAY_MS = Player.PUBLISH_BASE_RETRY_MS;
|
||||||
|
|
||||||
for (let attempt = 1; attempt <= MAX_PUBLISH_RETRIES; attempt++) {
|
for (let attempt = 1; attempt <= MAX_PUBLISH_RETRIES; attempt++) {
|
||||||
try {
|
try {
|
||||||
@@ -685,7 +639,7 @@ export default class Player extends EventEmitter {
|
|||||||
|| msg.includes("publishToRoom failed")
|
|| msg.includes("publishToRoom failed")
|
||||||
|| msg.includes("internal error");
|
|| msg.includes("internal error");
|
||||||
|
|
||||||
try { this._mediaPlayer?.stop?.(); } catch (_) {}
|
try { this._mediaPlayer?.stop?.(); } catch(e) { logger.warn("[Player] MediaPlayer stop during retry:", e?.message); }
|
||||||
this._mediaPlayer = null;
|
this._mediaPlayer = null;
|
||||||
|
|
||||||
if (isTransient && attempt < MAX_PUBLISH_RETRIES) {
|
if (isTransient && attempt < MAX_PUBLISH_RETRIES) {
|
||||||
@@ -720,7 +674,7 @@ export default class Player extends EventEmitter {
|
|||||||
if (this._mediaPlayer) {
|
if (this._mediaPlayer) {
|
||||||
try {
|
try {
|
||||||
if (this._mediaPlayer.fProc) {
|
if (this._mediaPlayer.fProc) {
|
||||||
try { this._mediaPlayer.fProc.removeAllListeners(); } catch (_) {}
|
try { this._mediaPlayer.fProc.removeAllListeners(); } catch(e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
await this._mediaPlayer.stop();
|
await this._mediaPlayer.stop();
|
||||||
@@ -730,9 +684,9 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (this._mediaPlayer?.fProc && !this._mediaPlayer.ffmpegFinished) {
|
if (this._mediaPlayer?.fProc && !this._mediaPlayer.ffmpegFinished) {
|
||||||
try { this._mediaPlayer.fProc.kill("SIGKILL"); } catch (_) {}
|
try { this._mediaPlayer.fProc.kill("SIGKILL"); } catch(e) { logger.warn("[Player] FFmpeg SIGKILL error:", e?.message); }
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Player] Stop MediaPlayer error:", e?.message); }
|
||||||
|
|
||||||
this._mediaPlayer = null;
|
this._mediaPlayer = null;
|
||||||
}
|
}
|
||||||
@@ -828,15 +782,15 @@ export default class Player extends EventEmitter {
|
|||||||
const elapsedMs = Math.max(0, Date.now() - this.startedPlaying);
|
const elapsedMs = Math.max(0, Date.now() - this.startedPlaying);
|
||||||
const remainingMs = Math.max(0, totalMs - elapsedMs);
|
const remainingMs = Math.max(0, totalMs - elapsedMs);
|
||||||
|
|
||||||
return elapsedMs / totalMs >= 0.85 || remainingMs <= 15_000;
|
return elapsedMs / totalMs >= Player.TRACK_MOSTLY_FINISHED_RATIO || remainingMs <= Player.TRACK_MOSTLY_FINISHED_FLOOR_MS;
|
||||||
}
|
}
|
||||||
|
|
||||||
async _streamViaRevoice(url, inputOptions = []) {
|
async _streamViaRevoice(url, inputOptions = []) {
|
||||||
if (this._streamingStopped) return;
|
if (this._streamingStopped) return;
|
||||||
|
|
||||||
this._streamingStopped = false;
|
this._streamingStopped = false;
|
||||||
let audioStream = null;
|
|
||||||
const currentTrack = this.queue.getCurrent();
|
const currentTrack = this.queue.getCurrent();
|
||||||
|
let audioStream = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
audioStream = await this._fetchStream(url);
|
audioStream = await this._fetchStream(url);
|
||||||
@@ -845,115 +799,96 @@ export default class Player extends EventEmitter {
|
|||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
if (audioStream) {
|
if (audioStream) {
|
||||||
try {
|
try {
|
||||||
if (typeof audioStream.unpipe === "function") audioStream.unpipe();
|
if (typeof audioStream.unpipe === "function") audioStream.unpipe();
|
||||||
if (typeof audioStream.destroy === "function") audioStream.destroy();
|
if (typeof audioStream.destroy === "function") audioStream.destroy();
|
||||||
} catch (_) {}
|
} catch (e) { }
|
||||||
}
|
}
|
||||||
this._currentPassthrough = null;
|
this._currentPassthrough = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
await new Promise((resolve, reject) => {
|
const isGracefulExit = () =>
|
||||||
|
this._streamingStopped || this._skipping || this._seeking || this.leaving;
|
||||||
|
|
||||||
|
|
||||||
|
const streamError = new Promise((_, reject) => {
|
||||||
audioStream.on("error", (e) => {
|
audioStream.on("error", (e) => {
|
||||||
cleanup();
|
if (isGracefulExit()) return;
|
||||||
if (this._streamingStopped || this._skipping || this._seeking) return resolve();
|
|
||||||
const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"];
|
const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"];
|
||||||
if (graceful.some(g => e.code === g || e.message?.includes(g))) {
|
if (graceful.some(g => e.code === g || e.message?.includes(g))) {
|
||||||
if (this._didTrackMostlyFinish(currentTrack)) return resolve();
|
if (this._didTrackMostlyFinish(currentTrack)) return;
|
||||||
return reject(new Error(`Stream ended early for ${currentTrack?.title || "track"}: ${e.message ?? e.code ?? "stream aborted"}`));
|
return reject(new Error(`Stream ended early for ${currentTrack?.title || "track"}: ${e.message ?? e.code ?? "stream aborted"}`));
|
||||||
}
|
}
|
||||||
reject(e);
|
reject(e);
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
if (!this._mediaPlayer) { cleanup(); return resolve(); }
|
if (!this._mediaPlayer) { cleanup(); return; }
|
||||||
|
|
||||||
this._mediaPlayer.removeAllListeners("finish");
|
this._mediaPlayer.removeAllListeners("finish");
|
||||||
this._mediaPlayer.removeAllListeners("error");
|
this._mediaPlayer.removeAllListeners("error");
|
||||||
|
|
||||||
const onFfmpegError = (err) => {
|
|
||||||
const ffMsg = err?.message ?? String(err);
|
|
||||||
|
|
||||||
const isGracefulKill =
|
try {
|
||||||
ffMsg.includes("aborted") ||
|
const playResult = this._mediaPlayer.playStream(audioStream, inputOptions);
|
||||||
ffMsg.includes("Input stream error") ||
|
if (playResult && typeof playResult.catch === "function") {
|
||||||
ffMsg.includes("SIGKILL") ||
|
playResult.catch((e) => {
|
||||||
ffMsg.includes("killed with signal");
|
if (isIgnorableMediaStateError(e) || isGracefulExit()) {
|
||||||
|
logger.mediaplayer("[Player] Suppressed async playStream InvalidState rejection");
|
||||||
if (isGracefulKill) {
|
|
||||||
if (this._didTrackMostlyFinish(currentTrack)) {
|
|
||||||
logger.player("[Player] FFmpeg stream ended near track completion");
|
|
||||||
cleanup();
|
cleanup();
|
||||||
return resolve();
|
return;
|
||||||
}
|
}
|
||||||
cleanup();
|
cleanup();
|
||||||
if (this._streamingStopped || this._skipping || this._seeking) return resolve();
|
throw e;
|
||||||
return reject(new Error(`FFmpeg stream ended early: ${ffMsg}`));
|
});
|
||||||
}
|
|
||||||
|
|
||||||
logger.error("[Player] FFmpeg error:", ffMsg);
|
|
||||||
cleanup();
|
|
||||||
if (this._streamingStopped || this._skipping || this._seeking) return resolve();
|
|
||||||
reject(new Error(`FFmpeg: ${ffMsg}`));
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
const playResult = this._mediaPlayer.playStream(audioStream, inputOptions);
|
|
||||||
if (playResult && typeof playResult.catch === "function") {
|
|
||||||
playResult.catch((e) => {
|
|
||||||
if (isIgnorableMediaStateError(e) || this._streamingStopped || this._skipping || this._seeking || this.leaving) {
|
|
||||||
logger.mediaplayer("[Player] Suppressed async playStream InvalidState rejection");
|
|
||||||
cleanup();
|
|
||||||
resolve();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
cleanup();
|
|
||||||
reject(e);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (this._mediaPlayer.fProc) {
|
|
||||||
this._mediaPlayer.fProc.once("error", onFfmpegError);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
cleanup();
|
|
||||||
if (isIgnorableMediaStateError(e)) {
|
|
||||||
logger.mediaplayer("[Player] Suppressed InvalidState during stream start");
|
|
||||||
return resolve();
|
|
||||||
}
|
|
||||||
return reject(e);
|
|
||||||
}
|
}
|
||||||
|
} catch (e) {
|
||||||
|
cleanup();
|
||||||
|
if (isIgnorableMediaStateError(e)) {
|
||||||
|
logger.mediaplayer("[Player] Suppressed InvalidState during stream start");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
const trackDuration = this._getTrackDurationMs(currentTrack);
|
|
||||||
const safetyMs = (trackDuration > 0 && currentTrack?.type !== "radio")
|
|
||||||
? trackDuration + 15_000
|
|
||||||
: 20 * 60 * 1000;
|
|
||||||
|
|
||||||
|
const trackDuration = this._getTrackDurationMs(currentTrack);
|
||||||
|
const safetyMs = (trackDuration > 0 && currentTrack?.type !== "radio")
|
||||||
|
? trackDuration + Player.TRACK_MOSTLY_FINISHED_FLOOR_MS
|
||||||
|
: Player.RADIO_SAFETY_TIMEOUT_MS;
|
||||||
|
|
||||||
|
await new Promise((resolve) => {
|
||||||
const safetyTimer = setTimeout(() => {
|
const safetyTimer = setTimeout(() => {
|
||||||
logger.warn(`[Player] Stream safety timeout hit (${Math.round(safetyMs/1000)}s) — advancing queue`);
|
logger.warn(`[Player] Stream safety timeout hit (${Math.round(safetyMs / 1000)}s) — advancing queue`);
|
||||||
cleanup();
|
cleanup();
|
||||||
resolve();
|
resolve();
|
||||||
}, safetyMs);
|
}, safetyMs);
|
||||||
|
|
||||||
this._mediaPlayer.once("finish", () => {
|
const onFinish = () => {
|
||||||
clearTimeout(safetyTimer);
|
clearTimeout(safetyTimer);
|
||||||
if (this._mediaPlayer?.fProc) this._mediaPlayer.fProc.removeListener("error", onFfmpegError);
|
|
||||||
cleanup();
|
cleanup();
|
||||||
resolve();
|
resolve();
|
||||||
});
|
};
|
||||||
this._mediaPlayer.once("error", (e) => {
|
|
||||||
|
const onError = (e) => {
|
||||||
clearTimeout(safetyTimer);
|
clearTimeout(safetyTimer);
|
||||||
if (this._mediaPlayer?.fProc) this._mediaPlayer.fProc.removeListener("error", onFfmpegError);
|
|
||||||
cleanup();
|
cleanup();
|
||||||
if (isIgnorableMediaStateError(e)) {
|
if (isIgnorableMediaStateError(e)) {
|
||||||
logger.mediaplayer("[Player] Suppressed InvalidState during playback");
|
logger.mediaplayer("[Player] Suppressed InvalidState during playback");
|
||||||
return resolve();
|
return resolve();
|
||||||
}
|
}
|
||||||
if (this._streamingStopped) return resolve();
|
if (this._streamingStopped) return resolve();
|
||||||
reject(e);
|
|
||||||
});
|
logger.warn("[Player] MediaPlayer error during stream:", e?.message);
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
|
||||||
|
this._mediaPlayer.once("finish", onFinish);
|
||||||
|
this._mediaPlayer.once("error", onError);
|
||||||
});
|
});
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (audioStream && !audioStream.destroyed) {
|
if (audioStream && !audioStream.destroyed) {
|
||||||
try { audioStream.destroy(); } catch (_) {}
|
try { audioStream.destroy(); } catch (e2) { }
|
||||||
}
|
}
|
||||||
this._currentPassthrough = null;
|
this._currentPassthrough = null;
|
||||||
if (isIgnorableMediaStateError(e)) {
|
if (isIgnorableMediaStateError(e)) {
|
||||||
@@ -1008,15 +943,15 @@ export default class Player extends EventEmitter {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
logger.player(`[Player] Dead connection detected for ${channelId}, cleaning up`);
|
logger.player(`[Player] Dead connection detected for ${channelId}, cleaning up`);
|
||||||
try { this.connection.removeAllListeners(); } catch (_) {}
|
try { this.connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Connection cleanup error:", e?.message); }
|
||||||
|
|
||||||
if (this._revoice && this._channelId) {
|
if (this._revoice && this._channelId) {
|
||||||
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {}
|
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch(e) { logger.warn("[Player] Mark intentional disconnect error:", e?.message); }
|
||||||
try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {}
|
try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch(e) { logger.warn("[Player] Leave gateway error:", e?.message); }
|
||||||
try { this._revoice.deleteConnection(this._channelId); } catch (_) {}
|
try { this._revoice.deleteConnection(this._channelId); } catch(e) { logger.warn("[Player] Delete connection error:", e?.message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
try { await this.connection.disconnect(); } catch (_) {}
|
try { await this.connection.disconnect(); } catch(e) { logger.warn("[Player] Connection disconnect error:", e?.message); }
|
||||||
this.connection = null;
|
this.connection = null;
|
||||||
this._mediaPlayer = null;
|
this._mediaPlayer = null;
|
||||||
}
|
}
|
||||||
@@ -1028,17 +963,17 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
if (this.connection) {
|
if (this.connection) {
|
||||||
logger.mediaplayer("[Player] Cleaning up existing connection before join");
|
logger.mediaplayer("[Player] Cleaning up existing connection before join");
|
||||||
try { this.connection.removeAllListeners(); } catch (_) {}
|
try { this.connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Connection cleanup error:", e?.message); }
|
||||||
|
|
||||||
if (this._revoice && this._channelId) {
|
if (this._revoice && this._channelId) {
|
||||||
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {}
|
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch(e) { logger.warn("[Player] Mark intentional disconnect error:", e?.message); }
|
||||||
try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {}
|
try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch(e) { logger.warn("[Player] Leave gateway error:", e?.message); }
|
||||||
try { this._revoice.deleteConnection(this._channelId); } catch (_) {}
|
try { this._revoice.deleteConnection(this._channelId); } catch(e) { logger.warn("[Player] Delete connection error:", e?.message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.connection.disconnect();
|
await this.connection.disconnect();
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Player] Connection disconnect error:", e?.message); }
|
||||||
|
|
||||||
await Utils.sleep(500);
|
await Utils.sleep(500);
|
||||||
this.connection = null;
|
this.connection = null;
|
||||||
@@ -1077,7 +1012,7 @@ export default class Player extends EventEmitter {
|
|||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
clearInterval(poll);
|
clearInterval(poll);
|
||||||
try { room.off(LKRoomEvent.ConnectionStateChanged, onStateChange); } catch (_) {}
|
try { room.off(LKRoomEvent.ConnectionStateChanged, onStateChange); } catch(e) { logger.warn("[Player] Room listener cleanup error:", e?.message); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const timeout = setTimeout(() => {
|
const timeout = setTimeout(() => {
|
||||||
@@ -1094,7 +1029,7 @@ export default class Player extends EventEmitter {
|
|||||||
settled = true;
|
settled = true;
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
}, 3_000);
|
}, Player.CONNECTION_WAIT_MS);
|
||||||
|
|
||||||
const onStateChange = (cs) => {
|
const onStateChange = (cs) => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
@@ -1148,7 +1083,7 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
connection.on("error", (err) => {
|
connection.on("error", (err) => {
|
||||||
if (this.connection !== connection) {
|
if (this.connection !== connection) {
|
||||||
try { connection.removeAllListeners(); } catch (_) {}
|
try { connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Stale connection cleanup error:", e?.message); }
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
logger.error("[Player] Voice error:", err?.message ?? err);
|
logger.error("[Player] Voice error:", err?.message ?? err);
|
||||||
@@ -1167,7 +1102,7 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
connection.on("disconnect", () => {
|
connection.on("disconnect", () => {
|
||||||
if (this.connection !== connection) {
|
if (this.connection !== connection) {
|
||||||
try { connection.removeAllListeners(); } catch (_) {}
|
try { connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Stale connection cleanup error:", e?.message); }
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!this.leaving && !this._destroyed) {
|
if (!this.leaving && !this._destroyed) {
|
||||||
@@ -1182,7 +1117,7 @@ export default class Player extends EventEmitter {
|
|||||||
.finally(() => this.emit("autoleave"));
|
.finally(() => this.emit("autoleave"));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
try { connection.removeAllListeners(); } catch (_) {}
|
try { connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Connection cleanup on leave error:", e?.message); }
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1235,7 +1170,7 @@ export default class Player extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (this.connection) {
|
if (this.connection) {
|
||||||
try { this.connection.disconnect(); } catch (_) {}
|
try { this.connection.disconnect(); } catch(e) { logger.warn("[Player] Connection disconnect on join failure:", e?.message); }
|
||||||
this.connection = null;
|
this.connection = null;
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
@@ -1255,7 +1190,7 @@ export default class Player extends EventEmitter {
|
|||||||
this._activeTrackOpt = null;
|
this._activeTrackOpt = null;
|
||||||
|
|
||||||
if (this._mediaPlayer) {
|
if (this._mediaPlayer) {
|
||||||
this._mediaPlayer.destroy();
|
try { this._mediaPlayer.destroy(); } catch(e) { /* MediaPlayer may not have destroy() */ }
|
||||||
this._mediaPlayer = null;
|
this._mediaPlayer = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1267,7 +1202,7 @@ export default class Player extends EventEmitter {
|
|||||||
} else if (this._revoice.connections) {
|
} else if (this._revoice.connections) {
|
||||||
this._revoice.connections.delete(channelId);
|
this._revoice.connections.delete(channelId);
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Player] Delete connection on leave error:", e?.message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.connection.leave();
|
await this.connection.leave();
|
||||||
@@ -1301,7 +1236,7 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (this._moonlink && this._onMoonlinkReady) {
|
if (this._moonlink && this._onMoonlinkReady) {
|
||||||
try { this._moonlink.off("ready", this._onMoonlinkReady); } catch (_) {}
|
try { this._moonlink.off("ready", this._onMoonlinkReady); } catch(e) { logger.warn("[Player] Moonlink cleanup error:", e?.message); }
|
||||||
this._onMoonlinkReady = null;
|
this._onMoonlinkReady = null;
|
||||||
}
|
}
|
||||||
this.leaving = true;
|
this.leaving = true;
|
||||||
@@ -1315,7 +1250,7 @@ export default class Player extends EventEmitter {
|
|||||||
this.searches.clear();
|
this.searches.clear();
|
||||||
|
|
||||||
if (this._workerPool) {
|
if (this._workerPool) {
|
||||||
try { this._workerPool.terminate(); } catch (_) {}
|
try { this._workerPool.terminate(); } catch(e) { logger.warn("[Player] Worker pool terminate error:", e?.message); }
|
||||||
this._workerPool = null;
|
this._workerPool = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1323,11 +1258,11 @@ export default class Player extends EventEmitter {
|
|||||||
this.connection = null;
|
this.connection = null;
|
||||||
this._mediaPlayer = null;
|
this._mediaPlayer = null;
|
||||||
if (this._revoice && this._channelId) {
|
if (this._revoice && this._channelId) {
|
||||||
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {}
|
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch(e) { logger.warn("[Player] Mark intentional disconnect on destroy:", e?.message); }
|
||||||
}
|
}
|
||||||
this._stopMediaPlayer().catch(() => {}).then(() => {
|
this._stopMediaPlayer().catch(() => {}).then(() => {
|
||||||
if (connToDestroy) {
|
if (connToDestroy) {
|
||||||
try { connToDestroy.removeAllListeners?.(); } catch (_) {}
|
try { connToDestroy.removeAllListeners?.(); } catch(e) { }
|
||||||
const disconnectPromise = connToDestroy.disconnect?.();
|
const disconnectPromise = connToDestroy.disconnect?.();
|
||||||
if (disconnectPromise instanceof Promise) {
|
if (disconnectPromise instanceof Promise) {
|
||||||
disconnectPromise.catch((err) => {
|
disconnectPromise.catch((err) => {
|
||||||
@@ -1391,7 +1326,7 @@ export default class Player extends EventEmitter {
|
|||||||
this.emit("queueEnd");
|
this.emit("queueEnd");
|
||||||
if (!this._autoplay) {
|
if (!this._autoplay) {
|
||||||
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
||||||
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true });
|
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1428,7 +1363,7 @@ export default class Player extends EventEmitter {
|
|||||||
this.emit("queueEnd");
|
this.emit("queueEnd");
|
||||||
if (!this._autoplay) {
|
if (!this._autoplay) {
|
||||||
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
||||||
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true });
|
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1903,12 +1838,12 @@ export default class Player extends EventEmitter {
|
|||||||
if (!s) return;
|
if (!s) return;
|
||||||
|
|
||||||
if (s.type === "radio") {
|
if (s.type === "radio") {
|
||||||
this.emit("message", mkEmbed(this._t("responses.radio.nowPlaying", {
|
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.radio.nowPlaying", {
|
||||||
title: Utils.escapeMarkdown(s.title),
|
title: Utils.escapeMarkdown(s.title),
|
||||||
author: s.author?.name || "Unknown",
|
author: s.author?.name || "Unknown",
|
||||||
url: s.author?.url || "",
|
url: s.author?.url || "",
|
||||||
channel: this._channelId || "",
|
channel: this._channelId || "",
|
||||||
})));
|
}))] });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const author = s.artists
|
const author = s.artists
|
||||||
@@ -1916,12 +1851,12 @@ export default class Player extends EventEmitter {
|
|||||||
: s.author?.url
|
: s.author?.url
|
||||||
? `[${s.author.name}](${s.author.url})`
|
? `[${s.author.name}](${s.author.url})`
|
||||||
: s.author?.name || "Unknown";
|
: s.author?.name || "Unknown";
|
||||||
this.emit("message", mkEmbed(this._t("responses.play.nowPlaying", {
|
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.play.nowPlaying", {
|
||||||
title: Utils.escapeMarkdown(s.title),
|
title: Utils.escapeMarkdown(s.title),
|
||||||
url: s.spotifyUrl || s.url,
|
url: s.spotifyUrl || s.url,
|
||||||
author: author,
|
author: author,
|
||||||
channel: this._channelId || "",
|
channel: this._channelId || "",
|
||||||
})));
|
}))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
_workerPool = null;
|
_workerPool = null;
|
||||||
@@ -2090,17 +2025,17 @@ export default class Player extends EventEmitter {
|
|||||||
try {
|
try {
|
||||||
if (typeof this._currentPassthrough.unpipe === "function") this._currentPassthrough.unpipe();
|
if (typeof this._currentPassthrough.unpipe === "function") this._currentPassthrough.unpipe();
|
||||||
if (typeof this._currentPassthrough.destroy === "function") this._currentPassthrough.destroy();
|
if (typeof this._currentPassthrough.destroy === "function") this._currentPassthrough.destroy();
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Player] Passthrough cleanup error:", e?.message); }
|
||||||
this._currentPassthrough = null;
|
this._currentPassthrough = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this._mediaPlayer) {
|
if (this._mediaPlayer) {
|
||||||
try {
|
try {
|
||||||
if (this._mediaPlayer.fProc) {
|
if (this._mediaPlayer.fProc) {
|
||||||
try { this._mediaPlayer.fProc.removeAllListeners(); } catch (_) {}
|
try { this._mediaPlayer.fProc.removeAllListeners(); } catch(e) { }
|
||||||
}
|
}
|
||||||
await this._mediaPlayer.stop();
|
await this._mediaPlayer.stop();
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Player] MediaPlayer stop on next track:", e?.message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
this._streamingStopped = false;
|
this._streamingStopped = false;
|
||||||
@@ -2121,7 +2056,7 @@ export default class Player extends EventEmitter {
|
|||||||
if (!this._wasRadio && !this._queueEndedSent && !this._autoplay) {
|
if (!this._wasRadio && !this._queueEndedSent && !this._autoplay) {
|
||||||
this._queueEndedSent = true;
|
this._queueEndedSent = true;
|
||||||
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
||||||
this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true });
|
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
|
||||||
}
|
}
|
||||||
this._wasRadio = false;
|
this._wasRadio = false;
|
||||||
return;
|
return;
|
||||||
@@ -2156,7 +2091,7 @@ export default class Player extends EventEmitter {
|
|||||||
const hasValidPlayer = await this._ensureMediaPlayer();
|
const hasValidPlayer = await this._ensureMediaPlayer();
|
||||||
if (!hasValidPlayer) {
|
if (!hasValidPlayer) {
|
||||||
logger.error("[Player] Failed to create healthy MediaPlayer — cannot play.");
|
logger.error("[Player] Failed to create healthy MediaPlayer — cannot play.");
|
||||||
this.emit("message", mkEmbed(this._t("responses._common.voiceConnectionLost")));
|
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.voiceConnectionLost"))] });
|
||||||
|
|
||||||
if (!this._is247Enabled()) {
|
if (!this._is247Enabled()) {
|
||||||
this._startInactivityTimer();
|
this._startInactivityTimer();
|
||||||
@@ -2214,7 +2149,7 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
if (!streamUrl || !Utils.isValidUrl(streamUrl)) {
|
if (!streamUrl || !Utils.isValidUrl(streamUrl)) {
|
||||||
logger.error("[Player] No valid stream URL for:", songData.title);
|
logger.error("[Player] No valid stream URL for:", songData.title);
|
||||||
this.emit("message", mkEmbed(this._t("responses._common.couldNotGetStream", { title: songData.title })));
|
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.couldNotGetStream", { title: songData.title }))] });
|
||||||
this._streamingStopped = true;
|
this._streamingStopped = true;
|
||||||
this.emit("stopplay");
|
this.emit("stopplay");
|
||||||
if (!this._is247Enabled()) {
|
if (!this._is247Enabled()) {
|
||||||
@@ -2235,7 +2170,7 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
if (trackOptMatch) {
|
if (trackOptMatch) {
|
||||||
this._activeTrackOpt = trackOptMatch;
|
this._activeTrackOpt = trackOptMatch;
|
||||||
if (trackOptMatch.startMs > 0 && songData.encoded && streamUrl.includes("/v4/loadstream")) {
|
if (trackOptMatch.startMs > 0 && streamUrl.includes("/v4/loadstream")) {
|
||||||
startOffsetMs = trackOptMatch.startMs;
|
startOffsetMs = trackOptMatch.startMs;
|
||||||
streamUrl = streamUrl.replace(/position=\d+/, `position=${startOffsetMs}`);
|
streamUrl = streamUrl.replace(/position=\d+/, `position=${startOffsetMs}`);
|
||||||
logger.player(`[Player] TrackOptions: starting from ${startOffsetMs}ms via loadstream position param`);
|
logger.player(`[Player] TrackOptions: starting from ${startOffsetMs}ms via loadstream position param`);
|
||||||
@@ -2277,7 +2212,7 @@ export default class Player extends EventEmitter {
|
|||||||
this._streamingStopped = true;
|
this._streamingStopped = true;
|
||||||
if (!this._skipping && !this.leaving && !this._paused) {
|
if (!this._skipping && !this.leaving && !this._paused) {
|
||||||
if (songData.type !== "radio") {
|
if (songData.type !== "radio") {
|
||||||
this.emit("message", mkEmbed(this._t("responses._common.errorStreaming", { title: songData.title })));
|
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.errorStreaming", { title: songData.title }))] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2300,7 +2235,8 @@ export default class Player extends EventEmitter {
|
|||||||
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
|
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
|
||||||
if (!this.queue.songLoop) this.queue.current = null;
|
if (!this.queue.songLoop) this.queue.current = null;
|
||||||
this._streamingStopped = false;
|
this._streamingStopped = false;
|
||||||
return this._doPlayNext();
|
this._playingNext = false;
|
||||||
|
return this.playNext();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2319,9 +2255,25 @@ export default class Player extends EventEmitter {
|
|||||||
this._trackEndRemainingMs = null;
|
this._trackEndRemainingMs = null;
|
||||||
this._skipping = true;
|
this._skipping = true;
|
||||||
this._stopMediaPlayer().then(() => {
|
this._stopMediaPlayer().then(() => {
|
||||||
this._doPlayNext();
|
this._playingNext = false;
|
||||||
|
if (!this.queue.isEmpty() && !this.leaving) {
|
||||||
|
this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message));
|
||||||
|
} else {
|
||||||
|
this.emit("stopplay");
|
||||||
|
if (!this._is247Enabled()) {
|
||||||
|
this._startInactivityTimer();
|
||||||
|
}
|
||||||
|
}
|
||||||
}).catch(() => {
|
}).catch(() => {
|
||||||
this._doPlayNext();
|
this._playingNext = false;
|
||||||
|
if (!this.queue.isEmpty() && !this.leaving) {
|
||||||
|
this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message));
|
||||||
|
} else {
|
||||||
|
this.emit("stopplay");
|
||||||
|
if (!this._is247Enabled()) {
|
||||||
|
this._startInactivityTimer();
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2372,8 +2324,8 @@ export default class Player extends EventEmitter {
|
|||||||
const userIds = [];
|
const userIds = [];
|
||||||
if (this._voiceCache) {
|
if (this._voiceCache) {
|
||||||
const humans = this._voiceCache.getHumansInChannel(
|
const humans = this._voiceCache.getHumansInChannel(
|
||||||
String(this._guildId).replace(/\D/g, ""),
|
cleanId(this._guildId),
|
||||||
String(this._channelId).replace(/\D/g, "")
|
cleanId(this._channelId)
|
||||||
);
|
);
|
||||||
userIds.push(...humans);
|
userIds.push(...humans);
|
||||||
}
|
}
|
||||||
@@ -2387,15 +2339,15 @@ export default class Player extends EventEmitter {
|
|||||||
: typeof voiceStates.values === "function" ? [...voiceStates.values()]
|
: typeof voiceStates.values === "function" ? [...voiceStates.values()]
|
||||||
: Object.values(voiceStates);
|
: Object.values(voiceStates);
|
||||||
for (const state of entries) {
|
for (const state of entries) {
|
||||||
const ch = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
const ch = cleanId(state?.channelId ?? state?.channel_id ?? "");
|
||||||
if (ch === String(this._channelId).replace(/\D/g, "")) {
|
if (ch === cleanId(this._channelId)) {
|
||||||
const uid = state?.userId ?? state?.user_id;
|
const uid = state?.userId ?? state?.user_id;
|
||||||
const member = guild?.members?.get?.(uid);
|
const member = guild?.members?.get?.(uid);
|
||||||
if (uid && !member?.user?.bot) userIds.push(uid);
|
if (uid && !member?.user?.bot) userIds.push(uid);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Player] Voice state lookup error:", e?.message); }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (userIds.length === 0) return null;
|
if (userIds.length === 0) return null;
|
||||||
@@ -2406,6 +2358,11 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
async _applyTrackOptionsSeek(match) {
|
async _applyTrackOptionsSeek(match) {
|
||||||
if (!match || match.startMs <= 0) return;
|
if (!match || match.startMs <= 0) return;
|
||||||
|
const current = this.queue.getCurrent();
|
||||||
|
if (!current?.encoded || !this.connection || this.leaving) {
|
||||||
|
logger.warn(`[Player] TrackOptions: cannot seek (encoded=${!!current?.encoded} connection=${!!this.connection} leaving=${this.leaving})`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
let seeked = false;
|
let seeked = false;
|
||||||
for (let attempt = 0; attempt < 10; attempt++) {
|
for (let attempt = 0; attempt < 10; attempt++) {
|
||||||
await Utils.sleep(500);
|
await Utils.sleep(500);
|
||||||
@@ -2421,7 +2378,15 @@ export default class Player extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!seeked) {
|
if (!seeked) {
|
||||||
logger.warn(`[Player] TrackOptions: auto-seek to ${match.startMs}ms failed after all retries`);
|
logger.warn(`[Player] TrackOptions: auto-seek to ${match.startMs}ms failed after all retries, trying _replayWithFilters`);
|
||||||
|
try {
|
||||||
|
await this._replayWithFilters(match.startMs);
|
||||||
|
this.startedPlaying = Date.now() - match.startMs;
|
||||||
|
this._recalcTrackEndTimer();
|
||||||
|
logger.player(`[Player] TrackOptions: fallback replay from ${match.startMs}ms succeeded`);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn(`[Player] TrackOptions: fallback replay also failed:`, e.message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+179
-237
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file PlayerManager.mjs — PlayerManager — creates, caches, and routes Player instances per voice channel across all guilds
|
||||||
|
* @module src.PlayerManager
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PlayerManager.mjs — Manages voice channel players across servers
|
* PlayerManager.mjs — Manages voice channel players across servers
|
||||||
*
|
*
|
||||||
@@ -6,37 +11,15 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import Player from "./Player.mjs";
|
import Player from "./Player.mjs";
|
||||||
import { CommandHandler } from "./CommandHandler.mjs";
|
import { Utils, cleanId } from "./Utils.mjs";
|
||||||
import { Message } from "./MessageHandler.mjs";
|
|
||||||
import { SettingsManager } from "./Settings.mjs";
|
|
||||||
import { Utils } from "./Utils.mjs";
|
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
import { get247ChannelMode } from "./constants/Helpers247.mjs";
|
import { get247ChannelMode } from "./constants/Helpers247.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getVoiceManager } from "@fluxerjs/voice";
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
import { getGlobalColor } from "./MessageHandler.mjs";
|
import { getGlobalColor, getMessageGuildId } from "./MessageHandler.mjs";
|
||||||
import { Dashboard } from "./dashboard/Dashboard.mjs";
|
import { Dashboard } from "./dashboard/Dashboard.mjs";
|
||||||
|
import { hasHumansInChannel, iterateVoiceStates } from "./constants/VoiceStateResolver.mjs";
|
||||||
|
|
||||||
/** Helper — build a plain embed payload from a description string */
|
|
||||||
function mkEmbed(desc) {
|
|
||||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] };
|
|
||||||
}
|
|
||||||
|
|
||||||
function cleanId(value) {
|
|
||||||
return String(value ?? "").replace(/\D/g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
function getMessageGuildId(message) {
|
|
||||||
return message?.channel?.guildId ??
|
|
||||||
message?.channel?.guild?.id ??
|
|
||||||
message?.message?.guildId ??
|
|
||||||
message?.message?.guild?.id ??
|
|
||||||
message?.channel?.server_id ??
|
|
||||||
message?.channel?.serverId ??
|
|
||||||
message?.message?.server_id ??
|
|
||||||
message?.message?.serverId ??
|
|
||||||
null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getPlayerGuildId(player, fallbackChannel = null) {
|
function getPlayerGuildId(player, fallbackChannel = null) {
|
||||||
return cleanId(
|
return cleanId(
|
||||||
@@ -72,7 +55,8 @@ function botHasVoicePermissions(client, channelId) {
|
|||||||
if (!perms) return true;
|
if (!perms) return true;
|
||||||
if (perms.has(0x8)) return true;
|
if (perms.has(0x8)) return true;
|
||||||
return perms.has(0x400) && perms.has(0x100000) && perms.has(0x200000);
|
return perms.has(0x400) && perms.has(0x100000) && perms.has(0x200000);
|
||||||
} catch (_) {
|
} catch (e) {
|
||||||
|
logger.warn("[PlayerManager] botHasVoicePermissions check failed:", e?.message);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,6 +97,9 @@ function sanitizeJoinError(err, client = null, channelId = null) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PlayerManager class.
|
||||||
|
*/
|
||||||
export class PlayerManager {
|
export class PlayerManager {
|
||||||
/** @type {SettingsManager} */
|
/** @type {SettingsManager} */
|
||||||
settings;
|
settings;
|
||||||
@@ -436,122 +423,73 @@ export class PlayerManager {
|
|||||||
/**
|
/**
|
||||||
* Attempt to detect the voice channel a user is currently in.
|
* Attempt to detect the voice channel a user is currently in.
|
||||||
* @param {Message} message
|
* @param {Message} message
|
||||||
* @returns {string|null} Voice channel ID or null
|
* @param {Object} [settings]
|
||||||
|
* @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>}
|
||||||
*/
|
*/
|
||||||
checkVoiceChannels(message) {
|
async checkVoiceChannels(message, settings) {
|
||||||
if (!message) return null;
|
const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message);
|
||||||
|
const userId = message?.author?.id ?? message?.member?.user?.id;
|
||||||
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
if (!guildId || !userId) return { channelId: null, alreadyInVoice: false, hasHumans: false };
|
||||||
|
|
||||||
const userId = message.author?.id ?? message.message?.author?.id;
|
const guild = this.commands?.client?.guilds?.get?.(cleanGuildId);
|
||||||
const guildId = getMessageGuildId(message);
|
|
||||||
|
|
||||||
if (!userId) return null;
|
|
||||||
if (!guildId) return null;
|
|
||||||
|
|
||||||
const cleanGuild = cleanId(guildId);
|
if (this.voiceCache) {
|
||||||
const seedObserved = (channelId) => {
|
const observed = this.voiceCache.getUserLocation(cleanGuildId, userId);
|
||||||
const cleanChannelId = cleanId(channelId);
|
if (observed && observed.channelId) {
|
||||||
if (!cleanChannelId) return null;
|
const alreadyInVoice = this.playerMap.has(cleanId(observed.channelId));
|
||||||
const cache = this.voiceCache ?? this.observedVoiceUsers;
|
const hasHumans = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanId(observed.channelId));
|
||||||
if (cache && !cache.has(userId, cleanGuild)) {
|
return { channelId: observed.channelId, alreadyInVoice, hasHumans };
|
||||||
cache.set(userId, { channelId: cleanChannelId, guildId: cleanGuild });
|
|
||||||
}
|
}
|
||||||
const loc = cache?.get(userId, cleanGuild);
|
|
||||||
return cleanId(loc?.channelId) || cleanChannelId;
|
|
||||||
};
|
|
||||||
|
|
||||||
const cache = this.voiceCache ?? this.observedVoiceUsers;
|
|
||||||
const observed = cache?.get?.(userId, cleanGuild);
|
|
||||||
if (cleanId(observed?.guildId) === cleanGuild) {
|
|
||||||
const observedChannelId = cleanId(observed?.channelId);
|
|
||||||
if (observedChannelId) return observedChannelId;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
const vm = getVoiceManager(this.commands.client);
|
|
||||||
const voiceChannelId = vm?.getVoiceChannelId?.(guildId, userId);
|
|
||||||
const seeded = seedObserved(voiceChannelId);
|
|
||||||
if (seeded) return seeded;
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
try {
|
let channelId = message?.member?.voice?.channelId ?? null;
|
||||||
const vm = getVoiceManager(this.commands.client);
|
|
||||||
if (vm?.voiceStates) {
|
|
||||||
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
|
if (!channelId && guild) {
|
||||||
if (guildVoiceMap && typeof guildVoiceMap.get === "function") {
|
for (const vs of iterateVoiceStates(guild)) {
|
||||||
const vmChannelId = guildVoiceMap.get(userId);
|
if (vs.userId === String(userId) && !vs.isBot) {
|
||||||
const seeded = seedObserved(vmChannelId);
|
channelId = vs.channelId;
|
||||||
if (seeded) return seeded;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
const memberVoiceChannelId =
|
|
||||||
message?.member?.voice?.channelId ??
|
|
||||||
message?.message?.member?.voice?.channelId ??
|
|
||||||
null;
|
|
||||||
{
|
|
||||||
const seeded = seedObserved(memberVoiceChannelId);
|
|
||||||
if (seeded) return seeded;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
|
||||||
const guild =
|
|
||||||
this.commands.client?.guilds?.get?.(guildId) ??
|
|
||||||
this.commands.client?.guilds?.get?.(cleanGuild);
|
|
||||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
|
||||||
if (voiceStates) {
|
|
||||||
if (!Array.isArray(voiceStates) && typeof voiceStates === "object") {
|
|
||||||
const direct = voiceStates[userId];
|
|
||||||
const directChannelId =
|
|
||||||
typeof direct === "string"
|
|
||||||
? direct
|
|
||||||
: direct?.channelId ?? direct?.channel_id ?? null;
|
|
||||||
const seeded = seedObserved(directChannelId);
|
|
||||||
if (seeded) return seeded;
|
|
||||||
}
|
|
||||||
|
|
||||||
const entries = Array.isArray(voiceStates)
|
if (!channelId) {
|
||||||
? voiceStates
|
try {
|
||||||
: typeof voiceStates.values === "function"
|
const vm = getVoiceManager(this.commands?.client);
|
||||||
? voiceStates.values()
|
channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? null;
|
||||||
: Object.values(voiceStates);
|
} catch (e) {
|
||||||
|
logger.warn("[PlayerManager] VoiceManager lookup failed:", e?.message);
|
||||||
for (const state of entries) {
|
|
||||||
const stateUserId = state?.userId ?? state?.user_id ?? state?.id;
|
|
||||||
const stateGuildId = cleanId(state?.guildId ?? state?.guild_id ?? guildId);
|
|
||||||
if (stateUserId !== userId || stateGuildId !== cleanGuild) continue;
|
|
||||||
const seeded = seedObserved(state?.channelId ?? state?.channel_id);
|
|
||||||
if (seeded) return seeded;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
}
|
||||||
|
|
||||||
const liveGuildPlayers = [...this.playerMap.entries()].filter(([channelId, player]) => {
|
|
||||||
const fallbackChannel =
|
if (!channelId && this.voiceCache) {
|
||||||
this.commands.client?.channels?.get?.(channelId) ??
|
const loc = this.voiceCache.getHumanUser(userId);
|
||||||
null;
|
if (loc && cleanId(loc.guildId) === cleanGuildId) {
|
||||||
return getPlayerGuildId(player, fallbackChannel) === cleanGuild && !player?._destroyed;
|
channelId = loc.channelId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!channelId) return { channelId: null, alreadyInVoice: false, hasHumans: false };
|
||||||
|
|
||||||
|
const alreadyInVoice = this.playerMap.has(cleanId(channelId));
|
||||||
|
|
||||||
|
const hasHumansResult = hasHumansInChannel({
|
||||||
|
guildId: cleanGuildId,
|
||||||
|
channelId: cleanId(channelId),
|
||||||
|
client: this.commands?.client,
|
||||||
|
voiceCache: this.voiceCache,
|
||||||
|
observedVoiceUsers: this.observedVoiceUsers,
|
||||||
|
room: this.playerMap.get(cleanId(channelId))?.connection?.room,
|
||||||
|
botId: this.commands?.client?.user?.id,
|
||||||
});
|
});
|
||||||
if (liveGuildPlayers.length === 1) {
|
|
||||||
return getPlayerChannelId(liveGuildPlayers[0][1], liveGuildPlayers[0][0]) || cleanId(liveGuildPlayers[0][0]);
|
return { channelId, alreadyInVoice, hasHumans: hasHumansResult };
|
||||||
}
|
|
||||||
if (liveGuildPlayers.length > 1) {
|
|
||||||
for (const [mapKey, player] of liveGuildPlayers) {
|
|
||||||
try {
|
|
||||||
const room = player?.connection?.room;
|
|
||||||
if (!room?.isConnected || !room.remoteParticipants) continue;
|
|
||||||
for (const [, participant] of room.remoteParticipants) {
|
|
||||||
const pId = participant?.identity ?? participant?.sid;
|
|
||||||
if (pId === userId) {
|
|
||||||
const found = getPlayerChannelId(player, mapKey) || cleanId(mapKey);
|
|
||||||
seedObserved(found);
|
|
||||||
return found;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -566,7 +504,7 @@ export class PlayerManager {
|
|||||||
const guildId = getMessageGuildId(message);
|
const guildId = getMessageGuildId(message);
|
||||||
const cleanGuildId = cleanId(guildId);
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
|
||||||
const userChannelId = this.checkVoiceChannels(message);
|
const { channelId: userChannelId } = await this.checkVoiceChannels(message);
|
||||||
const cleanUserChannelId = cleanId(userChannelId);
|
const cleanUserChannelId = cleanId(userChannelId);
|
||||||
|
|
||||||
if (cleanUserChannelId) {
|
if (cleanUserChannelId) {
|
||||||
@@ -579,7 +517,9 @@ export class PlayerManager {
|
|||||||
if (guildId && textChannelId) {
|
if (guildId && textChannelId) {
|
||||||
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
|
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) {
|
||||||
|
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||||
|
}
|
||||||
return player;
|
return player;
|
||||||
}
|
}
|
||||||
if (this._pendingJoins.has(cleanUserChannelId)) {
|
if (this._pendingJoins.has(cleanUserChannelId)) {
|
||||||
@@ -600,7 +540,7 @@ export class PlayerManager {
|
|||||||
first[1].textChannel = message.channel;
|
first[1].textChannel = message.channel;
|
||||||
return first[1];
|
return first[1];
|
||||||
}
|
}
|
||||||
message.reply(mkEmbed(this._t(message, "responses._common.noVoiceStrict")));
|
message.reply(this._t(message, "responses._common.noVoiceStrict"));
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -614,18 +554,18 @@ export class PlayerManager {
|
|||||||
if (cleanGuildId && textChannelId) {
|
if (cleanGuildId && textChannelId) {
|
||||||
this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId);
|
this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId);
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) {
|
||||||
|
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||||
|
}
|
||||||
return match[1];
|
return match[1];
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldJoin) {
|
if (shouldJoin) {
|
||||||
return new Promise((resolve) => {
|
return this.initPlayer(message, userChannelId);
|
||||||
this.initPlayer(message, userChannelId, (p) => resolve(p));
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const prefix = this.commands.getPrefix(guildId);
|
const prefix = this.commands.getPrefix(guildId);
|
||||||
message.reply(mkEmbed(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix })));
|
message.reply(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix }));
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -633,14 +573,12 @@ export class PlayerManager {
|
|||||||
if (shouldJoin) {
|
if (shouldJoin) {
|
||||||
return this.promptVC(message);
|
return this.promptVC(message);
|
||||||
}
|
}
|
||||||
message.reply(mkEmbed(this._t(message, "responses._common.noVoiceChannel")));
|
message.reply(this._t(message, "responses._common.noVoiceChannel"));
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shouldJoin) {
|
if (shouldJoin) {
|
||||||
return new Promise((resolve) => {
|
return this.initPlayer(message, userChannelId);
|
||||||
this.initPlayer(message, userChannelId, (p) => resolve(p));
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
@@ -652,9 +590,9 @@ export class PlayerManager {
|
|||||||
* @returns {Promise<string|false>}
|
* @returns {Promise<string|false>}
|
||||||
*/
|
*/
|
||||||
async promptVC(msg) {
|
async promptVC(msg) {
|
||||||
const autoDetected = this.checkVoiceChannels(msg);
|
const { channelId: autoDetected } = await this.checkVoiceChannels(msg);
|
||||||
if (autoDetected) {
|
if (autoDetected) {
|
||||||
return new Promise(resolve => this.initPlayer(msg, autoDetected, (p) => resolve(p)));
|
return this.initPlayer(msg, autoDetected);
|
||||||
}
|
}
|
||||||
|
|
||||||
const guildId = getMessageGuildId(msg);
|
const guildId = getMessageGuildId(msg);
|
||||||
@@ -678,9 +616,9 @@ export class PlayerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const hint = this._t(msg, "responses._common.voiceSelectionHint");
|
const hint = this._t(msg, "responses._common.voiceSelectionHint");
|
||||||
const selectionMsg = await msg.reply(mkEmbed(
|
const selectionMsg = await msg.reply(
|
||||||
(channelSelection ? channelSelection + "\n**..or** " + hint : "Please " + hint)
|
(channelSelection ? channelSelection + "\n**..or** " + hint : "Please " + hint)
|
||||||
));
|
);
|
||||||
|
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
let unsubscribeReactions;
|
let unsubscribeReactions;
|
||||||
@@ -694,7 +632,7 @@ export class PlayerManager {
|
|||||||
|
|
||||||
const timeout = setTimeout(() => {
|
const timeout = setTimeout(() => {
|
||||||
cleanup();
|
cleanup();
|
||||||
msg.reply(mkEmbed(this._t(msg, "responses._common.voiceSelectionTimedOut")));
|
msg.reply(this._t(msg, "responses._common.voiceSelectionTimedOut"));
|
||||||
resolve(false);
|
resolve(false);
|
||||||
}, 30_000);
|
}, 30_000);
|
||||||
|
|
||||||
@@ -708,7 +646,7 @@ export class PlayerManager {
|
|||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
cleanup();
|
cleanup();
|
||||||
const cid = channel._id ?? channel.id;
|
const cid = channel._id ?? channel.id;
|
||||||
this.initPlayer(msg, cid, (p) => resolve(p));
|
this.initPlayer(msg, cid).then(p => resolve(p));
|
||||||
},
|
},
|
||||||
promptUser
|
promptUser
|
||||||
);
|
);
|
||||||
@@ -719,18 +657,18 @@ export class PlayerManager {
|
|||||||
if (content === "x") {
|
if (content === "x") {
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
cleanup();
|
cleanup();
|
||||||
m.reply(mkEmbed(this._t(m, "voice.join.cancelled")));
|
m.reply(this._t(m, "voice.join.cancelled"));
|
||||||
resolve(false);
|
resolve(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!this.commands.validateInput("voiceChannel", m.content, m)) {
|
if (!this.commands.validateInput("voiceChannel", m.content, m)) {
|
||||||
m.reply(mkEmbed(this._t(m, "responses._common.voiceSelectionInvalid")));
|
m.reply(this._t(m, "responses._common.voiceSelectionInvalid"));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const channel = this.commands.formatInput("voiceChannel", m.content, m);
|
const channel = this.commands.formatInput("voiceChannel", m.content, m);
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
cleanup();
|
cleanup();
|
||||||
this.initPlayer(m, channel, (p) => resolve(p));
|
this.initPlayer(m, channel).then(p => resolve(p));
|
||||||
}, promptUser);
|
}, promptUser);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -757,7 +695,7 @@ export class PlayerManager {
|
|||||||
? this.playerMap.get(cleanChannelId) ??
|
? this.playerMap.get(cleanChannelId) ??
|
||||||
this.getPlayerByChannelId(cleanChannelId)
|
this.getPlayerByChannelId(cleanChannelId)
|
||||||
: null;
|
: null;
|
||||||
if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice")));
|
if (!player) return msg.reply(this._t(msg, "responses._common.notInVoice"));
|
||||||
|
|
||||||
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
|
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
|
||||||
this.playerMap.delete(activeChannelId);
|
this.playerMap.delete(activeChannelId);
|
||||||
@@ -771,37 +709,50 @@ export class PlayerManager {
|
|||||||
logger.warn("[PlayerManager] leave() error (non-fatal):", e.message);
|
logger.warn("[PlayerManager] leave() error (non-fatal):", e.message);
|
||||||
}
|
}
|
||||||
player.destroy();
|
player.destroy();
|
||||||
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
|
await msg.reply(this._t(msg, "responses._common.successfullyLeft"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restore saved volume for a player from server settings.
|
||||||
|
* @param {Player} player
|
||||||
|
* @param {string} guildId
|
||||||
|
*/
|
||||||
|
_restorePlayerVolume(player, guildId) {
|
||||||
|
const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume");
|
||||||
|
if (savedVol !== undefined && savedVol !== null) {
|
||||||
|
const vol = Number(savedVol);
|
||||||
|
if (!isNaN(vol)) player.setVolume(vol / 100);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create and register a new Player for the given voice channel.
|
* Create and register a new Player for the given voice channel.
|
||||||
* @param {Message} message
|
* @param {Message} message
|
||||||
* @param {string} cid - Voice channel ID
|
* @param {string} cid - Voice channel ID
|
||||||
* @param {Function} [cb]
|
* @returns {Promise<Player|null>}
|
||||||
*/
|
*/
|
||||||
initPlayer(message, cid, cb = () => {}) {
|
async initPlayer(message, cid) {
|
||||||
const channel = this.commands.client?.channels?.get(cid);
|
const channel = this.commands.client?.channels?.get(cid);
|
||||||
|
|
||||||
if (!channel) {
|
if (!channel) {
|
||||||
cb(null);
|
message.reply(
|
||||||
return message.reply(mkEmbed(
|
|
||||||
this._t(message, "responses.join.channelNotFound", { channel: cid })
|
this._t(message, "responses.join.channelNotFound", { channel: cid })
|
||||||
));
|
);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isVoice = channel.type === 2;
|
const isVoice = channel.type === 2;
|
||||||
|
|
||||||
if (!isVoice) {
|
if (!isVoice) {
|
||||||
cb(null);
|
message.reply(this._t(message, "responses._common.voiceChannelRequired"));
|
||||||
return message.reply(mkEmbed(this._t(message, "responses._common.voiceChannelRequired")));
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!botHasVoicePermissions(this.commands?.client, cid)) {
|
if (!botHasVoicePermissions(this.commands?.client, cid)) {
|
||||||
cb(null);
|
message.reply(
|
||||||
return message.reply(mkEmbed(
|
|
||||||
this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanId(cid)}>` })
|
this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanId(cid)}>` })
|
||||||
));
|
);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const cleanChannelId = cleanId(cid);
|
const cleanChannelId = cleanId(cid);
|
||||||
@@ -809,12 +760,12 @@ export class PlayerManager {
|
|||||||
?? this.getPlayerByChannelId(cleanChannelId);
|
?? this.getPlayerByChannelId(cleanChannelId);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
existing.textChannel = message.channel;
|
existing.textChannel = message.channel;
|
||||||
cb(existing);
|
message.reply(this._t(message, "responses.join.alreadyJoined", { channel: cid }));
|
||||||
return message.reply(mkEmbed(this._t(message, "responses.join.alreadyJoined", { channel: cid })));
|
return existing;
|
||||||
}
|
}
|
||||||
if (this._pendingJoins.has(cleanChannelId)) {
|
if (this._pendingJoins.has(cleanChannelId)) {
|
||||||
cb(null);
|
message.reply(this._t(message, "responses.join.joining"));
|
||||||
return message.reply(mkEmbed(this._t(message, "responses.join.joining")));
|
return null;
|
||||||
}
|
}
|
||||||
this._pendingJoins.add(cleanChannelId);
|
this._pendingJoins.add(cleanChannelId);
|
||||||
|
|
||||||
@@ -846,19 +797,19 @@ export class PlayerManager {
|
|||||||
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
|
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
|
||||||
|
|
||||||
const raw247 = (() => {
|
const raw247 = (() => {
|
||||||
try { return this.settings.getServer(guildId)?.get("stay_247"); } catch (_) { return null; }
|
try { return this.settings.getServer(guildId)?.get("stay_247"); } catch (e) { logger.warn("[PlayerManager] Failed to read 24/7 setting:", e?.message); return null; }
|
||||||
})();
|
})();
|
||||||
const isIn247List = (() => {
|
const isIn247List = (() => {
|
||||||
if (!raw247 || raw247 === "none") return false;
|
if (!raw247 || raw247 === "none") return false;
|
||||||
const channels = Array.isArray(raw247)
|
const channels = Array.isArray(raw247)
|
||||||
? raw247.map(id => String(id).replace(/\D/g, "")).filter(Boolean)
|
? raw247.map(id => cleanId(id)).filter(Boolean)
|
||||||
: [String(raw247).replace(/\D/g, "")].filter(Boolean);
|
: [cleanId(raw247)].filter(Boolean);
|
||||||
return channels.includes(homeChannelId) || channels.includes(activeChannelId);
|
return channels.includes(homeChannelId) || channels.includes(activeChannelId);
|
||||||
})();
|
})();
|
||||||
|
|
||||||
const matchChannel = isIn247List
|
const matchChannel = isIn247List
|
||||||
? (channels247list => channels247list.includes(homeChannelId) ? homeChannelId : activeChannelId)(
|
? (channels247list => channels247list.includes(homeChannelId) ? homeChannelId : activeChannelId)(
|
||||||
Array.isArray(raw247) ? raw247.map(id => String(id).replace(/\D/g, "")) : [String(raw247).replace(/\D/g, "")]
|
Array.isArray(raw247) ? raw247.map(id => cleanId(id)) : [cleanId(raw247)]
|
||||||
)
|
)
|
||||||
: null;
|
: null;
|
||||||
const mode247 = matchChannel
|
const mode247 = matchChannel
|
||||||
@@ -900,7 +851,7 @@ export class PlayerManager {
|
|||||||
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
|
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
|
||||||
}
|
}
|
||||||
if (typeof ch?.send === "function") {
|
if (typeof ch?.send === "function") {
|
||||||
ch.send(mkEmbed(desc)).catch(err => {
|
ch.send({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }).catch(err => {
|
||||||
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||||
logger.warn(`[PlayerManager] Cannot send autoleave message in channel ${ch.id} — missing permissions`);
|
logger.warn(`[PlayerManager] Cannot send autoleave message in channel ${ch.id} — missing permissions`);
|
||||||
}
|
}
|
||||||
@@ -922,9 +873,11 @@ export class PlayerManager {
|
|||||||
const serverSettings = this.settings.getServer(guildId);
|
const serverSettings = this.settings.getServer(guildId);
|
||||||
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
|
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
|
||||||
if (savedAnnChId) {
|
if (savedAnnChId) {
|
||||||
ch = this.commands?.client?.channels?.get?.(String(savedAnnChId).replace(/\D/g, "")) ?? null;
|
ch = this.commands?.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) {
|
||||||
|
logger.warn("[PlayerManager] Failed to resolve announcement channel:", e?.message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!ch || typeof ch.send !== "function") {
|
if (!ch || typeof ch.send !== "function") {
|
||||||
try {
|
try {
|
||||||
@@ -932,7 +885,9 @@ export class PlayerManager {
|
|||||||
if (guild?.systemChannelId) {
|
if (guild?.systemChannelId) {
|
||||||
ch = guild.channels?.get?.(guild.systemChannelId) ?? null;
|
ch = guild.channels?.get?.(guild.systemChannelId) ?? null;
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) {
|
||||||
|
logger.warn("[PlayerManager] Failed to resolve system channel:", e?.message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!ch || typeof ch.send !== "function") {
|
if (!ch || typeof ch.send !== "function") {
|
||||||
try {
|
try {
|
||||||
@@ -945,89 +900,76 @@ export class PlayerManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) {
|
||||||
|
logger.warn("[PlayerManager] Failed to find fallback text channel:", e?.message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (!ch || typeof ch.send !== "function") return;
|
if (!ch || typeof ch.send !== "function") return;
|
||||||
|
|
||||||
if (!player.textChannel) player.textChannel = ch;
|
if (!player.textChannel) player.textChannel = ch;
|
||||||
|
|
||||||
ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)).catch(err => {
|
ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)] }).catch(err => {
|
||||||
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||||
logger.warn(`[PlayerManager] Cannot send player message in channel ${ch.id} — missing permissions`);
|
logger.warn(`[PlayerManager] Cannot send player message in channel ${ch.id} — missing permissions`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
(async () => {
|
const statusMsg = await message.reply(this._t(message, "responses.join.joining"));
|
||||||
const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining")));
|
try {
|
||||||
try {
|
await player.join(cid);
|
||||||
await player.join(cid);
|
|
||||||
|
|
||||||
this.playerMap.set(cleanChannelId, player);
|
this.playerMap.set(cleanChannelId, player);
|
||||||
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||||
this._pendingJoins.delete(cleanChannelId);
|
this._pendingJoins.delete(cleanChannelId);
|
||||||
|
|
||||||
await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid })));
|
await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid }));
|
||||||
|
|
||||||
const guildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
const guildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
||||||
if (guildId) {
|
this._restorePlayerVolume(player, guildId);
|
||||||
const savedVol = this.settings.getServer(guildId)?.get("volume");
|
|
||||||
if (savedVol !== undefined && savedVol !== null) {
|
return player;
|
||||||
const vol = Number(savedVol);
|
} catch (err) {
|
||||||
if (!isNaN(vol)) player.setVolume(vol / 100);
|
this._pendingJoins.delete(cleanChannelId);
|
||||||
|
|
||||||
|
const errCode = sanitizeJoinError(err, this.commands?.client, cleanChannelId);
|
||||||
|
let errorMsg;
|
||||||
|
if (errCode === "SESSION_RACE") {
|
||||||
|
logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`);
|
||||||
|
try {
|
||||||
|
await new Promise(r => setTimeout(r, 2_000));
|
||||||
|
if (player._revoice && player._channelId) {
|
||||||
|
try { player._revoice._leaveGateway(player._channelId, player._guildId ?? player._resolveGuildId()); } catch(e) { logger.warn("[PlayerManager] Failed to leave gateway during retry:", e?.message); }
|
||||||
|
try { player._revoice.deleteConnection(player._channelId); } catch(e) { logger.warn("[PlayerManager] Failed to delete connection during retry:", e?.message); }
|
||||||
}
|
}
|
||||||
|
await player.join(cid);
|
||||||
|
|
||||||
|
this.playerMap.set(cleanChannelId, player);
|
||||||
|
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||||
|
await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid }));
|
||||||
|
|
||||||
|
const retryGuildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
||||||
|
this._restorePlayerVolume(player, retryGuildId);
|
||||||
|
return player;
|
||||||
|
} catch (retryErr) {
|
||||||
|
logger.warn(`[PlayerManager] Retry also failed for channel ${cleanChannelId}: ${retryErr.message}`);
|
||||||
|
errorMsg = this._t(message, "responses.join.joinFailedGeneric");
|
||||||
}
|
}
|
||||||
|
} else if (errCode === "PERMISSION") {
|
||||||
cb(player);
|
errorMsg = this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanChannelId}>` });
|
||||||
} catch (err) {
|
} else if (errCode === "NOT_FOUND") {
|
||||||
this._pendingJoins.delete(cleanChannelId);
|
errorMsg = this._t(message, "responses.join.joinFailedNotFound");
|
||||||
|
} else if (errCode === "TIMEOUT") {
|
||||||
const errCode = sanitizeJoinError(err, this.commands?.client, cleanChannelId);
|
errorMsg = this._t(message, "responses.join.joinFailed");
|
||||||
let errorMsg;
|
} else {
|
||||||
if (errCode === "SESSION_RACE") {
|
errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message });
|
||||||
logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`);
|
|
||||||
try {
|
|
||||||
await new Promise(r => setTimeout(r, 2_000));
|
|
||||||
if (player._revoice && player._channelId) {
|
|
||||||
try { player._revoice._leaveGateway(player._channelId, player._guildId ?? player._resolveGuildId()); } catch (_) {}
|
|
||||||
try { player._revoice.deleteConnection(player._channelId); } catch (_) {}
|
|
||||||
}
|
|
||||||
await player.join(cid);
|
|
||||||
|
|
||||||
this.playerMap.set(cleanChannelId, player);
|
|
||||||
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
|
||||||
await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid })));
|
|
||||||
|
|
||||||
const retryGuildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
|
||||||
if (retryGuildId) {
|
|
||||||
const savedVol = this.settings.getServer(retryGuildId)?.get("volume");
|
|
||||||
if (savedVol !== undefined && savedVol !== null) {
|
|
||||||
const vol = Number(savedVol);
|
|
||||||
if (!isNaN(vol)) player.setVolume(vol / 100);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
cb(player);
|
|
||||||
return;
|
|
||||||
} catch (retryErr) {
|
|
||||||
logger.warn(`[PlayerManager] Retry also failed for channel ${cleanChannelId}: ${retryErr.message}`);
|
|
||||||
errorMsg = this._t(message, "responses.join.joinFailedGeneric");
|
|
||||||
}
|
|
||||||
} else if (errCode === "PERMISSION") {
|
|
||||||
errorMsg = this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanChannelId}>` });
|
|
||||||
} else if (errCode === "NOT_FOUND") {
|
|
||||||
errorMsg = this._t(message, "responses.join.joinFailedNotFound");
|
|
||||||
} else if (errCode === "TIMEOUT") {
|
|
||||||
errorMsg = this._t(message, "responses.join.joinFailed");
|
|
||||||
} else {
|
|
||||||
errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message });
|
|
||||||
}
|
|
||||||
await statusMsg.edit(mkEmbed(errorMsg)).catch(() => {});
|
|
||||||
this.playerMap.delete(cleanChannelId);
|
|
||||||
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
|
||||||
player.destroy();
|
|
||||||
cb(null);
|
|
||||||
}
|
}
|
||||||
})();
|
await statusMsg.edit(errorMsg).catch(() => {});
|
||||||
|
this.playerMap.delete(cleanChannelId);
|
||||||
|
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||||
|
player.destroy();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+31
-34
@@ -1,10 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* @file Settings.mjs — Settings — abstract base class and RemoteSettingsManager for per-server configuration backed by SQLite
|
||||||
|
* @module src.Settings
|
||||||
|
*/
|
||||||
|
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
import mysql from "mysql2";
|
import mysql from "mysql2";
|
||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
|
|
||||||
export { SettingsManager } from "../settings/Settings.mjs";
|
/**
|
||||||
|
* Abstract base class for settings managers.
|
||||||
|
* Provides the interface that all concrete settings managers must implement.
|
||||||
|
*/
|
||||||
|
export class SettingsManager extends EventEmitter {
|
||||||
|
/** @abstract @type {Object} */
|
||||||
|
defaults;
|
||||||
|
/** @abstract */
|
||||||
|
update(server, key) { }
|
||||||
|
/** @abstract @returns {ServerSettings} */
|
||||||
|
getServer(id) { }
|
||||||
|
/** @abstract @returns {boolean} */
|
||||||
|
hasServer(id) { }
|
||||||
|
/** @abstract @returns {boolean} */
|
||||||
|
isOption(key) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ServerSettings class.
|
||||||
|
*/
|
||||||
export class ServerSettings {
|
export class ServerSettings {
|
||||||
id;
|
id;
|
||||||
manager;
|
manager;
|
||||||
@@ -20,16 +43,20 @@ export class ServerSettings {
|
|||||||
reset(key) { return this.set(key, this.manager.defaults[key]); }
|
reset(key) { return this.set(key, this.manager.defaults[key]); }
|
||||||
getAll() { return this.data; }
|
getAll() { return this.data; }
|
||||||
loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } }
|
loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } }
|
||||||
deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } }
|
|
||||||
|
|
||||||
checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
|
checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
|
||||||
|
|
||||||
|
deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } }
|
||||||
|
|
||||||
get serializationData() { return { ...this.data, id: this.id }; }
|
get serializationData() { return { ...this.data, id: this.id }; }
|
||||||
serialize() { return this.serializationData; }
|
serialize() { return this.serializationData; }
|
||||||
serializeObject() { return this.serializationData; }
|
serializeObject() { return this.serializationData; }
|
||||||
}
|
}
|
||||||
|
|
||||||
export class RemoteSettingsManager extends EventEmitter {
|
/**
|
||||||
|
* RemoteSettingsManager class.
|
||||||
|
*/
|
||||||
|
export class RemoteSettingsManager extends SettingsManager {
|
||||||
guilds = new Map();
|
guilds = new Map();
|
||||||
descriptions = {};
|
descriptions = {};
|
||||||
defaults = {};
|
defaults = {};
|
||||||
@@ -61,11 +88,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
* adding it (NOT NULL DEFAULT '') and updating the primary key to (id, bot_id).
|
* adding it (NOT NULL DEFAULT '') and updating the primary key to (id, bot_id).
|
||||||
* If the column exists but isn't in the PK (previous failed migration),
|
* If the column exists but isn't in the PK (previous failed migration),
|
||||||
* fix the NULL values and retry the PK update.
|
* fix the NULL values and retry the PK update.
|
||||||
*
|
|
||||||
* Key detail: MySQL primary key columns CANNOT be NULL. The previous version
|
|
||||||
* used DEFAULT NULL which caused ALTER TABLE ... ADD PRIMARY KEY to fail
|
|
||||||
* silently, leaving the PK as just (id) and producing ER_DUP_ENTRY errors
|
|
||||||
* when two bots tried to INSERT rows for the same guild.
|
|
||||||
*/
|
*/
|
||||||
async _ensureBotIdColumn() {
|
async _ensureBotIdColumn() {
|
||||||
if (this._hasBotIdColumn) return;
|
if (this._hasBotIdColumn) return;
|
||||||
@@ -147,8 +169,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
/**
|
/**
|
||||||
* Set or update the bot ID used for database row isolation.
|
* Set or update the bot ID used for database row isolation.
|
||||||
* Called after login when the bot user ID becomes available.
|
* Called after login when the bot user ID becomes available.
|
||||||
* Ensures the bot_id column exists (auto-migrates if needed), then
|
|
||||||
* reloads guild data filtered by the bot's ID.
|
|
||||||
* @param {string} id
|
* @param {string} id
|
||||||
*/
|
*/
|
||||||
async setBotId(id) {
|
async setBotId(id) {
|
||||||
@@ -173,34 +193,16 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the SQL WHERE clause fragment for bot_id filtering.
|
|
||||||
* When botId is set AND the bot_id column exists in the table,
|
|
||||||
* includes "AND bot_id = <escaped>" in queries.
|
|
||||||
* Otherwise no filter is applied (backward-compatible with old schemas).
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
_botIdWhere() {
|
_botIdWhere() {
|
||||||
if (!this.botId || !this._hasBotIdColumn) return "";
|
if (!this.botId || !this._hasBotIdColumn) return "";
|
||||||
return ` AND bot_id = ${mysql.escape(String(this.botId))}`;
|
return ` AND bot_id = ${mysql.escape(String(this.botId))}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the bot_id column + value for INSERT statements.
|
|
||||||
* Only includes bot_id when both the botId is set AND the column exists.
|
|
||||||
* @returns {{ col: string, val: string }}
|
|
||||||
*/
|
|
||||||
_botIdInsert() {
|
_botIdInsert() {
|
||||||
if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" };
|
if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" };
|
||||||
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
|
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch a single guild's settings row from the database, filtered by bot_id.
|
|
||||||
* Used by GatewayHandler when a guild is (re-)joined and not in the cache.
|
|
||||||
* @param {string} guildId
|
|
||||||
* @returns {Promise<{error: object|null, results: Array, fields: Array}>}
|
|
||||||
*/
|
|
||||||
selectGuild(guildId) {
|
selectGuild(guildId) {
|
||||||
const escapedId = mysql.escape(String(guildId));
|
const escapedId = mysql.escape(String(guildId));
|
||||||
return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`);
|
return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`);
|
||||||
@@ -284,7 +286,7 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
update(server, key) {
|
update(server, key) {
|
||||||
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); }
|
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server).catch(e => logger.error("[Settings] create error in update:", e.message)); }
|
||||||
const s = this.guilds.get(server.id);
|
const s = this.guilds.get(server.id);
|
||||||
s.data[key] = server.data[key];
|
s.data[key] = server.data[key];
|
||||||
const existing = this._debounceTimers.get(server.id);
|
const existing = this._debounceTimers.get(server.id);
|
||||||
@@ -305,11 +307,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
return this.guilds.get(id);
|
return this.guilds.get(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Drop a server from the in-memory cache without touching the DB row.
|
|
||||||
* This lets settings be restored automatically if the bot is re-invited.
|
|
||||||
* @param {string} id - Guild / server ID
|
|
||||||
*/
|
|
||||||
removeServer(id) {
|
removeServer(id) {
|
||||||
const timer = this._debounceTimers.get(id);
|
const timer = this._debounceTimers.get(id);
|
||||||
if (timer) {
|
if (timer) {
|
||||||
|
|||||||
@@ -1,9 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* @file TrackOptionsManager.mjs — TrackOptionsManager — SQLite-backed per-track options storage for auto-seek and end-time timers
|
||||||
|
* @module src.TrackOptionsManager
|
||||||
|
*/
|
||||||
|
|
||||||
import mysql from "mysql2";
|
import mysql from "mysql2";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
|
|
||||||
const DEFAULT_ALIAS = "default";
|
const DEFAULT_ALIAS = "default";
|
||||||
const MAX_ALIAS_LEN = 32;
|
const MAX_ALIAS_LEN = 32;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TrackOptionsManager class.
|
||||||
|
*/
|
||||||
export class TrackOptionsManager {
|
export class TrackOptionsManager {
|
||||||
db = null;
|
db = null;
|
||||||
botId = null;
|
botId = null;
|
||||||
@@ -194,9 +202,11 @@ export class TrackOptionsManager {
|
|||||||
this._cache.delete(`${userId}:${identifier}:${safeAlias}`);
|
this._cache.delete(`${userId}:${identifier}:${safeAlias}`);
|
||||||
} else {
|
} else {
|
||||||
sql = `DELETE FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)}${this._botIdWhere()}`;
|
sql = `DELETE FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)}${this._botIdWhere()}`;
|
||||||
|
const keysToDelete = [];
|
||||||
for (const key of this._cache.keys()) {
|
for (const key of this._cache.keys()) {
|
||||||
if (key.startsWith(`${userId}:${identifier}:`)) this._cache.delete(key);
|
if (key.startsWith(`${userId}:${identifier}:`)) keysToDelete.push(key);
|
||||||
}
|
}
|
||||||
|
for (const key of keysToDelete) this._cache.delete(key);
|
||||||
}
|
}
|
||||||
const result = await this._query(sql);
|
const result = await this._query(sql);
|
||||||
return result.affectedRows > 0;
|
return result.affectedRows > 0;
|
||||||
|
|||||||
+50
-188
@@ -1,8 +1,28 @@
|
|||||||
/**
|
/**
|
||||||
* Utils.mjs — Utility functions for the music bot
|
* @file Utils.mjs — Utility class with static helpers — text normalization, markdown escaping, duration parsing, and string truncation
|
||||||
* @module Utils
|
* @module src.Utils
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utils.mjs — Music bot utility functions
|
||||||
|
* @module Utils
|
||||||
|
*
|
||||||
|
* Internal helpers delegate to @fluxerjs/util where available
|
||||||
|
* (escapeMarkdown, truncate) with additional null-safety guards.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { escapeMarkdown as _escapeMarkdown, truncate as _truncate } from "@fluxerjs/util";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strip non-digit characters from a value, returning a clean ID string.
|
||||||
|
* Replaces the inline `String(x).replace(/\D/g, "")` pattern used 97+ times.
|
||||||
|
* @param {string|number} value
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function cleanId(value) {
|
||||||
|
return String(value ?? "").replace(/\D/g, "");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @class Utils
|
* @class Utils
|
||||||
* @description Static utility methods for time formatting, array manipulation,
|
* @description Static utility methods for time formatting, array manipulation,
|
||||||
@@ -14,8 +34,6 @@ export class Utils {
|
|||||||
* Format milliseconds to human-readable time string (H:MM:SS or M:SS)
|
* Format milliseconds to human-readable time string (H:MM:SS or M:SS)
|
||||||
* @param {number} milliseconds - Duration in milliseconds
|
* @param {number} milliseconds - Duration in milliseconds
|
||||||
* @returns {string} Formatted time string
|
* @returns {string} Formatted time string
|
||||||
* @example Utils.prettifyMS(125000)
|
|
||||||
* @example Utils.prettifyMS(3661000)
|
|
||||||
*/
|
*/
|
||||||
static prettifyMS(milliseconds) {
|
static prettifyMS(milliseconds) {
|
||||||
if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) {
|
if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) {
|
||||||
@@ -35,12 +53,17 @@ export class Utils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse duration string (H:MM:SS or M:SS) to milliseconds
|
* Parse duration string (H:MM:SS or M:SS or raw seconds) to milliseconds.
|
||||||
* @param {string} str - Duration string
|
* @param {string} str - Duration string
|
||||||
* @returns {number} Milliseconds, 0 if invalid
|
* @returns {number} Milliseconds, 0 if invalid
|
||||||
*/
|
*/
|
||||||
static parseDuration(str) {
|
static parseDuration(str) {
|
||||||
if (!str || typeof str !== "string") return 0;
|
if (!str || typeof str !== "string") return 0;
|
||||||
|
str = str.trim();
|
||||||
|
|
||||||
|
if (/^\d+$/.test(str)) {
|
||||||
|
return parseInt(str, 10) * 1000;
|
||||||
|
}
|
||||||
|
|
||||||
const parts = str.split(":").map((s) => parseInt(s.trim(), 10)).reverse();
|
const parts = str.split(":").map((s) => parseInt(s.trim(), 10)).reverse();
|
||||||
if (parts.some(isNaN) || parts.some(n => n < 0)) return 0;
|
if (parts.some(isNaN) || parts.some(n => n < 0)) return 0;
|
||||||
@@ -79,45 +102,6 @@ export class Utils {
|
|||||||
return array;
|
return array;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Get random element from array
|
|
||||||
* @template T
|
|
||||||
* @param {T[]} array - Source array
|
|
||||||
* @returns {T | undefined} Random element or undefined if empty
|
|
||||||
*/
|
|
||||||
static randomElement(array) {
|
|
||||||
if (!Array.isArray(array) || array.length === 0) return undefined;
|
|
||||||
return array[Math.floor(Math.random() * array.length)];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Chunk array into smaller arrays
|
|
||||||
* @template T
|
|
||||||
* @param {T[]} array - Array to chunk
|
|
||||||
* @param {number} size - Chunk size (minimum 1)
|
|
||||||
* @returns {T[][]} Array of chunks
|
|
||||||
*/
|
|
||||||
static chunk(array, size) {
|
|
||||||
if (!Array.isArray(array)) return [];
|
|
||||||
const chunkSize = Math.max(1, Math.floor(size));
|
|
||||||
const chunks = [];
|
|
||||||
for (let i = 0; i < array.length; i += chunkSize) {
|
|
||||||
chunks.push(array.slice(i, i + chunkSize));
|
|
||||||
}
|
|
||||||
return chunks;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove duplicates from array (primitive values only)
|
|
||||||
* @template T
|
|
||||||
* @param {T[]} array - Array with potential duplicates
|
|
||||||
* @returns {T[]} New array without duplicates
|
|
||||||
*/
|
|
||||||
static unique(array) {
|
|
||||||
if (!Array.isArray(array)) return [];
|
|
||||||
return [...new Set(array)];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Truncate text with ellipsis
|
* Truncate text with ellipsis
|
||||||
* @param {string} str - String to truncate
|
* @param {string} str - String to truncate
|
||||||
@@ -171,34 +155,14 @@ export class Utils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sanitize string for safe filename
|
* Escape markdown formatting characters.
|
||||||
* @param {string} str - Input string
|
* Delegates to @fluxerjs/util escapeMarkdown.
|
||||||
* @param {number} [maxLen=50] - Maximum length
|
|
||||||
* @returns {string} Safe filename
|
|
||||||
*/
|
|
||||||
static sanitizeFilename(str, maxLen = 50) {
|
|
||||||
if (!str || typeof str !== "string") return "unknown";
|
|
||||||
return str
|
|
||||||
.replace(/[^a-z0-9\u4e00-\u9fa5]/gi, "_")
|
|
||||||
.replace(/_{2,}/g, "_")
|
|
||||||
.substring(0, maxLen)
|
|
||||||
.replace(/^_+|_+$/g, "");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} text - Raw text
|
* @param {string} text - Raw text
|
||||||
* @returns {string} Escaped text
|
* @returns {string} Escaped text
|
||||||
*/
|
*/
|
||||||
static escapeMarkdown(text) {
|
static escapeMarkdown(text) {
|
||||||
if (!text || typeof text !== "string") return "";
|
if (!text || typeof text !== "string") return "";
|
||||||
return text
|
return _escapeMarkdown(text);
|
||||||
.replace(/\\/g, "\\\\")
|
|
||||||
.replace(/`/g, "\\`")
|
|
||||||
.replace(/\*/g, "\\*")
|
|
||||||
.replace(/_/g, "\\_")
|
|
||||||
.replace(/~/g, "\\~")
|
|
||||||
.replace(/\|/g, "\\|")
|
|
||||||
.replace(/>/g, "\\>");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -211,23 +175,6 @@ export class Utils {
|
|||||||
return num.toLocaleString("en-US");
|
return num.toLocaleString("en-US");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Format bytes to human readable (KB, MB, GB)
|
|
||||||
* @param {number} bytes - Bytes to format
|
|
||||||
* @param {number} [decimals=2] - Decimal places
|
|
||||||
* @returns {string} Human readable size
|
|
||||||
*/
|
|
||||||
static formatBytes(bytes, decimals = 2) {
|
|
||||||
if (bytes === 0) return "0 Bytes";
|
|
||||||
if (!bytes || bytes < 0 || !isFinite(bytes)) return "Unknown";
|
|
||||||
|
|
||||||
const k = 1024;
|
|
||||||
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
|
|
||||||
const i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1);
|
|
||||||
|
|
||||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate random unique ID
|
* Generate random unique ID
|
||||||
* @param {number} [length=16] - Desired length of ID (8-32 recommended)
|
* @param {number} [length=16] - Desired length of ID (8-32 recommended)
|
||||||
@@ -246,18 +193,6 @@ export class Utils {
|
|||||||
return (timestamp + random).substring(0, targetLen);
|
return (timestamp + random).substring(0, targetLen);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Generate UUID v4 (RFC4122 compliant)
|
|
||||||
* @returns {string} UUID string
|
|
||||||
*/
|
|
||||||
static uuid() {
|
|
||||||
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
||||||
const r = (Math.random() * 16) | 0;
|
|
||||||
const v = c === "x" ? r : (r & 0x3) | 0x8;
|
|
||||||
return v.toString(16);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if a value represents a finite number
|
* Check if a value represents a finite number
|
||||||
* @param {string|number} str
|
* @param {string|number} str
|
||||||
@@ -298,22 +233,6 @@ export class Utils {
|
|||||||
return Math.max(min, Math.min(max, num));
|
return Math.max(min, Math.min(max, num));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Safe JSON parse with fallback
|
|
||||||
* @template T
|
|
||||||
* @param {string} str - JSON string
|
|
||||||
* @param {T} [fallback=null] - Fallback value on error
|
|
||||||
* @returns {T | null} Parsed object or fallback
|
|
||||||
*/
|
|
||||||
static safeJsonParse(str, fallback = null) {
|
|
||||||
if (!str || typeof str !== "string") return fallback;
|
|
||||||
try {
|
|
||||||
return JSON.parse(str);
|
|
||||||
} catch {
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sleep/delay promise
|
* Sleep/delay promise
|
||||||
* @param {number} ms - Milliseconds to sleep
|
* @param {number} ms - Milliseconds to sleep
|
||||||
@@ -323,34 +242,6 @@ export class Utils {
|
|||||||
return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
|
return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Retry an async operation with exponential backoff
|
|
||||||
* @template T
|
|
||||||
* @param {() => Promise<T>} fn - Function to retry
|
|
||||||
* @param {number} [attempts=3] - Max retry attempts
|
|
||||||
* @param {number} [delay=1000] - Initial delay in ms
|
|
||||||
* @param {number} [backoff=2] - Backoff multiplier
|
|
||||||
* @returns {Promise<T>}
|
|
||||||
*/
|
|
||||||
static async retry(fn, attempts = 3, delay = 1000, backoff = 2) {
|
|
||||||
if (typeof fn !== "function") {
|
|
||||||
throw new TypeError("First argument must be a function");
|
|
||||||
}
|
|
||||||
|
|
||||||
let lastError;
|
|
||||||
for (let i = 0; i < attempts; i++) {
|
|
||||||
try {
|
|
||||||
return await fn();
|
|
||||||
} catch (err) {
|
|
||||||
lastError = err;
|
|
||||||
if (i < attempts - 1) {
|
|
||||||
await this.sleep(delay * Math.pow(backoff, i));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw lastError;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Timeout wrapper for promises
|
* Timeout wrapper for promises
|
||||||
* @template T
|
* @template T
|
||||||
@@ -367,53 +258,6 @@ export class Utils {
|
|||||||
return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timerId));
|
return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timerId));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Deep clone an object (JSON method - not suitable for circular refs)
|
|
||||||
* @template T
|
|
||||||
* @param {T} obj - Object to clone
|
|
||||||
* @returns {T} Cloned object
|
|
||||||
*/
|
|
||||||
static deepClone(obj) {
|
|
||||||
if (obj === null || typeof obj !== "object") return obj;
|
|
||||||
try {
|
|
||||||
return JSON.parse(JSON.stringify(obj));
|
|
||||||
} catch {
|
|
||||||
return obj;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pick specific keys from object
|
|
||||||
* @template T, K
|
|
||||||
* @param {T} obj - Source object
|
|
||||||
* @param {K[]} keys - Keys to pick
|
|
||||||
* @returns {Pick<T, K>} New object with picked keys
|
|
||||||
*/
|
|
||||||
static pick(obj, keys) {
|
|
||||||
if (!obj || typeof obj !== "object") return {};
|
|
||||||
const result = {};
|
|
||||||
for (const key of keys) {
|
|
||||||
if (key in obj) result[key] = obj[key];
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Omit specific keys from object
|
|
||||||
* @template T, K
|
|
||||||
* @param {T} obj - Source object
|
|
||||||
* @param {K[]} keys - Keys to omit
|
|
||||||
* @returns {Omit<T, K>} New object without omitted keys
|
|
||||||
*/
|
|
||||||
static omit(obj, keys) {
|
|
||||||
if (!obj || typeof obj !== "object") return {};
|
|
||||||
const result = { ...obj };
|
|
||||||
for (const key of keys) {
|
|
||||||
delete result[key];
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create progress bar string
|
* Create progress bar string
|
||||||
* @param {number} current - Current position in ms or 0-1 ratio
|
* @param {number} current - Current position in ms or 0-1 ratio
|
||||||
@@ -498,4 +342,22 @@ export class Utils {
|
|||||||
|
|
||||||
return (hours * 3600 + minutes * 60 + seconds) * 1000;
|
return (hours * 3600 + minutes * 60 + seconds) * 1000;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/**
|
||||||
|
* Normalize text for fuzzy matching: NFKD, strip non-word chars, collapse whitespace, lowercase.
|
||||||
|
* Replaces the duplicated normalizeMatchText / normalizeTrackText functions.
|
||||||
|
* @param {string} value - Raw text to normalize
|
||||||
|
* @param {boolean} [cleanFirst=false] - Run cleanTitle() first (for worker.mjs title matching)
|
||||||
|
* @returns {string} Normalized text
|
||||||
|
*/
|
||||||
|
static normalizeText(value, cleanFirst = false) {
|
||||||
|
let text = String(value ?? "");
|
||||||
|
if (cleanFirst) text = this.cleanTitle(text);
|
||||||
|
return text
|
||||||
|
.normalize("NFKD")
|
||||||
|
.replace(/[^\w\s]+/g, " ")
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.trim()
|
||||||
|
.toLowerCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
-14
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file API.mjs — API constants — FluxerList API endpoints, authentication headers, pagination defaults, and cache TTL values
|
||||||
|
* @module src.constants.API
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* API.mjs — Single source of truth for all external API constants.
|
* API.mjs — Single source of truth for all external API constants.
|
||||||
*
|
*
|
||||||
@@ -90,25 +95,14 @@ export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build the vote link for a resource on FluxerList.
|
* Build the vote/profile link for a resource on FluxerList.
|
||||||
|
* Both vote and profile links share the same URL pattern.
|
||||||
*
|
*
|
||||||
* @param {"server"|"bot"} type - Resource type
|
* @param {"server"|"bot"} type - Resource type
|
||||||
* @param {string} resourceId - The server or bot ID or slug
|
* @param {string} resourceId - The server or bot ID or slug
|
||||||
* @returns {string} URL to the vote page on FluxerList
|
* @returns {string} URL to the resource page on FluxerList
|
||||||
*/
|
*/
|
||||||
export function buildVoteLink(type, resourceId) {
|
export function buildVoteLink(type, resourceId) {
|
||||||
const path = type === "server" ? "servers" : "bots";
|
const path = type === "server" ? "servers" : "bots";
|
||||||
return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`;
|
return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Build the profile link for a resource on FluxerList.
|
|
||||||
*
|
|
||||||
* @param {"server"|"bot"} type - Resource type
|
|
||||||
* @param {string} resourceId - The server or bot ID or slug
|
|
||||||
* @returns {string} URL to the profile page on FluxerList
|
|
||||||
*/
|
|
||||||
export function buildProfileLink(type, resourceId) {
|
|
||||||
const path = type === "server" ? "servers" : "bots";
|
|
||||||
return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`;
|
|
||||||
}
|
|
||||||
+162
-126
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file FluxerRevoice.mjs — FluxerRevoice — voice connection adapter that bridges Fluxer gateway with LiveKit rooms, replacing revoice.js API calls
|
||||||
|
* @module src.constants.FluxerRevoice
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* FluxerRevoice.mjs — Revoice-compatible adapter that uses the Fluxer API
|
* FluxerRevoice.mjs — Revoice-compatible adapter that uses the Fluxer API
|
||||||
*
|
*
|
||||||
@@ -42,55 +47,51 @@ export const LKRoomEvent = Object.freeze({
|
|||||||
ParticipantDisconnected:"participantDisconnected",
|
ParticipantDisconnected:"participantDisconnected",
|
||||||
});
|
});
|
||||||
|
|
||||||
/** @deprecated Use LKRoomEvent instead — kept for backward compat within this file */
|
|
||||||
const RoomEvent = LKRoomEvent;
|
|
||||||
|
|
||||||
import { logger } from "./Logger.mjs";
|
import { logger } from "./Logger.mjs";
|
||||||
|
|
||||||
{
|
/**
|
||||||
if (!globalThis.__fluxerLiveKitLogPatchApplied) {
|
* LiveKit log filter — intercepts LiveKit SDK noise without monkey-patching
|
||||||
globalThis.__fluxerLiveKitLogPatchApplied = true;
|
* console.log or process.stdout globally. Applied per-room by setting
|
||||||
|
* the room's logger to a filtered version.
|
||||||
|
*/
|
||||||
|
const LIVEKIT_LOG_PREFIXES = ["[voice LiveKitRtc]", "lk-rtc"];
|
||||||
|
|
||||||
const _originalConsoleLog = console.log;
|
function isLiveKitLogMessage(...args) {
|
||||||
console.log = function (...args) {
|
if (args.length === 1 && typeof args[0] === "string") {
|
||||||
if (args.length === 1 && typeof args[0] === "string" && args[0].startsWith("{")) {
|
if (args[0].startsWith("{")) {
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(args[0]);
|
const parsed = JSON.parse(args[0]);
|
||||||
if (parsed.name === "lk-rtc") return;
|
if (parsed.name === "lk-rtc") return true;
|
||||||
} catch (_) {
|
} catch (_e) { }
|
||||||
}
|
}
|
||||||
}
|
if (LIVEKIT_LOG_PREFIXES.some(p => args[0].includes(p))) return true;
|
||||||
if (args.length >= 1 && typeof args[0] === "string" && args[0].includes("[voice LiveKitRtc]")) {
|
}
|
||||||
return;
|
return false;
|
||||||
}
|
}
|
||||||
_originalConsoleLog.apply(console, args);
|
|
||||||
};
|
|
||||||
|
|
||||||
const _originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
/**
|
||||||
process.stdout.write = function (chunk, encoding, callback) {
|
* Temporarily suppress LiveKit SDK log noise during room setup.
|
||||||
if (typeof chunk === "string" && chunk.startsWith("{")) {
|
* Unlike the old global monkey-patch, this is scoped to a callback
|
||||||
try {
|
* and restores the original console.log when done.
|
||||||
if (chunk.includes('"lk-rtc"')) {
|
*/
|
||||||
const parsed = JSON.parse(chunk);
|
function withSuppressedLiveKitLogs(fn) {
|
||||||
if (parsed.name === "lk-rtc") {
|
const origLog = console.log;
|
||||||
if (typeof encoding === "function") { encoding(); }
|
console.log = function (...args) {
|
||||||
else if (typeof callback === "function") { callback(); }
|
if (isLiveKitLogMessage(...args)) return;
|
||||||
return true;
|
origLog.apply(console, args);
|
||||||
}
|
};
|
||||||
}
|
try {
|
||||||
} catch (_) {
|
return fn();
|
||||||
}
|
} finally {
|
||||||
}
|
console.log = origLog;
|
||||||
return _originalStdoutWrite(chunk, encoding, callback);
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Helper: returns a human-readable label for a ConnectionState value */
|
/** Helper: returns a human-readable label for a ConnectionState value */
|
||||||
function stateLabel(cs) {
|
function stateLabel(cs) {
|
||||||
if (cs === ConnectionState?.CONN_CONNECTED) return "CONN_CONNECTED";
|
if (cs === ConnectionState.CONN_CONNECTED) return "CONN_CONNECTED";
|
||||||
if (cs === ConnectionState?.CONN_DISCONNECTED) return "CONN_DISCONNECTED";
|
if (cs === ConnectionState.CONN_DISCONNECTED) return "CONN_DISCONNECTED";
|
||||||
if (cs === ConnectionState?.CONN_RECONNECTING) return "CONN_RECONNECTING";
|
if (cs === ConnectionState.CONN_RECONNECTING) return "CONN_RECONNECTING";
|
||||||
if (cs === 1) return "CONN_CONNECTED(1)";
|
if (cs === 1) return "CONN_CONNECTED(1)";
|
||||||
if (cs === 0) return "CONN_DISCONNECTED(0)";
|
if (cs === 0) return "CONN_DISCONNECTED(0)";
|
||||||
if (cs === 2) return "CONN_RECONNECTING(2)";
|
if (cs === 2) return "CONN_RECONNECTING(2)";
|
||||||
@@ -176,6 +177,7 @@ export class FluxerVoiceConnection extends EventEmitter {
|
|||||||
try {
|
try {
|
||||||
await this.room.disconnect();
|
await this.room.disconnect();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
logger.warn("[FluxerVoiceConnection] Room disconnect error:", e?.message);
|
||||||
}
|
}
|
||||||
} else if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
|
} else if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
|
||||||
try {
|
try {
|
||||||
@@ -228,6 +230,9 @@ export class FluxerRevoice extends EventEmitter {
|
|||||||
/** @type {Set<string>} Channel IDs where disconnect is expected (bot-initiated) */
|
/** @type {Set<string>} Channel IDs where disconnect is expected (bot-initiated) */
|
||||||
_intentionalDisconnects = new Set();
|
_intentionalDisconnects = new Set();
|
||||||
|
|
||||||
|
/** @type {Map<string, NodeJS.Timeout>} Per-channel timeout tokens for intentional disconnect marks */
|
||||||
|
_intentionalDisconnectTokens = new Map();
|
||||||
|
|
||||||
/** @type {FluxerRevoice|null} Singleton instance */
|
/** @type {FluxerRevoice|null} Singleton instance */
|
||||||
static _instance = null;
|
static _instance = null;
|
||||||
|
|
||||||
@@ -245,28 +250,31 @@ export class FluxerRevoice extends EventEmitter {
|
|||||||
|
|
||||||
constructor(client) {
|
constructor(client) {
|
||||||
super();
|
super();
|
||||||
if (FluxerRevoice._instance) {
|
if (FluxerRevoice._instance && FluxerRevoice._instance !== this) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
`[FluxerRevoice] Duplicate instance creation detected! ` +
|
`[FluxerRevoice] Duplicate instance detected! Use FluxerRevoice.getInstance().`
|
||||||
`Use FluxerRevoice.getInstance() instead of new FluxerRevoice(). ` +
|
|
||||||
`Stack: ${new Error().stack?.split('\n').slice(2, 5).join(' | ')}`
|
|
||||||
);
|
);
|
||||||
} else {
|
|
||||||
FluxerRevoice._instance = this;
|
|
||||||
}
|
}
|
||||||
if (!client) throw new Error("FluxerRevoice requires a Fluxer client instance");
|
if (!client) throw new Error("FluxerRevoice requires a Fluxer client instance");
|
||||||
this.client = client;
|
this.client = client;
|
||||||
|
if (!FluxerRevoice._instance) FluxerRevoice._instance = this;
|
||||||
logger.player("[FluxerRevoice] Instance created with Fluxer client.");
|
logger.player("[FluxerRevoice] Instance created with Fluxer client.");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mark a channel as expecting an intentional disconnect so the
|
* Mark a channel as expecting an intentional disconnect so the
|
||||||
* RoomEvent.Disconnected handler can log it correctly.
|
* LKRoomEvent.Disconnected handler can log it correctly.
|
||||||
* @param {string} channelId
|
* @param {string} channelId
|
||||||
*/
|
*/
|
||||||
markIntentionalDisconnect(channelId) {
|
markIntentionalDisconnect(channelId) {
|
||||||
this._intentionalDisconnects.add(String(channelId));
|
const key = String(channelId);
|
||||||
setTimeout(() => this._intentionalDisconnects.delete(String(channelId)), 10_000);
|
this._intentionalDisconnects.add(key);
|
||||||
|
const prev = this._intentionalDisconnectTokens.get(key);
|
||||||
|
if (prev) clearTimeout(prev);
|
||||||
|
this._intentionalDisconnectTokens.set(key, setTimeout(() => {
|
||||||
|
this._intentionalDisconnects.delete(key);
|
||||||
|
this._intentionalDisconnectTokens.delete(key);
|
||||||
|
}, 10_000));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -341,7 +349,8 @@ export class FluxerRevoice extends EventEmitter {
|
|||||||
if (existing.room) {
|
if (existing.room) {
|
||||||
try {
|
try {
|
||||||
await existing.room.disconnect();
|
await existing.room.disconnect();
|
||||||
} catch (_) {
|
} catch (e) {
|
||||||
|
logger.warn("[FluxerRevoice] Stale room disconnect error:", e?.message);
|
||||||
}
|
}
|
||||||
} else if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") {
|
} else if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") {
|
||||||
try {
|
try {
|
||||||
@@ -353,7 +362,7 @@ export class FluxerRevoice extends EventEmitter {
|
|||||||
|
|
||||||
existing._destroyed = true;
|
existing._destroyed = true;
|
||||||
existing._connected = false;
|
existing._connected = false;
|
||||||
try { existing.removeAllListeners(); } catch (_) {}
|
try { existing.removeAllListeners(); } catch (e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -375,7 +384,9 @@ export class FluxerRevoice extends EventEmitter {
|
|||||||
|
|
||||||
const prevQueue = this._globalJoinQueue;
|
const prevQueue = this._globalJoinQueue;
|
||||||
const ourResult = prevQueue.then(() => joinOperation());
|
const ourResult = prevQueue.then(() => joinOperation());
|
||||||
this._globalJoinQueue = ourResult.catch(() => {});
|
this._globalJoinQueue = ourResult.catch((err) => {
|
||||||
|
logger.warn("[FluxerRevoice] Previous join in queue failed:", err?.message ?? err);
|
||||||
|
});
|
||||||
return await ourResult;
|
return await ourResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -392,7 +403,9 @@ export class FluxerRevoice extends EventEmitter {
|
|||||||
try {
|
try {
|
||||||
const ch = this.client.channels?.get?.(channelId);
|
const ch = this.client.channels?.get?.(channelId);
|
||||||
guildId = ch?.guildId ?? ch?.guild?.id ?? null;
|
guildId = ch?.guildId ?? ch?.guild?.id ?? null;
|
||||||
} catch (_) {}
|
} catch (e) {
|
||||||
|
logger.debug("[FluxerRevoice] Could not resolve guild for channel:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
if (this.connections.has(channelId)) {
|
if (this.connections.has(channelId)) {
|
||||||
const existing = this.connections.get(channelId);
|
const existing = this.connections.get(channelId);
|
||||||
@@ -444,8 +457,22 @@ export class FluxerRevoice extends EventEmitter {
|
|||||||
logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
|
logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (room && typeof room.setLogger === "function") {
|
||||||
|
try {
|
||||||
|
room.setLogger({
|
||||||
|
debug: () => {},
|
||||||
|
info: () => {},
|
||||||
|
warn: (...args) => { if (!isLiveKitLogMessage(...args)) logger.warn("[LiveKit]", ...args); },
|
||||||
|
error: (...args) => logger.error("[LiveKit]", ...args),
|
||||||
|
});
|
||||||
|
} catch (_e) { }
|
||||||
|
}
|
||||||
|
|
||||||
if (!room) {
|
if (!room) {
|
||||||
try { await nativeConnection.disconnect(); } catch (_) {}
|
try { await nativeConnection.disconnect(); } catch (e) {
|
||||||
|
logger.warn("[FluxerRevoice] Cleanup disconnect error:", e?.message);
|
||||||
|
}
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Fluxer voice connection for ${channelId} does not expose a LiveKit Room. ` +
|
`Fluxer voice connection for ${channelId} does not expose a LiveKit Room. ` +
|
||||||
`Music playback requires a LiveKit-based voice server.`
|
`Music playback requires a LiveKit-based voice server.`
|
||||||
@@ -460,17 +487,17 @@ export class FluxerRevoice extends EventEmitter {
|
|||||||
const statePromise = new Promise((resolve) => {
|
const statePromise = new Promise((resolve) => {
|
||||||
const handler = (cs) => {
|
const handler = (cs) => {
|
||||||
if (eventResolved) return;
|
if (eventResolved) return;
|
||||||
if (cs === ConnectionState?.CONN_CONNECTED || cs === 1) {
|
if (cs === ConnectionState.CONN_CONNECTED || cs === 1) {
|
||||||
eventResolved = true;
|
eventResolved = true;
|
||||||
room.off(RoomEvent.ConnectionStateChanged, handler);
|
room.off(LKRoomEvent.ConnectionStateChanged, handler);
|
||||||
resolve();
|
resolve();
|
||||||
} else if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) {
|
} else if (cs === ConnectionState.CONN_DISCONNECTED || cs === 0) {
|
||||||
eventResolved = true;
|
eventResolved = true;
|
||||||
room.off(RoomEvent.ConnectionStateChanged, handler);
|
room.off(LKRoomEvent.ConnectionStateChanged, handler);
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
room.on(RoomEvent.ConnectionStateChanged, handler);
|
room.on(LKRoomEvent.ConnectionStateChanged, handler);
|
||||||
});
|
});
|
||||||
|
|
||||||
while (!room.isConnected && (Date.now() - startTime) < maxWait) {
|
while (!room.isConnected && (Date.now() - startTime) < maxWait) {
|
||||||
@@ -482,88 +509,97 @@ export class FluxerRevoice extends EventEmitter {
|
|||||||
if (room.isConnected) break;
|
if (room.isConnected) break;
|
||||||
|
|
||||||
const cs = room.connectionState;
|
const cs = room.connectionState;
|
||||||
if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) break;
|
if (cs === ConnectionState.CONN_DISCONNECTED || cs === 0) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const finalConnected = room.isConnected;
|
const finalConnected = room.isConnected;
|
||||||
const finalCS = room.connectionState;
|
const finalCS = room.connectionState;
|
||||||
|
|
||||||
if (!finalConnected && (finalCS === ConnectionState?.CONN_DISCONNECTED || finalCS === 0)) {
|
if (!finalConnected && (finalCS === ConnectionState.CONN_DISCONNECTED || finalCS === 0)) {
|
||||||
try { await nativeConnection.disconnect(); } catch (_) {}
|
try { await nativeConnection.disconnect(); } catch (e) {
|
||||||
|
logger.warn("[FluxerRevoice] Cleanup disconnect error:", e?.message);
|
||||||
|
}
|
||||||
throw new Error(`LiveKit room in disconnected state: ${stateLabel(finalCS)}`);
|
throw new Error(`LiveKit room in disconnected state: ${stateLabel(finalCS)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
|
logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
|
||||||
|
|
||||||
const connection = new FluxerVoiceConnection(channelId, this, {
|
|
||||||
room,
|
|
||||||
nativeConnection,
|
|
||||||
});
|
|
||||||
|
|
||||||
room.on(RoomEvent.ConnectionStateChanged, (cs) => {
|
const connection = withSuppressedLiveKitLogs(() => {
|
||||||
if (cs === ConnectionState.CONN_RECONNECTING || cs === 2) {
|
const conn = new FluxerVoiceConnection(channelId, this, {
|
||||||
logger.player(`[FluxerRevoice] Room reconnecting for channel ${channelId}`);
|
room,
|
||||||
} else if (cs === ConnectionState.CONN_CONNECTED || cs === 1) {
|
nativeConnection,
|
||||||
if (connection._destroyed) return;
|
});
|
||||||
connection._connected = true;
|
|
||||||
logger.player(`[FluxerRevoice] Room (re)connected for channel ${channelId}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
room.on(RoomEvent.Disconnected, (reason) => {
|
room.on(LKRoomEvent.ConnectionStateChanged, (cs) => {
|
||||||
const isIntentional = this._intentionalDisconnects.has(String(channelId));
|
if (cs === ConnectionState.CONN_RECONNECTING || cs === 2) {
|
||||||
const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected");
|
logger.player(`[FluxerRevoice] Room reconnecting for channel ${channelId}`);
|
||||||
logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}`);
|
} else if (cs === ConnectionState.CONN_CONNECTED || cs === 1) {
|
||||||
this._intentionalDisconnects.delete(String(channelId));
|
if (conn._destroyed) return;
|
||||||
connection._connected = false;
|
conn._connected = true;
|
||||||
connection._destroyed = true;
|
logger.player(`[FluxerRevoice] Room (re)connected for channel ${channelId}`);
|
||||||
|
|
||||||
this.connections.delete(channelId);
|
|
||||||
|
|
||||||
if (!isIntentional) {
|
|
||||||
this._leaveGateway(channelId, channelGuildId);
|
|
||||||
|
|
||||||
if (nativeConnection && typeof nativeConnection.disconnect === "function") {
|
|
||||||
try { nativeConnection.disconnect(); } catch (_) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
connection.emit("disconnect");
|
|
||||||
});
|
|
||||||
|
|
||||||
room.on(RoomEvent.ParticipantConnected, (participant) => {
|
|
||||||
const userId = participant?.identity ?? participant?.sid;
|
|
||||||
if (userId) {
|
|
||||||
const uKey = `${channelId}:${userId}`;
|
|
||||||
this.users.set(uKey, { id: userId, connectedTo: channelId });
|
|
||||||
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
|
||||||
connection.emit("userjoin", userId);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
room.on(RoomEvent.ParticipantDisconnected, (participant) => {
|
|
||||||
const userId = participant?.identity ?? participant?.sid;
|
|
||||||
if (userId) {
|
|
||||||
const uKey = `${channelId}:${userId}`;
|
|
||||||
this.users.delete(uKey);
|
|
||||||
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
|
||||||
connection.emit("userleave", userId);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
this.connections.set(channelId, connection);
|
|
||||||
|
|
||||||
if (_leaveIfEmpty) {
|
|
||||||
connection.on("userleave", () => {
|
|
||||||
const remoteCount = room.remoteParticipants?.size ?? 0;
|
|
||||||
if (remoteCount === 0) {
|
|
||||||
logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`);
|
|
||||||
connection.emit("autoleave");
|
|
||||||
this.connections.delete(channelId);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
room.on(LKRoomEvent.Disconnected, (reason) => {
|
||||||
|
const isIntentional = this._intentionalDisconnects.has(String(channelId));
|
||||||
|
const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected");
|
||||||
|
logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}`);
|
||||||
|
this._intentionalDisconnects.delete(String(channelId));
|
||||||
|
conn._connected = false;
|
||||||
|
conn._destroyed = true;
|
||||||
|
|
||||||
|
this.connections.delete(channelId);
|
||||||
|
|
||||||
|
if (!isIntentional) {
|
||||||
|
this._leaveGateway(channelId, channelGuildId);
|
||||||
|
|
||||||
|
if (nativeConnection && typeof nativeConnection.disconnect === "function") {
|
||||||
|
try { nativeConnection.disconnect(); } catch (e) {
|
||||||
|
logger.warn("[FluxerRevoice] Native disconnect error:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
conn.emit("disconnect");
|
||||||
|
});
|
||||||
|
|
||||||
|
room.on(LKRoomEvent.ParticipantConnected, (participant) => {
|
||||||
|
const userId = participant?.identity ?? participant?.sid;
|
||||||
|
if (userId) {
|
||||||
|
const uKey = `${channelId}:${userId}`;
|
||||||
|
this.users.set(uKey, { id: userId, connectedTo: channelId });
|
||||||
|
conn._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
||||||
|
conn.emit("userjoin", userId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
room.on(LKRoomEvent.ParticipantDisconnected, (participant) => {
|
||||||
|
const userId = participant?.identity ?? participant?.sid;
|
||||||
|
if (userId) {
|
||||||
|
const uKey = `${channelId}:${userId}`;
|
||||||
|
this.users.delete(uKey);
|
||||||
|
conn._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
||||||
|
conn.emit("userleave", userId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.connections.set(channelId, conn);
|
||||||
|
|
||||||
|
if (_leaveIfEmpty) {
|
||||||
|
conn.on("userleave", () => {
|
||||||
|
const remoteCount = room.remoteParticipants?.size ?? 0;
|
||||||
|
if (remoteCount === 0) {
|
||||||
|
logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`);
|
||||||
|
conn.emit("autoleave");
|
||||||
|
this.connections.delete(channelId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return conn;
|
||||||
|
});
|
||||||
|
|
||||||
return connection;
|
return connection;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file Helpers247.mjs — Helpers247 — per-channel 24/7 mode management (on/auto/off) with guild-wide backward compatibility
|
||||||
|
* @module src.constants.Helpers247
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shared 24/7 mode helpers.
|
* Shared 24/7 mode helpers.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file Locale.mjs — Locale — i18n system loading JSON locale files with per-guild language settings and template variable interpolation
|
||||||
|
* @module src.constants.Locale
|
||||||
|
*/
|
||||||
|
|
||||||
import { readFileSync, readdirSync, existsSync } from "fs";
|
import { readFileSync, readdirSync, existsSync } from "fs";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import { fileURLToPath } from "url";
|
import { fileURLToPath } from "url";
|
||||||
@@ -108,7 +113,7 @@ export class Locale {
|
|||||||
code = setting;
|
code = setting;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
|
|
||||||
const data = this.locales.get(code) ?? this.locales.get(this.defaultLocale) ?? {};
|
const data = this.locales.get(code) ?? this.locales.get(this.defaultLocale) ?? {};
|
||||||
this._resolved.set(guildId, data);
|
this._resolved.set(guildId, data);
|
||||||
@@ -156,8 +161,8 @@ export class Locale {
|
|||||||
const prefix = serverSettings.get("prefix");
|
const prefix = serverSettings.get("prefix");
|
||||||
if (prefix) return prefix;
|
if (prefix) return prefix;
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { }
|
||||||
return "%";
|
return this._defaultPrefix || "!";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file Logger.mjs — Logger — categorized logging (info, warn, error, voice, player) with timestamp formatting and module prefixes
|
||||||
|
* @module src.constants.Logger
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Logger — configurable console output for Fluxer.
|
* Logger — configurable console output for Fluxer.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
/**
|
||||||
|
* @file UI.mjs — UI constants — shared color values, emoji arrays, timeout durations, and volume limits used across commands and embeds
|
||||||
|
* @module src.constants.UI
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UI.mjs — Shared UI constants used across commands and embeds.
|
||||||
|
*
|
||||||
|
* Centralises emoji arrays, timeout values, and colour constants
|
||||||
|
* that were previously duplicated across many command files.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Error embed colour — used everywhere instead of hardcoding "#ff0000". */
|
||||||
|
export const ERROR_COLOR = "#ff0000";
|
||||||
|
|
||||||
|
/** Warning/highlight colour for diagnostic and debug embeds. */
|
||||||
|
export const WARN_COLOR = 0xFFAA00;
|
||||||
|
|
||||||
|
/** Success colour for diagnostic embeds. */
|
||||||
|
export const SUCCESS_COLOR = 0x00CC66;
|
||||||
|
|
||||||
|
/** Failure/danger colour for diagnostic embeds (same as ERROR_COLOR but numeric). */
|
||||||
|
export const DANGER_COLOR = 0xFF4444;
|
||||||
|
|
||||||
|
/** Default timeout (ms) before removing navigation reactions from embeds. */
|
||||||
|
export const EMOJI_REMOVE_TIMEOUT = 60_000;
|
||||||
|
|
||||||
|
/** Default inactivity timeout (ms) for interactive embed sessions. */
|
||||||
|
export const SESSION_TIMEOUT = 30_000;
|
||||||
|
|
||||||
|
/** Number emojis for search/radio selection menus. */
|
||||||
|
export const NUMBER_EMOJIS = [
|
||||||
|
"1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣",
|
||||||
|
"6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟",
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Cancel emoji for selection menus. */
|
||||||
|
export const CANCEL_EMOJI = "❌";
|
||||||
|
|
||||||
|
/** Navigation emojis for paginated embeds. */
|
||||||
|
export const PREV_EMOJI = "⬅️";
|
||||||
|
export const NEXT_EMOJI = "➡️";
|
||||||
|
|
||||||
|
/** Maximum allowed volume percentage. */
|
||||||
|
export const MAX_VOLUME = 200;
|
||||||
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file VoiceStateCache.mjs — VoiceStateCache — O(1) composite-keyed LRU cache for voice state lookups with dual indexes (user→channel, channel→users)
|
||||||
|
* @module src.constants.VoiceStateCache
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* VoiceStateCache — O(1) voice-state lookups with bounded memory.
|
* VoiceStateCache — O(1) voice-state lookups with bounded memory.
|
||||||
*
|
*
|
||||||
@@ -20,7 +25,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { logger } from "./Logger.mjs";
|
import { logger } from "./Logger.mjs";
|
||||||
|
import { cleanId } from "../Utils.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* VoiceStateCache class.
|
||||||
|
*/
|
||||||
export class VoiceStateCache {
|
export class VoiceStateCache {
|
||||||
/**
|
/**
|
||||||
* @param {object} [opts]
|
* @param {object} [opts]
|
||||||
@@ -48,12 +57,12 @@ export class VoiceStateCache {
|
|||||||
|
|
||||||
/** Build composite key "guildId:userId" (both cleaned to digits only) */
|
/** Build composite key "guildId:userId" (both cleaned to digits only) */
|
||||||
static userKey(guildId, userId) {
|
static userKey(guildId, userId) {
|
||||||
return `${String(guildId ?? "").replace(/\D/g, "")}:${String(userId ?? "").replace(/\D/g, "")}`;
|
return `${cleanId(guildId)}:${cleanId(userId)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Build composite key "guildId:channelId" (both cleaned to digits only) */
|
/** Build composite key "guildId:channelId" (both cleaned to digits only) */
|
||||||
static channelKey(guildId, channelId) {
|
static channelKey(guildId, channelId) {
|
||||||
return `${String(guildId ?? "").replace(/\D/g, "")}:${String(channelId ?? "").replace(/\D/g, "")}`;
|
return `${cleanId(guildId)}:${cleanId(channelId)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -66,9 +75,9 @@ export class VoiceStateCache {
|
|||||||
* @param {boolean} [params.isBot=false]
|
* @param {boolean} [params.isBot=false]
|
||||||
*/
|
*/
|
||||||
updateUser({ guildId, userId, channelId, isBot = false }) {
|
updateUser({ guildId, userId, channelId, isBot = false }) {
|
||||||
const cleanGuild = String(guildId ?? "").replace(/\D/g, "");
|
const cleanGuild = cleanId(guildId);
|
||||||
const cleanUser = String(userId ?? "").replace(/\D/g, "");
|
const cleanUser = cleanId(userId);
|
||||||
const cleanChannel = channelId ? String(channelId).replace(/\D/g, "") : null;
|
const cleanChannel = channelId ? cleanId(channelId) : null;
|
||||||
if (!cleanGuild || !cleanUser) return;
|
if (!cleanGuild || !cleanUser) return;
|
||||||
|
|
||||||
const locations = isBot ? this.botLocations : this.userLocations;
|
const locations = isBot ? this.botLocations : this.userLocations;
|
||||||
@@ -228,33 +237,48 @@ export class VoiceStateCache {
|
|||||||
* @param {string} guildId
|
* @param {string} guildId
|
||||||
*/
|
*/
|
||||||
removeGuild(guildId) {
|
removeGuild(guildId) {
|
||||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
const cleanGuild = cleanId(guildId);
|
||||||
const prefix = cleanGuild + ":";
|
const prefix = cleanGuild + ":";
|
||||||
|
|
||||||
|
|
||||||
|
const userKeysToRemove = [];
|
||||||
for (const [uKey, loc] of this.userLocations) {
|
for (const [uKey, loc] of this.userLocations) {
|
||||||
if (uKey.startsWith(prefix)) {
|
if (uKey.startsWith(prefix)) userKeysToRemove.push(uKey);
|
||||||
|
}
|
||||||
|
for (const uKey of userKeysToRemove) {
|
||||||
|
const loc = this.userLocations.get(uKey);
|
||||||
|
if (loc) {
|
||||||
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
||||||
const set = this.channelMembers.get(cKey);
|
const set = this.channelMembers.get(cKey);
|
||||||
if (set) { set.delete(loc.userId); if (set.size === 0) this.channelMembers.delete(cKey); }
|
if (set) { set.delete(loc.userId); if (set.size === 0) this.channelMembers.delete(cKey); }
|
||||||
this.userLocations.delete(uKey);
|
|
||||||
}
|
}
|
||||||
|
this.userLocations.delete(uKey);
|
||||||
}
|
}
|
||||||
for (const [cKey, set] of this.channelMembers) {
|
const channelKeysToRemove = [];
|
||||||
if (cKey.startsWith(prefix)) this.channelMembers.delete(cKey);
|
for (const [cKey] of this.channelMembers) {
|
||||||
|
if (cKey.startsWith(prefix)) channelKeysToRemove.push(cKey);
|
||||||
}
|
}
|
||||||
|
for (const cKey of channelKeysToRemove) this.channelMembers.delete(cKey);
|
||||||
this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix));
|
this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix));
|
||||||
|
|
||||||
|
const botKeysToRemove = [];
|
||||||
for (const [uKey, loc] of this.botLocations) {
|
for (const [uKey, loc] of this.botLocations) {
|
||||||
if (uKey.startsWith(prefix)) {
|
if (uKey.startsWith(prefix)) botKeysToRemove.push(uKey);
|
||||||
|
}
|
||||||
|
for (const uKey of botKeysToRemove) {
|
||||||
|
const loc = this.botLocations.get(uKey);
|
||||||
|
if (loc) {
|
||||||
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
||||||
const set = this.botChannelMembers.get(cKey);
|
const set = this.botChannelMembers.get(cKey);
|
||||||
if (set) { set.delete(loc.userId); if (set.size === 0) this.botChannelMembers.delete(cKey); }
|
if (set) { set.delete(loc.userId); if (set.size === 0) this.botChannelMembers.delete(cKey); }
|
||||||
this.botLocations.delete(uKey);
|
|
||||||
}
|
}
|
||||||
|
this.botLocations.delete(uKey);
|
||||||
}
|
}
|
||||||
for (const [cKey, set] of this.botChannelMembers) {
|
const botChannelKeysToRemove = [];
|
||||||
if (cKey.startsWith(prefix)) this.botChannelMembers.delete(cKey);
|
for (const [cKey] of this.botChannelMembers) {
|
||||||
|
if (cKey.startsWith(prefix)) botChannelKeysToRemove.push(cKey);
|
||||||
}
|
}
|
||||||
|
for (const cKey of botChannelKeysToRemove) this.botChannelMembers.delete(cKey);
|
||||||
this._lruBotKeys = this._lruBotKeys.filter(k => !k.startsWith(prefix));
|
this._lruBotKeys = this._lruBotKeys.filter(k => !k.startsWith(prefix));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -272,7 +296,7 @@ export class VoiceStateCache {
|
|||||||
for (const userId of humanSet) {
|
for (const userId of humanSet) {
|
||||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||||
const loc = this.userLocations.get(uKey);
|
const loc = this.userLocations.get(uKey);
|
||||||
if (loc && loc.channelId === String(channelId).replace(/\D/g, "")) {
|
if (loc && loc.channelId === cleanId(channelId)) {
|
||||||
this.userLocations.delete(uKey);
|
this.userLocations.delete(uKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -284,7 +308,7 @@ export class VoiceStateCache {
|
|||||||
for (const userId of botSet) {
|
for (const userId of botSet) {
|
||||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||||
const loc = this.botLocations.get(uKey);
|
const loc = this.botLocations.get(uKey);
|
||||||
if (loc && loc.channelId === String(channelId).replace(/\D/g, "")) {
|
if (loc && loc.channelId === cleanId(channelId)) {
|
||||||
this.botLocations.delete(uKey);
|
this.botLocations.delete(uKey);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -301,7 +325,7 @@ export class VoiceStateCache {
|
|||||||
* @param {boolean} [botsOnly=false] Only purge bot entries
|
* @param {boolean} [botsOnly=false] Only purge bot entries
|
||||||
*/
|
*/
|
||||||
purgeUsersInGuild(guildId, userIds, botsOnly = false) {
|
purgeUsersInGuild(guildId, userIds, botsOnly = false) {
|
||||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
const cleanGuild = cleanId(guildId);
|
||||||
|
|
||||||
if (!botsOnly) {
|
if (!botsOnly) {
|
||||||
for (const userId of userIds) {
|
for (const userId of userIds) {
|
||||||
@@ -375,7 +399,7 @@ export class VoiceStateCache {
|
|||||||
if (guildId) {
|
if (guildId) {
|
||||||
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||||
}
|
}
|
||||||
const cleanUser = String(userId).replace(/\D/g, "");
|
const cleanUser = cleanId(userId);
|
||||||
for (const [uKey, loc] of this.userLocations) {
|
for (const [uKey, loc] of this.userLocations) {
|
||||||
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
||||||
}
|
}
|
||||||
@@ -422,7 +446,7 @@ export class VoiceStateCache {
|
|||||||
if (guildId) {
|
if (guildId) {
|
||||||
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
||||||
} else {
|
} else {
|
||||||
const cleanUser = String(userId).replace(/\D/g, "");
|
const cleanUser = cleanId(userId);
|
||||||
for (const [uKey, loc] of this.userLocations) {
|
for (const [uKey, loc] of this.userLocations) {
|
||||||
if (loc.userId === cleanUser) {
|
if (loc.userId === cleanUser) {
|
||||||
this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false });
|
this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false });
|
||||||
@@ -458,7 +482,7 @@ export class VoiceStateCache {
|
|||||||
if (guildId) {
|
if (guildId) {
|
||||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||||
}
|
}
|
||||||
const cleanUser = String(userId).replace(/\D/g, "");
|
const cleanUser = cleanId(userId);
|
||||||
for (const [uKey, loc] of this.userLocations) {
|
for (const [uKey, loc] of this.userLocations) {
|
||||||
if (loc.userId === cleanUser) return true;
|
if (loc.userId === cleanUser) return true;
|
||||||
}
|
}
|
||||||
@@ -504,7 +528,7 @@ export class VoiceStateCache {
|
|||||||
if (guildId !== undefined) {
|
if (guildId !== undefined) {
|
||||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||||
}
|
}
|
||||||
const cleanUser = String(userId).replace(/\D/g, "");
|
const cleanUser = cleanId(userId);
|
||||||
for (const [, loc] of this.userLocations) {
|
for (const [, loc] of this.userLocations) {
|
||||||
if (loc.userId === cleanUser) return true;
|
if (loc.userId === cleanUser) return true;
|
||||||
}
|
}
|
||||||
@@ -525,7 +549,7 @@ export class VoiceStateCache {
|
|||||||
const loc = this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
const loc = this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||||
return loc ? { channelId: loc.channelId, guildId: loc.guildId } : undefined;
|
return loc ? { channelId: loc.channelId, guildId: loc.guildId } : undefined;
|
||||||
}
|
}
|
||||||
const cleanUser = String(userId).replace(/\D/g, "");
|
const cleanUser = cleanId(userId);
|
||||||
for (const [, loc] of this.userLocations) {
|
for (const [, loc] of this.userLocations) {
|
||||||
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
||||||
}
|
}
|
||||||
@@ -556,7 +580,7 @@ export class VoiceStateCache {
|
|||||||
if (guildId !== undefined) {
|
if (guildId !== undefined) {
|
||||||
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
||||||
} else {
|
} else {
|
||||||
const cleanUser = String(userId).replace(/\D/g, "");
|
const cleanUser = cleanId(userId);
|
||||||
const toRemove = [];
|
const toRemove = [];
|
||||||
for (const [uKey, loc] of this.userLocations) {
|
for (const [uKey, loc] of this.userLocations) {
|
||||||
if (loc.userId === cleanUser) toRemove.push(loc);
|
if (loc.userId === cleanUser) toRemove.push(loc);
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
/**
|
||||||
|
* @file VoiceStateResolver.mjs — VoiceStateResolver — unified voice state enumeration across Map/Array/Object guild voice_states with human-detection fallbacks
|
||||||
|
* @module src.constants.VoiceStateResolver
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* VoiceStateResolver.mjs — Unified voice state enumeration.
|
||||||
|
*
|
||||||
|
* Eliminates the 12+ duplicated voice-state-iteration blocks scattered
|
||||||
|
* across Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, and Dashboard.mjs.
|
||||||
|
*
|
||||||
|
* Fluxer's guild.voice_states can be a Map, an Array, or a plain Object
|
||||||
|
* depending on the client version and cache state. This module normalises
|
||||||
|
* all three into a single iteration interface.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { logger } from "./Logger.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Iterate over all voice states for a guild, yielding objects with
|
||||||
|
* { userId, channelId, isBot } regardless of the underlying data structure.
|
||||||
|
*
|
||||||
|
* @param {import("@fluxerjs/core").Guild} guild
|
||||||
|
* @yields {{ userId: string, channelId: string, isBot: boolean }}
|
||||||
|
*/
|
||||||
|
export function* iterateVoiceStates(guild) {
|
||||||
|
if (!guild) return;
|
||||||
|
|
||||||
|
const voiceStates = guild.voice_states;
|
||||||
|
if (!voiceStates) return;
|
||||||
|
|
||||||
|
let entries;
|
||||||
|
try {
|
||||||
|
if (Array.isArray(voiceStates)) {
|
||||||
|
entries = voiceStates;
|
||||||
|
} else if (typeof voiceStates.values === "function") {
|
||||||
|
entries = voiceStates.values();
|
||||||
|
} else if (typeof voiceStates[Symbol.iterator] === "function") {
|
||||||
|
entries = voiceStates;
|
||||||
|
} else {
|
||||||
|
entries = Object.values(voiceStates);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[VoiceStateResolver] Failed to enumerate voice states:", e?.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const state of entries) {
|
||||||
|
if (!state) continue;
|
||||||
|
const userId = state.userId ?? state.user_id;
|
||||||
|
const channelId = state.channelId ?? state.channel_id;
|
||||||
|
if (!userId || !channelId) continue;
|
||||||
|
|
||||||
|
const member = guild.members?.get?.(userId);
|
||||||
|
const isBot = member?.user?.bot ?? false;
|
||||||
|
|
||||||
|
yield { userId: String(userId), channelId: String(channelId), isBot };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether a guild's voice channel contains any non-bot users.
|
||||||
|
* Uses three fallback strategies: VoiceStateCache, guild.voice_states,
|
||||||
|
* and LiveKit remote participants.
|
||||||
|
*
|
||||||
|
* @param {object} opts
|
||||||
|
* @param {string} opts.guildId - Clean guild ID
|
||||||
|
* @param {string} opts.channelId - Clean channel ID
|
||||||
|
* @param {object} [opts.client] - Fluxer client (for guild cache)
|
||||||
|
* @param {object} [opts.voiceCache] - VoiceStateCache instance
|
||||||
|
* @param {Map} [opts.observedVoiceUsers] - Observed voice users map
|
||||||
|
* @param {object} [opts.room] - LiveKit Room (for remote participants)
|
||||||
|
* @param {string} [opts.botId] - Bot user ID (to exclude from LiveKit check)
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function hasHumansInChannel({ guildId, channelId, client, voiceCache, observedVoiceUsers, room, botId }) {
|
||||||
|
if (!channelId || !guildId) return false;
|
||||||
|
|
||||||
|
|
||||||
|
if (voiceCache && typeof voiceCache.hasHumansInChannel === "function") {
|
||||||
|
if (voiceCache.hasHumansInChannel(guildId, channelId)) return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (observedVoiceUsers) {
|
||||||
|
try {
|
||||||
|
const iterator = typeof observedVoiceUsers.iterateHumanUsers === "function"
|
||||||
|
? observedVoiceUsers.iterateHumanUsers()
|
||||||
|
: observedVoiceUsers.entries();
|
||||||
|
|
||||||
|
for (const [, info] of iterator) {
|
||||||
|
const gId = String(info.guildId ?? "");
|
||||||
|
const cId = String(info.channelId ?? "");
|
||||||
|
if (gId === guildId && cId === channelId) return true;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[VoiceStateResolver] ObservedVoiceUsers check failed:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (client) {
|
||||||
|
try {
|
||||||
|
const guild = client.guilds?.get?.(guildId);
|
||||||
|
if (guild) {
|
||||||
|
for (const vs of iterateVoiceStates(guild)) {
|
||||||
|
if (vs.channelId === channelId && !vs.isBot) return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[VoiceStateResolver] Guild voice_states check failed:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (room?.isConnected && room.remoteParticipants) {
|
||||||
|
try {
|
||||||
|
for (const [, participant] of room.remoteParticipants) {
|
||||||
|
const pId = participant?.identity || participant?.sid;
|
||||||
|
if (pId && pId !== botId) return true;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[VoiceStateResolver] LiveKit participants check failed:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all channel IDs that have at least one human user in voice.
|
||||||
|
*
|
||||||
|
* @param {import("@fluxerjs/core").Guild} guild
|
||||||
|
* @returns {Set<string>} Set of channel IDs with human users
|
||||||
|
*/
|
||||||
|
export function getChannelsWithHumans(guild) {
|
||||||
|
const channels = new Set();
|
||||||
|
for (const vs of iterateVoiceStates(guild)) {
|
||||||
|
if (!vs.isBot) channels.add(vs.channelId);
|
||||||
|
}
|
||||||
|
return channels;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all user IDs in a specific voice channel (including bots).
|
||||||
|
*
|
||||||
|
* @param {import("@fluxerjs/core").Guild} guild
|
||||||
|
* @param {string} channelId
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
export function getUsersInChannel(guild, channelId) {
|
||||||
|
const users = [];
|
||||||
|
for (const vs of iterateVoiceStates(guild)) {
|
||||||
|
if (vs.channelId === channelId) users.push(vs.userId);
|
||||||
|
}
|
||||||
|
return users;
|
||||||
|
}
|
||||||
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file providers.mjs — Music provider definitions — source names, emoji icons, choice lists, and inline provider parsing for search commands
|
||||||
|
* @module src.constants.providers
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* providers.mjs — Single source of truth for all provider data.
|
* providers.mjs — Single source of truth for all provider data.
|
||||||
*
|
*
|
||||||
@@ -98,3 +103,18 @@ export const PROVIDER_CHOICES = [
|
|||||||
"ytrec", "sprec", "dzrec", "tdrec", "jsrec", "vkrec",
|
"ytrec", "sprec", "dzrec", "tdrec", "jsrec", "vkrec",
|
||||||
"gtts", "tts", "ftts",
|
"gtts", "tts", "ftts",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse an inline provider prefix from a query string (e.g. "sp: song name").
|
||||||
|
* @param {string} raw
|
||||||
|
* @returns {{ provider: string|null, query: string }}
|
||||||
|
*/
|
||||||
|
export function parseInlineProvider(raw) {
|
||||||
|
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
|
||||||
|
if (!match) return { provider: null, query: raw.trim() };
|
||||||
|
const maybeProvider = match[1].toLowerCase();
|
||||||
|
if (PROVIDER_CHOICES.includes(maybeProvider)) {
|
||||||
|
return { provider: maybeProvider, query: match[2].trim() };
|
||||||
|
}
|
||||||
|
return { provider: null, query: raw.trim() };
|
||||||
|
}
|
||||||
+45
-47
@@ -1,11 +1,20 @@
|
|||||||
|
/**
|
||||||
|
* @file Dashboard.mjs — Dashboard — web dashboard backend with player status API, guild listing, and bot statistics endpoints
|
||||||
|
* @module src.dashboard.Dashboard
|
||||||
|
*/
|
||||||
|
|
||||||
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
|
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
|
||||||
import { PermissionFlags } from "@fluxerjs/core";
|
import { PermissionFlags } from "@fluxerjs/core";
|
||||||
import Player from "../Player.mjs";
|
import Player from "../Player.mjs";
|
||||||
import { Utils } from "../Utils.mjs";
|
import { Utils, cleanId } from "../Utils.mjs";
|
||||||
import { DatabaseManager } from "./DatabaseManager.mjs";
|
import { DatabaseManager } from "./DatabaseManager.mjs";
|
||||||
import { RedisHandler } from "./RedisHandler.mjs";
|
import { RedisHandler } from "./RedisHandler.mjs";
|
||||||
import { logger } from "../constants/Logger.mjs";
|
import { logger } from "../constants/Logger.mjs";
|
||||||
|
import { iterateVoiceStates } from "../constants/VoiceStateResolver.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dashboard class.
|
||||||
|
*/
|
||||||
export class Dashboard {
|
export class Dashboard {
|
||||||
enabled = false;
|
enabled = false;
|
||||||
expiryTime = 1000 * 60 * 60 * 6;
|
expiryTime = 1000 * 60 * 60 * 6;
|
||||||
@@ -93,7 +102,7 @@ export class Dashboard {
|
|||||||
const sharedIds = new Set(shared.map(s => s.id));
|
const sharedIds = new Set(shared.map(s => s.id));
|
||||||
result = result.filter(g => sharedIds.has(g.id));
|
result = result.filter(g => sharedIds.has(g.id));
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch(e) { logger.warn("[Dashboard] allServers accessor check:", e?.message); }
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -200,7 +209,7 @@ export class Dashboard {
|
|||||||
data: String(user.id)
|
data: String(user.id)
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
} catch (_) { /* non-critical */ }
|
} catch (_) { }
|
||||||
}
|
}
|
||||||
return { message: "Already Connected" };
|
return { message: "Already Connected" };
|
||||||
}
|
}
|
||||||
@@ -288,10 +297,10 @@ export class Dashboard {
|
|||||||
|
|
||||||
case "voiceState": {
|
case "voiceState": {
|
||||||
if (!user) return { channel: null };
|
if (!user) return { channel: null };
|
||||||
const userId = String(user.id).replace(/\D/g, "");
|
const userId = cleanId(user.id);
|
||||||
if (this.remix.voiceCache) {
|
if (this.remix.voiceCache) {
|
||||||
for (const [mapUserId, info] of this.remix.voiceCache) {
|
for (const [mapUserId, info] of this.remix.voiceCache) {
|
||||||
if (String(mapUserId).replace(/\D/g, "") === userId && info.channelId) {
|
if (cleanId(mapUserId) === userId && info.channelId) {
|
||||||
const ch = this.remix.client.channels.get(info.channelId);
|
const ch = this.remix.client.channels.get(info.channelId);
|
||||||
return {
|
return {
|
||||||
channelId: info.channelId,
|
channelId: info.channelId,
|
||||||
@@ -305,16 +314,13 @@ export class Dashboard {
|
|||||||
const guildValues = guilds && typeof guilds.values === "function"
|
const guildValues = guilds && typeof guilds.values === "function"
|
||||||
? [...guilds.values()] : guilds ? Object.values(guilds) : [];
|
? [...guilds.values()] : guilds ? Object.values(guilds) : [];
|
||||||
for (const guild of guildValues) {
|
for (const guild of guildValues) {
|
||||||
if (!guild?.voice_states) continue;
|
for (const vs of iterateVoiceStates(guild)) {
|
||||||
const vs = Array.isArray(guild.voice_states) ? guild.voice_states :
|
const stateUserId = cleanId(vs.userId);
|
||||||
typeof guild.voice_states.values === "function" ? [...guild.voice_states.values()] : Object.values(guild.voice_states);
|
if (stateUserId === userId && vs.channelId) {
|
||||||
for (const state of vs) {
|
const ch = this.remix.client.channels.get(vs.channelId);
|
||||||
const stateUserId = String(state?.userId ?? state?.user_id ?? "").replace(/\D/g, "");
|
|
||||||
if (stateUserId === userId && state.channelId) {
|
|
||||||
const ch = this.remix.client.channels.get(state.channelId);
|
|
||||||
return {
|
return {
|
||||||
channelId: state.channelId,
|
channelId: vs.channelId,
|
||||||
channel: ch ? Dashboard.convertChannel(ch) : { id: state.channelId, name: "Unknown" },
|
channel: ch ? Dashboard.convertChannel(ch) : { id: vs.channelId, name: "Unknown" },
|
||||||
guildId: guild.id,
|
guildId: guild.id,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -343,7 +349,7 @@ export class Dashboard {
|
|||||||
data: String(user.id)
|
data: String(user.id)
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
} catch (_) { /* non-critical */ }
|
} catch (_) { }
|
||||||
return { message: "Left channel" };
|
return { message: "Left channel" };
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
@@ -370,21 +376,21 @@ export class Dashboard {
|
|||||||
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null;
|
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null;
|
||||||
if (!user) return "User not provided";
|
if (!user) return "User not provided";
|
||||||
|
|
||||||
const cleanUserId = String(user.id).replace(/\D/g, "");
|
const cleanUserId = cleanId(user.id);
|
||||||
const cleanChanId = String(player._channelId ?? "").replace(/\D/g, "");
|
const cleanChanId = cleanId(player._channelId);
|
||||||
if (!cleanChanId) return "Player has no active channel";
|
if (!cleanChanId) return "Player has no active channel";
|
||||||
|
|
||||||
const observed = this.remix.voiceCache;
|
const observed = this.remix.voiceCache;
|
||||||
if (observed) {
|
if (observed) {
|
||||||
const guildId = String(player._guildId ?? "").replace(/\D/g, "");
|
const guildId = cleanId(player._guildId);
|
||||||
const userLoc = observed.get(cleanUserId, guildId || undefined);
|
const userLoc = observed.get(cleanUserId, guildId || undefined);
|
||||||
if (userLoc) {
|
if (userLoc) {
|
||||||
const infoChannelId = String(userLoc.channelId ?? "").replace(/\D/g, "");
|
const infoChannelId = cleanId(userLoc.channelId);
|
||||||
if (infoChannelId === cleanChanId) return null;
|
if (infoChannelId === cleanChanId) return null;
|
||||||
}
|
}
|
||||||
for (const [mapUserId, info] of observed) {
|
for (const [mapUserId, info] of observed) {
|
||||||
if (String(mapUserId).replace(/\D/g, "") === cleanUserId) {
|
if (cleanId(mapUserId) === cleanUserId) {
|
||||||
const infoChannelId = String(info.channelId ?? "").replace(/\D/g, "");
|
const infoChannelId = cleanId(info.channelId);
|
||||||
if (infoChannelId === cleanChanId) return null;
|
if (infoChannelId === cleanChanId) return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -435,9 +441,9 @@ export class Dashboard {
|
|||||||
if (user.avatar) {
|
if (user.avatar) {
|
||||||
avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`;
|
avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`;
|
||||||
} else if (typeof user.displayAvatarURL === "function") {
|
} else if (typeof user.displayAvatarURL === "function") {
|
||||||
try { avatarUrl = user.displayAvatarURL() ?? ""; } catch (_) {}
|
try { avatarUrl = user.displayAvatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] displayAvatarURL:", e?.message); }
|
||||||
} else if (typeof user.avatarURL === "function") {
|
} else if (typeof user.avatarURL === "function") {
|
||||||
try { avatarUrl = user.avatarURL() ?? ""; } catch (_) {}
|
try { avatarUrl = user.avatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] avatarURL:", e?.message); }
|
||||||
}
|
}
|
||||||
if (!avatarUrl) {
|
if (!avatarUrl) {
|
||||||
avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.id?.slice(-4) ?? "0") % 5}.png`;
|
avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.id?.slice(-4) ?? "0") % 5}.png`;
|
||||||
@@ -490,16 +496,12 @@ export class Dashboard {
|
|||||||
let voiceParticipants = [];
|
let voiceParticipants = [];
|
||||||
if (isVoice) {
|
if (isVoice) {
|
||||||
const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||||
if (guild?.voice_states) {
|
for (const vs of iterateVoiceStates(guild)) {
|
||||||
const vs = Array.isArray(guild.voice_states) ? guild.voice_states :
|
const scId = cleanId(vs.channelId);
|
||||||
typeof guild.voice_states.values === "function" ? [...guild.voice_states.values()] : Object.values(guild.voice_states);
|
const chId = cleanId(channel?.id);
|
||||||
for (const state of vs) {
|
if (scId === chId) {
|
||||||
const scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
const user = guild?.members?.get?.(vs.userId)?.user;
|
||||||
const chId = String(channel?.id ?? "").replace(/\D/g, "");
|
if (user && !user.bot) voiceParticipants.push(Dashboard.convertUser(user));
|
||||||
if (scId === chId) {
|
|
||||||
const user = guild.members?.get?.(state?.userId ?? state?.user_id)?.user;
|
|
||||||
if (user && !user.bot) voiceParticipants.push(Dashboard.convertUser(user));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -582,8 +584,8 @@ export class Dashboard {
|
|||||||
const channelId = player._channelId;
|
const channelId = player._channelId;
|
||||||
const channel = channelId ? player.client?.channels?.get(channelId) : null;
|
const channel = channelId ? player.client?.channels?.get(channelId) : null;
|
||||||
const guild = channel?.guild ?? (player._guildId ? player.client?.guilds?.get(player._guildId) : null);
|
const guild = channel?.guild ?? (player._guildId ? player.client?.guilds?.get(player._guildId) : null);
|
||||||
const cleanChannelId = channelId ? String(channelId).replace(/\D/g, "") : "";
|
const cleanChannelId = channelId ? cleanId(channelId) : "";
|
||||||
const cleanGuildId = player._guildId ? String(player._guildId).replace(/\D/g, "") : "";
|
const cleanGuildId = player._guildId ? cleanId(player._guildId) : "";
|
||||||
|
|
||||||
const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] };
|
const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] };
|
||||||
|
|
||||||
@@ -600,16 +602,12 @@ export class Dashboard {
|
|||||||
const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||||
const ids = [];
|
const ids = [];
|
||||||
const seen = new Set();
|
const seen = new Set();
|
||||||
if (g?.voice_states) {
|
for (const vs of iterateVoiceStates(g)) {
|
||||||
const vs = Array.isArray(g.voice_states) ? g.voice_states :
|
const scId = cleanId(vs.channelId);
|
||||||
typeof g.voice_states.values === "function" ? [...g.voice_states.values()] : Object.values(g.voice_states);
|
const chId = cleanId(channel?.id);
|
||||||
for (const state of vs) {
|
if (scId === chId) {
|
||||||
const scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
const memberId = vs.userId;
|
||||||
const chId = String(channel?.id ?? "").replace(/\D/g, "");
|
if (memberId) { ids.push(memberId); seen.add(memberId); }
|
||||||
if (scId === chId) {
|
|
||||||
const memberId = String(state?.userId ?? state?.user_id ?? "");
|
|
||||||
if (memberId) { ids.push(memberId); seen.add(memberId); }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const vc = player._voiceCache ?? player._observedVoiceUsers;
|
const vc = player._voiceCache ?? player._observedVoiceUsers;
|
||||||
@@ -626,8 +624,8 @@ export class Dashboard {
|
|||||||
} else {
|
} else {
|
||||||
for (const [mapUserId, info] of vc) {
|
for (const [mapUserId, info] of vc) {
|
||||||
if (seen.has(mapUserId)) continue;
|
if (seen.has(mapUserId)) continue;
|
||||||
const infoCh = String(info.channelId ?? "").replace(/\D/g, "");
|
const infoCh = cleanId(info.channelId);
|
||||||
const infoG = String(info.guildId ?? "").replace(/\D/g, "");
|
const infoG = cleanId(info.guildId);
|
||||||
if (infoCh === cleanChannelId && infoG === cleanGuildId) {
|
if (infoCh === cleanChannelId && infoG === cleanGuildId) {
|
||||||
const botId = player.client?.user?.id;
|
const botId = player.client?.user?.id;
|
||||||
if (botId && String(mapUserId) === String(botId)) continue;
|
if (botId && String(mapUserId) === String(botId)) continue;
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file DatabaseManager.mjs — DatabaseManager — SQLite database manager for the web dashboard's persistent storage
|
||||||
|
* @module src.dashboard.DatabaseManager
|
||||||
|
*/
|
||||||
|
|
||||||
import { compare, genSalt, hash } from "bcryptjs";
|
import { compare, genSalt, hash } from "bcryptjs";
|
||||||
import { createPool } from "mysql2/promise";
|
import { createPool } from "mysql2/promise";
|
||||||
import { logger } from "../constants/Logger.mjs";
|
import { logger } from "../constants/Logger.mjs";
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file RedisHandler.mjs — RedisHandler — Redis pub/sub handler for cross-process dashboard state synchronization
|
||||||
|
* @module src.dashboard.RedisHandler
|
||||||
|
*/
|
||||||
|
|
||||||
import { createClient } from "redis";
|
import { createClient } from "redis";
|
||||||
import { logger } from "../constants/Logger.mjs";
|
import { logger } from "../constants/Logger.mjs";
|
||||||
|
|
||||||
@@ -13,6 +18,9 @@ const DEFAULT_RETRY_STRATEGY = (options) => {
|
|||||||
return Math.min(options.attempt * 500, 5_000);
|
return Math.min(options.attempt * 500, 5_000);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RedisHandler class.
|
||||||
|
*/
|
||||||
export class RedisHandler {
|
export class RedisHandler {
|
||||||
platform = "fluxer";
|
platform = "fluxer";
|
||||||
|
|
||||||
@@ -163,8 +171,8 @@ export class RedisHandler {
|
|||||||
this._destroyed = true;
|
this._destroyed = true;
|
||||||
if (this._pingInterval) { clearInterval(this._pingInterval); this._pingInterval = null; }
|
if (this._pingInterval) { clearInterval(this._pingInterval); this._pingInterval = null; }
|
||||||
if (this._readyTimer) { clearTimeout(this._readyTimer); this._readyTimer = null; }
|
if (this._readyTimer) { clearTimeout(this._readyTimer); this._readyTimer = null; }
|
||||||
try { await this.subscriber?.quit(); } catch (_) {}
|
try { await this.subscriber?.quit(); } catch(e) { logger.warn("[Redis/Subscriber] Quit error:", e?.message); }
|
||||||
try { await this.client?.quit(); } catch (_) {}
|
try { await this.client?.quit(); } catch(e) { logger.warn("[Redis/Main] Quit error:", e?.message); }
|
||||||
logger.redis("[Redis] Connections closed gracefully");
|
logger.redis("[Redis] Connections closed gracefully");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+6
-1
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file probe.mjs — Health probe — monitors NodeLink and LiveKit endpoint availability
|
||||||
|
* @module src.probe
|
||||||
|
*/
|
||||||
|
|
||||||
import ffprobe from "ffprobe-static";
|
import ffprobe from "ffprobe-static";
|
||||||
import { spawn } from "node:child_process";
|
import { spawn } from "node:child_process";
|
||||||
|
|
||||||
@@ -19,7 +24,7 @@ export default function probe(file) {
|
|||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
settled = true;
|
settled = true;
|
||||||
clearTimeout(timeoutHandle);
|
clearTimeout(timeoutHandle);
|
||||||
try { proc.kill(); } catch (_) {}
|
try { proc.kill(); } catch(e) { }
|
||||||
};
|
};
|
||||||
|
|
||||||
const timeoutHandle = setTimeout(() => {
|
const timeoutHandle = setTimeout(() => {
|
||||||
|
|||||||
+9
-8
@@ -1,3 +1,8 @@
|
|||||||
|
/**
|
||||||
|
* @file worker.mjs — Worker thread module — handles track search jobs via NodeLink REST API with provider fallback chains
|
||||||
|
* @module src.worker
|
||||||
|
*/
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
|
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
|
||||||
*/
|
*/
|
||||||
@@ -6,14 +11,15 @@ import { workerData, parentPort } from "worker_threads";
|
|||||||
import { EventEmitter } from "events";
|
import { EventEmitter } from "events";
|
||||||
import http from "http";
|
import http from "http";
|
||||||
import https from "https";
|
import https from "https";
|
||||||
import { Utils } from "./Utils.mjs";
|
import { Utils, cleanId } from "./Utils.mjs";
|
||||||
import { PROVIDERS } from "./constants/providers.mjs";
|
import { PROVIDERS } from "./constants/providers.mjs";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
|
import { NL_DEFAULT_PASSWORD } from "./Player.mjs";
|
||||||
|
|
||||||
const nl = workerData?.data?.nodelink ?? {};
|
const nl = workerData?.data?.nodelink ?? {};
|
||||||
const NL_HOST = nl.host ?? "localhost";
|
const NL_HOST = nl.host ?? "localhost";
|
||||||
const NL_PORT = nl.port ?? 3000;
|
const NL_PORT = nl.port ?? 3000;
|
||||||
const NL_DEFAULT_PASSWORD = "youshallnotpass";
|
|
||||||
const NL_PASSWORD = nl.password ?? NL_DEFAULT_PASSWORD;
|
const NL_PASSWORD = nl.password ?? NL_DEFAULT_PASSWORD;
|
||||||
const NL_SESSION_ID = nl.sessionId ?? null;
|
const NL_SESSION_ID = nl.sessionId ?? null;
|
||||||
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
|
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
|
||||||
@@ -148,12 +154,7 @@ function trackToVideo(track) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function normalizeMatchText(value) {
|
function normalizeMatchText(value) {
|
||||||
return Utils.cleanTitle(String(value ?? ""))
|
return Utils.normalizeText(value, true);
|
||||||
.normalize("NFKD")
|
|
||||||
.replace(/[^\w\s]+/g, " ")
|
|
||||||
.replace(/\s+/g, " ")
|
|
||||||
.trim()
|
|
||||||
.toLowerCase();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function tokenizeMatchText(value) {
|
function tokenizeMatchText(value) {
|
||||||
|
|||||||
Reference in new issue
Block a user