mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
refactor(debug): rewrite for correctness, state preservation, readability
This commit is contained in:
1 parent
23505457fa
commit
0d92ba04fa
1 file changed
+214
-215
+214
-215
@@ -5,15 +5,14 @@
|
||||
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { cleanId } from "../src/MessageHandler.mjs";
|
||||
import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs";
|
||||
import { logger } from "../src/constants/Logger.mjs";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { ERROR_COLOR, WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR } from "../src/constants/UI.mjs";
|
||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||
import { ERROR_COLOR, WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
||||
|
||||
const REJOIN_DELAY_MS = 2_000;
|
||||
const INTENTIONAL_LEAVE_TTL = 30_000;
|
||||
const MAX_DESC = 4096;
|
||||
|
||||
/**
|
||||
* Return a human-readable label for a voice room's connection state.
|
||||
@@ -55,20 +54,19 @@ function isGhostConnection(player) {
|
||||
if (cs === 0 || cs === "CONN_DISCONNECTED") return true;
|
||||
if (cs === "CONN_RECONNECTING" || cs === 3 || cs === 4) return true;
|
||||
|
||||
if (cs === 2 && !room.isConnected) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the bot's voice state from the gateway cache for a given guild.
|
||||
* @param {object} client - The Discord client instance
|
||||
* @param {object} client - The Fluxer client instance
|
||||
* @param {string} guildId - The guild ID to look up
|
||||
* @returns {{ userId: string, channelId: string } | null}
|
||||
*/
|
||||
function getBotGatewayVoiceState(client, guildId) {
|
||||
const botId = client.user?.id;
|
||||
if (!botId || !guildId) return null;
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates) {
|
||||
@@ -79,12 +77,14 @@ function getBotGatewayVoiceState(client, guildId) {
|
||||
if (channelId) return { userId: botId, channelId: cleanId(channelId) };
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (VoiceManager):", e?.message); }
|
||||
|
||||
try {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
||||
if (!voiceStates) return null;
|
||||
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
@@ -94,6 +94,7 @@ function getBotGatewayVoiceState(client, guildId) {
|
||||
const obj = typeof val === "object" && val !== null ? val : {};
|
||||
return { user_id: uid, channel_id: obj.channelId ?? obj.channel_id ?? null, ...obj };
|
||||
});
|
||||
|
||||
for (const state of entries) {
|
||||
const uid = state?.user_id ?? state?.userId ?? state?.id;
|
||||
if (uid === botId) {
|
||||
@@ -101,12 +102,14 @@ function getBotGatewayVoiceState(client, guildId) {
|
||||
if (chId) return { userId: botId, channelId: cleanId(chId) };
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (guild cache):", e?.message); }
|
||||
|
||||
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 {object} client - The Fluxer client instance
|
||||
* @param {import("../src/Player.mjs").default} player
|
||||
* @returns {boolean}
|
||||
*/
|
||||
@@ -120,14 +123,25 @@ function isStaleGatewayPresence(client, player) {
|
||||
const playerChannel = cleanId(player._channelId ?? player._home247Channel);
|
||||
const gatewayChannel = gatewayState.channelId;
|
||||
|
||||
if (!playerChannel) return true;
|
||||
if (playerChannel !== gatewayChannel) return true;
|
||||
|
||||
return false;
|
||||
return !playerChannel || playerChannel !== gatewayChannel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy a player's stale connection and respawn a fresh player, restoring queue and playback.
|
||||
* Build a human-readable label for a player's guild/channel.
|
||||
* @param {object} client - The Fluxer client
|
||||
* @param {string} channelId - The channel ID
|
||||
* @param {import("../src/Player.mjs").default} player
|
||||
* @returns {string}
|
||||
*/
|
||||
function buildPlayerLabel(client, channelId, player) {
|
||||
const channel = client.channels.get(channelId);
|
||||
const gId = player._guildId ?? channel?.guildId;
|
||||
const guild = gId ? client.guilds.get(cleanId(gId)) : null;
|
||||
return `${guild?.name ?? "unknown"} / #${channel?.name ?? channelId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy a player's stale connection and respawn a fresh player, restoring queue, loop, filters, 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 }>}
|
||||
@@ -144,6 +158,11 @@ async function forceRejoinPlayer(ctx, player) {
|
||||
const queueTracks = player.queue?.data ? [...player.queue.data] : [];
|
||||
const wasPaused = player._paused;
|
||||
const wasAutoplay = player._autoplay;
|
||||
const wasLoop = player.queue?.loop ?? false;
|
||||
const wasSongLoop = player.queue?.songLoop ?? false;
|
||||
const savedVolume = player.preferredVolume ?? 1;
|
||||
const savedFilter = player.activeFilter ?? null;
|
||||
const savedFilterPayload = player.activeFilterPayload ?? null;
|
||||
|
||||
try {
|
||||
ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL);
|
||||
@@ -171,16 +190,16 @@ async function forceRejoinPlayer(ctx, player) {
|
||||
|
||||
const revoiceConn = ctx.revoice?.connections?.get(cleanChannelId);
|
||||
if (revoiceConn) {
|
||||
try { await ctx.revoice._destroyStaleConnection(cleanChannelId, revoiceConn); } catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
try { await ctx.revoice._destroyStaleConnection(cleanChannelId, revoiceConn); } catch (e) { logger.warn("[Debug] revoice stale destroy:", e?.message); }
|
||||
} else if (player.connection) {
|
||||
try { player.connection.removeAllListeners(); } catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
try { ctx.revoice?._leaveGateway?.(cleanChannelId, cleanGuildId); } catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
try { ctx.revoice?.deleteConnection?.(cleanChannelId); } catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
try { await player.connection.disconnect(); } catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
try { player.connection.removeAllListeners(); } catch (e) { logger.warn("[Debug] connection listener removal:", e?.message); }
|
||||
try { ctx.revoice?._leaveGateway?.(cleanChannelId, cleanGuildId); } catch (e) { logger.warn("[Debug] gateway leave:", e?.message); }
|
||||
try { ctx.revoice?.deleteConnection?.(cleanChannelId); } catch (e) { logger.warn("[Debug] revoice delete:", e?.message); }
|
||||
try { await player.connection.disconnect(); } catch (e) { logger.warn("[Debug] connection disconnect:", e?.message); }
|
||||
}
|
||||
|
||||
try { await player.leave(); } catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
try { player.destroy(); } catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
try { await player.leave(); } catch (e) { logger.warn("[Debug] player leave:", e?.message); }
|
||||
try { player.destroy(); } catch (e) { logger.warn("[Debug] player destroy:", e?.message); }
|
||||
|
||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||
|
||||
@@ -190,13 +209,25 @@ async function forceRejoinPlayer(ctx, player) {
|
||||
return { success: false, reason: "_spawnPlayer returned null", channelId: cleanChannelId };
|
||||
}
|
||||
|
||||
if (newPlayer.preferredVolume !== savedVolume) {
|
||||
newPlayer.setVolume(savedVolume);
|
||||
}
|
||||
|
||||
if (wasLoop) newPlayer.queue?.setLoop?.(true);
|
||||
if (wasSongLoop) newPlayer.queue?.setSongLoop?.(true);
|
||||
|
||||
if (savedFilter && savedFilterPayload) {
|
||||
newPlayer.activeFilter = savedFilter;
|
||||
newPlayer.activeFilterPayload = savedFilterPayload;
|
||||
}
|
||||
|
||||
if (currentTrack && newPlayer.queue) {
|
||||
try {
|
||||
newPlayer.queue.data = queueTracks;
|
||||
newPlayer.queue.current = null;
|
||||
await newPlayer.playNext();
|
||||
if (wasPaused) newPlayer.pause();
|
||||
} catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
} catch (e) { logger.warn("[Debug] queue restore:", e?.message); }
|
||||
}
|
||||
|
||||
if (wasAutoplay) newPlayer._autoplay = true;
|
||||
@@ -210,10 +241,89 @@ async function forceRejoinPlayer(ctx, player) {
|
||||
channelId: cleanChannelId,
|
||||
};
|
||||
} catch (err) {
|
||||
logger.warn("[Debug] forceRejoinPlayer error:", err?.message);
|
||||
return { success: false, reason: err.message, channelId: cleanChannelId };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process a batch of players for rejoin, with progress updates.
|
||||
* @param {object} ctx - The bot context (this)
|
||||
* @param {Array<[string, import("../src/Player.mjs").default]>} entries - [channelId, player] pairs
|
||||
* @param {import("../src/MessageHandler.mjs").Message} statusMsg - The status message to edit with progress
|
||||
* @param {string} title - The embed title
|
||||
* @returns {Promise<Array>} Results array
|
||||
*/
|
||||
async function processRejoinBatch(ctx, entries, statusMsg, title) {
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const [cid, player] = entries[i];
|
||||
const label = buildPlayerLabel(ctx.client, cid, player);
|
||||
|
||||
const progressLines = [
|
||||
`🔄 **${title}** — Processing ${i + 1}/${entries.length}`,
|
||||
`Currently rejoining: \`${label}\``,
|
||||
``,
|
||||
];
|
||||
for (let j = 0; j < results.length; j++) {
|
||||
const r = results[j];
|
||||
const icon = r.success ? "✅" : "❌";
|
||||
progressLines.push(`${icon} \`${r.label}\`${r.success ? ` — room:${r.roomState}` : ` — failed (${r.reason ?? "?"})`}`);
|
||||
}
|
||||
await statusMsg.edit({ embeds: [new EmbedBuilder().setColor(WARN_COLOR).setTitle(`Debug — ${title}`).setDescription(progressLines.join("\n").slice(0, MAX_DESC))] }).catch(() => {});
|
||||
|
||||
const result = await forceRejoinPlayer(ctx, player);
|
||||
result.label = label;
|
||||
results.push(result);
|
||||
|
||||
if (i < entries.length - 1) {
|
||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the final results embed after a batch rejoin.
|
||||
* @param {Array} results - Results from processRejoinBatch
|
||||
* @param {string} title - The embed title
|
||||
* @param {string} noun - "ghost connection(s)" or "24/7 channel(s)"
|
||||
* @returns {{embeds: [EmbedBuilder]}}
|
||||
*/
|
||||
function buildRejoinResultEmbed(results, title, noun) {
|
||||
const resultLines = [
|
||||
`🔄 **${title} Complete**`,
|
||||
`${noun.charAt(0).toUpperCase() + noun.slice(1)} processed: **${results.length}**`,
|
||||
``,
|
||||
];
|
||||
|
||||
let rejoinedCount = 0;
|
||||
let resumedCount = 0;
|
||||
let failedCount = 0;
|
||||
|
||||
for (const r of results) {
|
||||
if (r.success) {
|
||||
rejoinedCount++;
|
||||
if (r.resumedPlayback) resumedCount++;
|
||||
resultLines.push(`✅ \`${r.label}\` — rejoined (room:${r.roomState}, playback:${r.resumedPlayback ? "resumed" : "no track"})`);
|
||||
} else {
|
||||
failedCount++;
|
||||
resultLines.push(`❌ \`${r.label}\` — failed${r.reason ? ` (${r.reason})` : ""}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (failedCount === 0) {
|
||||
resultLines.push("", `All **${rejoinedCount}** ${noun} restored.${resumedCount > 0 ? ` ${resumedCount} had playback resumed.` : ""}`);
|
||||
} else {
|
||||
resultLines.push("", `⚠️ **${failedCount}** ${noun} could not be restored.`);
|
||||
}
|
||||
|
||||
const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR;
|
||||
return { embeds: [new EmbedBuilder().setColor(finalColor).setTitle(`Debug — ${title}`).setDescription(resultLines.join("\n").slice(0, MAX_DESC))] };
|
||||
}
|
||||
|
||||
export const command = new CommandBuilder()
|
||||
.setName("debug")
|
||||
.setDescription("A debug command for various purposes.")
|
||||
@@ -232,32 +342,68 @@ export const command = new CommandBuilder()
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function run(msg, data) {
|
||||
switch (data.get("target").value) {
|
||||
case "247-rejoin": {
|
||||
const allPlayers = [...this.players.playerMap.entries()];
|
||||
const channels247 = allPlayers.filter(([, player]) => player._home247Channel);
|
||||
const target = data.get("target").value;
|
||||
|
||||
if (channels247.length === 0) {
|
||||
switch (target) {
|
||||
case "247-rejoin": {
|
||||
return await runBatchRejoin(msg, "247-rejoin", "24/7 Rejoin", "24/7 channel(s)", p => !!p._home247Channel);
|
||||
}
|
||||
|
||||
case "voice-rejoin": {
|
||||
return await runBatchRejoin(msg, "voice-rejoin", "Voice Rejoin", "ghost connection(s)", isGhostConnection, true);
|
||||
}
|
||||
|
||||
case "voice": {
|
||||
return await runVoiceDiagnostic(msg);
|
||||
}
|
||||
|
||||
default: {
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(WARN_COLOR)
|
||||
.setTitle("Debug — 24/7 Rejoin")
|
||||
.setDescription("No 24/7 channels found in the player map.")
|
||||
.setColor(ERROR_COLOR)
|
||||
.setTitle("Debug — Unknown Target")
|
||||
.setDescription(`Unknown debug target: \`${target}\`.\nValid options: \`voice\`, \`voice-rejoin\`, \`247-rejoin\`.`)
|
||||
;
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a batch rejoin for players matching a filter.
|
||||
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||
* @param {string} key - The debug key for log labels
|
||||
* @param {string} title - The display title
|
||||
* @param {string} noun - What we're rejoining (for result text)
|
||||
* @param {(player: import("../src/Player.mjs").default) => boolean} filter - Player filter
|
||||
* @param {boolean} showHintIfEmpty - Show a hint when no matches found
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = false) {
|
||||
const allPlayers = [...this.players.playerMap.entries()];
|
||||
const matching = allPlayers.filter(([, player]) => filter(player));
|
||||
|
||||
if (matching.length === 0) {
|
||||
const has247 = allPlayers.some(([, player]) => player._home247Channel);
|
||||
const hintLine = showHintIfEmpty && has247
|
||||
? `\n\n💡 No ghosts auto-detected, but 24/7 channels with dead WebSockets may still report as "connected".\nUse \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`
|
||||
: "";
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(SUCCESS_COLOR)
|
||||
.setTitle(`Debug — ${title}`)
|
||||
.setDescription(`No ${noun} found. All voice connections appear healthy.${hintLine}`)
|
||||
;
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
const statusLines = [
|
||||
`🔄 **24/7 Force Rejoin** — Found **${channels247.length}** 24/7 channel(s)`,
|
||||
`🔄 **${title}** — Found **${matching.length}** ${noun}`,
|
||||
`Destroying stale connections and respawning fresh players...`,
|
||||
``,
|
||||
];
|
||||
|
||||
for (let i = 0; i < channels247.length; i++) {
|
||||
const [cid, player] = channels247[i];
|
||||
const channel = this.client.channels.get(cid);
|
||||
const gId = player._guildId ?? channel?.guildId;
|
||||
const guild = gId ? this.client.guilds.get(cleanId(gId)) : null;
|
||||
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
||||
for (let i = 0; i < matching.length; i++) {
|
||||
const [cid, player] = matching[i];
|
||||
const label = buildPlayerLabel(this.client, cid, player);
|
||||
const ghost = isGhostConnection(player) ? " 👻GHOST" : "";
|
||||
const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none";
|
||||
const connectedLabel = player.connection?.room?.isConnected ? "yes" : "no";
|
||||
@@ -266,167 +412,25 @@ export async function run(msg, data) {
|
||||
|
||||
const statusEmbed = new EmbedBuilder()
|
||||
.setColor(WARN_COLOR)
|
||||
.setTitle("Debug — 24/7 Rejoin")
|
||||
.setDescription(statusLines.join("\n").slice(0, 4096))
|
||||
.setTitle(`Debug — ${title}`)
|
||||
.setDescription(statusLines.join("\n").slice(0, MAX_DESC))
|
||||
;
|
||||
const statusMsg = await msg.reply({ embeds: [statusEmbed] });
|
||||
|
||||
const results = [];
|
||||
const results = await processRejoinBatch(this, matching, statusMsg, title);
|
||||
|
||||
for (let i = 0; i < channels247.length; i++) {
|
||||
const [cid, player] = channels247[i];
|
||||
const channel = this.client.channels.get(cid);
|
||||
const gId = player._guildId ?? channel?.guildId;
|
||||
const guild = gId ? this.client.guilds.get(cleanId(gId)) : null;
|
||||
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
||||
|
||||
const result = await forceRejoinPlayer(this, player);
|
||||
result.label = label;
|
||||
results.push(result);
|
||||
|
||||
if (i < channels247.length - 1) {
|
||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||
}
|
||||
}
|
||||
|
||||
const resultLines = [
|
||||
`🔄 **24/7 Rejoin Complete**`,
|
||||
`Channels processed: **${channels247.length}**`,
|
||||
``,
|
||||
];
|
||||
|
||||
let rejoinedCount = 0;
|
||||
let resumedCount = 0;
|
||||
let failedCount = 0;
|
||||
|
||||
for (const r of results) {
|
||||
if (r.success) {
|
||||
rejoinedCount++;
|
||||
if (r.resumedPlayback) resumedCount++;
|
||||
resultLines.push(`✅ \`${r.label}\` — rejoined (room:${r.roomState}, playback:${r.resumedPlayback ? "resumed" : "no track"})`);
|
||||
} else {
|
||||
failedCount++;
|
||||
resultLines.push(`❌ \`${r.label}\` — failed${r.reason ? ` (${r.reason})` : ""}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (failedCount === 0) {
|
||||
resultLines.push("", `All **${rejoinedCount}** 24/7 channel(s) restored.${resumedCount > 0 ? ` ${resumedCount} had playback resumed.` : ""}`);
|
||||
} else {
|
||||
resultLines.push("", `⚠️ **${failedCount}** channel(s) could not be restored.`);
|
||||
}
|
||||
|
||||
const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR;
|
||||
const finalEmbed = new EmbedBuilder()
|
||||
.setColor(finalColor)
|
||||
.setTitle("Debug — 24/7 Rejoin")
|
||||
.setDescription(resultLines.join("\n").slice(0, 4096))
|
||||
;
|
||||
await statusMsg.edit({ embeds: [finalEmbed] }).catch(() => {
|
||||
msg.reply({ embeds: [finalEmbed] });
|
||||
const finalPayload = buildRejoinResultEmbed(results, title, noun);
|
||||
await statusMsg.edit(finalPayload).catch(() => {
|
||||
msg.reply(finalPayload);
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "voice-rejoin": {
|
||||
const allPlayers = [...this.players.playerMap.entries()];
|
||||
const ghostEntries = allPlayers.filter(([, player]) => isGhostConnection(player));
|
||||
|
||||
if (ghostEntries.length === 0) {
|
||||
const has247 = allPlayers.some(([, player]) => player._home247Channel);
|
||||
const hintLine = has247
|
||||
? `\n\n💡 No ghosts auto-detected, but 24/7 channels with dead WebSockets may still report as "connected".\nUse \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`
|
||||
: "";
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(SUCCESS_COLOR)
|
||||
.setTitle("Debug — Voice Rejoin")
|
||||
.setDescription(`No ghost connections found. All voice connections appear healthy.${hintLine}`)
|
||||
;
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
const statusLines = [
|
||||
`🔍 **Voice Rejoin** — Found **${ghostEntries.length}** ghost connection(s)`,
|
||||
`Destroying stale connections and respawning fresh players...`,
|
||||
``,
|
||||
];
|
||||
|
||||
for (let i = 0; i < ghostEntries.length; i++) {
|
||||
const [cid, player] = ghostEntries[i];
|
||||
const channel = this.client.channels.get(cid);
|
||||
const gId = player._guildId ?? channel?.guildId;
|
||||
const guild = gId ? this.client.guilds.get(cleanId(gId)) : null;
|
||||
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
||||
const is247 = player._home247Channel ? "yes" : "no";
|
||||
const hasTrack = player.queue?.getCurrent() ? "yes" : "no";
|
||||
statusLines.push(`👻 \`${label}\` — 247:${is247} hasTrack:${hasTrack}`);
|
||||
}
|
||||
|
||||
const statusEmbed = new EmbedBuilder()
|
||||
.setColor(WARN_COLOR)
|
||||
.setTitle("Debug — Voice Rejoin")
|
||||
.setDescription(statusLines.join("\n").slice(0, 4096))
|
||||
;
|
||||
const statusMsg = await msg.reply({ embeds: [statusEmbed] });
|
||||
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < ghostEntries.length; i++) {
|
||||
const [cid, player] = ghostEntries[i];
|
||||
const channel = this.client.channels.get(cid);
|
||||
const gId = player._guildId ?? channel?.guildId;
|
||||
const guild = gId ? this.client.guilds.get(cleanId(gId)) : null;
|
||||
const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`;
|
||||
|
||||
const result = await forceRejoinPlayer(this, player);
|
||||
result.label = label;
|
||||
results.push(result);
|
||||
|
||||
if (i < ghostEntries.length - 1) {
|
||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||
}
|
||||
}
|
||||
|
||||
const resultLines = [
|
||||
`🔍 **Voice Rejoin Complete**`,
|
||||
`Ghosts found: **${ghostEntries.length}**`,
|
||||
``,
|
||||
];
|
||||
|
||||
let rejoinedCount = 0;
|
||||
let resumedCount = 0;
|
||||
let failedCount = 0;
|
||||
|
||||
for (const r of results) {
|
||||
if (r.success) {
|
||||
rejoinedCount++;
|
||||
if (r.resumedPlayback) resumedCount++;
|
||||
resultLines.push(`✅ \`${r.label}\` — rejoined (room:${r.roomState}, playback:${r.resumedPlayback ? "resumed" : "no track"})`);
|
||||
} else {
|
||||
failedCount++;
|
||||
resultLines.push(`❌ \`${r.label}\` — failed${r.reason ? ` (${r.reason})` : ""}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (failedCount === 0) {
|
||||
resultLines.push("", `All **${rejoinedCount}** ghost connection(s) restored.${resumedCount > 0 ? ` ${resumedCount} had playback resumed.` : ""}`);
|
||||
} else {
|
||||
resultLines.push("", `⚠️ **${failedCount}** connection(s) could not be restored.`);
|
||||
}
|
||||
|
||||
const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR;
|
||||
const finalEmbed = new EmbedBuilder()
|
||||
.setColor(finalColor)
|
||||
.setTitle("Debug — Voice Rejoin")
|
||||
.setDescription(resultLines.join("\n").slice(0, 4096))
|
||||
;
|
||||
await statusMsg.edit({ embeds: [finalEmbed] }).catch(() => {
|
||||
msg.reply({ embeds: [finalEmbed] });
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "voice": {
|
||||
/**
|
||||
* Run the full voice diagnostic with paginated output.
|
||||
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function runVoiceDiagnostic(msg) {
|
||||
const servers = [...this.players.playerMap.entries()].map(([cid, s]) => {
|
||||
const channel = this.client.channels.get(cid);
|
||||
const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id;
|
||||
@@ -476,8 +480,6 @@ export async function run(msg, data) {
|
||||
pendingChannels: pending,
|
||||
};
|
||||
|
||||
const MAX_DESC = 4096;
|
||||
|
||||
const pages = [];
|
||||
|
||||
const summaryLines = [
|
||||
@@ -534,23 +536,21 @@ export async function run(msg, data) {
|
||||
}
|
||||
pages.push(summaryLines.join("\n"));
|
||||
|
||||
{
|
||||
let groupJson = "";
|
||||
|
||||
let i = 0;
|
||||
for (i = 0; i < servers.length; i++) {
|
||||
for (let i = 0; i < servers.length; i++) {
|
||||
const singleJson = JSON.stringify(servers[i], null, 2);
|
||||
const candidate = groupJson
|
||||
? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1)
|
||||
: singleJson;
|
||||
|
||||
if (("```json\n" + candidate + "\n```").length > MAX_DESC && groupJson) {
|
||||
const candidateLen = ("```json\n" + candidate + "\n```").length;
|
||||
|
||||
if (candidateLen > MAX_DESC && groupJson) {
|
||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||
groupJson = singleJson;
|
||||
} else if (("```json\n" + candidate + "\n```").length > MAX_DESC) {
|
||||
} else if (candidateLen > MAX_DESC) {
|
||||
const budget = MAX_DESC - 12;
|
||||
groupJson = singleJson.slice(0, budget);
|
||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||
pages.push(("```json\n" + singleJson.slice(0, budget) + "\n```").slice(0, MAX_DESC));
|
||||
groupJson = "";
|
||||
} else {
|
||||
groupJson = candidate;
|
||||
@@ -559,7 +559,6 @@ export async function run(msg, data) {
|
||||
if (groupJson) {
|
||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||
}
|
||||
}
|
||||
|
||||
if (pages.length === 1) {
|
||||
const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor();
|
||||
@@ -575,15 +574,16 @@ export async function run(msg, data) {
|
||||
let currentPage = 0;
|
||||
|
||||
const buildPage = (pageIdx, expired = false) => {
|
||||
const pageLabel = pageIdx === 0
|
||||
const isSummaryPage = pageIdx === 0;
|
||||
const pageLabel = isSummaryPage
|
||||
? "Summary"
|
||||
: `Player Detail${pages[pageIdx].includes(",") ? "s" : ""}`;
|
||||
: `Player Detail${pages[pageIdx].split(`"name":`).length - 1 > 1 ? "s" : ""}`;
|
||||
const footerText = expired
|
||||
? this.t(msg, "responses._common.controlsExpired")
|
||||
: `${this.t(msg, "responses.debug.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`;
|
||||
|
||||
const embedColor = (pageIdx === 0 && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor();
|
||||
const titleSuffix = (pageIdx === 0 && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "";
|
||||
const embedColor = (isSummaryPage && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor();
|
||||
const titleSuffix = (isSummaryPage && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "";
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(embedColor)
|
||||
@@ -605,9 +605,9 @@ export async function run(msg, data) {
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await replyMsg.message.removeAllReactions();
|
||||
} catch {
|
||||
} catch (e) {
|
||||
for (const emoji of navEmojis) {
|
||||
try { await replyMsg.message.removeReaction(emoji); } catch(e) { logger.warn("[Debug] Error:", e?.message); }
|
||||
try { await replyMsg.message.removeReaction(emoji); } catch (err) { logger.warn("[Debug] removeReaction fallback:", err?.message); }
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -623,7 +623,9 @@ export async function run(msg, data) {
|
||||
};
|
||||
|
||||
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||
if (e.emoji_id === "❌") {
|
||||
const emoji = e?.emoji_id ?? e?.emoji?.id ?? e?.emoji;
|
||||
|
||||
if (emoji === "❌") {
|
||||
clearTimeout(emojiTimeout);
|
||||
unobserve?.();
|
||||
await replyMsg.message.delete().catch(() => {});
|
||||
@@ -632,9 +634,9 @@ export async function run(msg, data) {
|
||||
|
||||
resetTimer();
|
||||
|
||||
if (e.emoji_id === "⬅️") {
|
||||
if (emoji === "⬅️") {
|
||||
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
||||
} else if (e.emoji_id === "➡️") {
|
||||
} else if (emoji === "➡️") {
|
||||
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
@@ -642,7 +644,4 @@ export async function run(msg, data) {
|
||||
});
|
||||
|
||||
resetTimer();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user