rollllbackkk

This commit is contained in:
NoLogicAlan committed 2026-05-14 17:18:16 +03:00
1 parent 18d46e6df0
commit 3c14f04756
11 files changed
+625 -743

No files matched your search

+4 -4
View File
@@ -273,7 +273,7 @@ export async function run(msg) {
for (const emoji of allEmojisForPage(p)) { for (const emoji of allEmojisForPage(p)) {
try { try {
await menuMsg.message.react(emoji); await menuMsg.message.react(emoji);
await Utils.sleep(25); await Utils.sleep(150);
} catch (_) {} } catch (_) {}
} }
}; };
@@ -389,7 +389,7 @@ export async function run(msg) {
.setDescription(this.t(msg, "responses.filter.nothingPlaying")) .setDescription(this.t(msg, "responses.filter.nothingPlaying"))
; ;
await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {}); await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {});
await Utils.sleep(500); await Utils.sleep(2000);
await menuMsg.edit({ await menuMsg.edit({
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)] embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)]
}).catch(() => {}); }).catch(() => {});
@@ -430,7 +430,7 @@ export async function run(msg) {
) )
; ;
await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {}); await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {});
await Utils.sleep(900); await Utils.sleep(3000);
await menuMsg.edit({ await menuMsg.edit({
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, track)] embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, track)]
}).catch(() => {}); }).catch(() => {});
@@ -462,7 +462,7 @@ export async function run(msg) {
; ;
await menuMsg.edit({ embeds: [confirmEmbed] }).catch(() => {}); await menuMsg.edit({ embeds: [confirmEmbed] }).catch(() => {});
await Utils.sleep(700); await Utils.sleep(2500);
// Restore picker (session stays open) // Restore picker (session stays open)
if (!settled) { if (!settled) {
+2 -1
View File
@@ -28,7 +28,8 @@ export async function run(msg, data) {
if (!targetChannel) return msg.reply(embed(this.t(msg, "responses.forceleave.channelNotFound"))); if (!targetChannel) return msg.reply(embed(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(embed(this.t(msg, "responses.forceleave.wrongServer")));
const p = this.players.findPlayerEntryByChannelId(cid)?.player ?? null; const p = this.players.playerMap.get(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(embed(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(embed(this.t(msg, "responses.forceleave.playerNotInit")));
await this.players.leave(msg, cid); await this.players.leave(msg, cid);
+107 -25
View File
@@ -1,4 +1,5 @@
import { CommandBuilder } from "../src/CommandHandler.mjs"; import { CommandBuilder } from "../src/CommandHandler.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 { get247ChannelMode } from "../src/constants/Helpers247.mjs"; import { get247ChannelMode } from "../src/constants/Helpers247.mjs";
@@ -22,6 +23,22 @@ function cleanId(value) {
return String(value ?? "").replace(/\D/g, ""); return String(value ?? "").replace(/\D/g, "");
} }
/**
* Resolve the guild ID from a player entry.
* Uses _guildId if set (populated after join() completes), otherwise falls
* back to the client channel cache. This is necessary because in the
* multi-voice scenario _guildId can still be null for a freshly-joined player,
* which caused guildPlayers to be empty and leave to report "not in voice".
*/
function resolvePlayerGuildId(player, mapKey, client) {
const direct = cleanId(player?._guildId);
if (direct) return direct;
const cid = cleanId(player?._channelId ?? mapKey);
if (!cid) return "";
const ch = client?.channels?.get?.(cid);
return cleanId(ch?.guildId ?? ch?.guild?.id ?? ch?.server_id ?? ch?.serverId);
}
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
@@ -32,7 +49,15 @@ export async function run(msg, data) {
?? msg.message?.serverId; ?? msg.message?.serverId;
const cleanGuildId = cleanId(guildId); const cleanGuildId = cleanId(guildId);
const guildPlayers = this.players.findGuildPlayers(cleanGuildId); // Gather all active players in this guild.
// resolvePlayerGuildId handles players whose _guildId is still null by
// checking the channel cache — critical for the multi-voice use case where
// a player may have been joined before _guildId was written.
const client = this.client;
const guildPlayers = [...this.players.playerMap.entries()].filter(([mapKey, p]) => {
if (p?._destroyed) return false;
return resolvePlayerGuildId(p, mapKey, client) === cleanGuildId;
});
// Resolve the target channel to leave: // Resolve the target channel to leave:
// 1. If a channel option was provided, use that // 1. If a channel option was provided, use that
@@ -69,8 +94,11 @@ export async function run(msg, data) {
// Match against both the map key and _channelId because after a voice-move // Match against both the map key and _channelId because after a voice-move
// these can differ (the map key stays as the original join channel ID while // these can differ (the map key stays as the original join channel ID while
// _channelId updates to the new channel). // _channelId updates to the new channel).
const playerEntry = this.players.findPlayerEntryByChannelId(targetChannelId); const player = this.players.playerMap.get(targetChannelId)
const player = playerEntry?.player ?? null; ?? guildPlayers.find(([mapKey, p]) =>
cleanId(p._channelId) === targetChannelId || cleanId(mapKey) === targetChannelId
)?.[1]
?? null;
if (!player) { if (!player) {
// No player in that channel — check if user picked a non-voice channel // No player in that channel — check if user picked a non-voice channel
@@ -114,36 +142,90 @@ export async function run(msg, data) {
return mode === "auto"; return mode === "auto";
}); });
const matchChannel = ch247.has(homeChannelId) ? homeChannelId if (ch247.has(activeChannelId) || ch247.has(homeChannelId)) {
: ch247.has(activeChannelId) ? activeChannelId const matchChannel = ch247.has(homeChannelId) ? homeChannelId
: null; : ch247.has(activeChannelId) ? activeChannelId
const mode = matchChannel ? get247ChannelMode(set, matchChannel) : "off"; : null;
const mode = matchChannel ? get247ChannelMode(set, matchChannel) : "off";
if (matchChannel) {
this.markIntentionalLeave(activeChannelId); this.markIntentionalLeave(activeChannelId);
if (homeChannelId !== activeChannelId) this.markIntentionalLeave(homeChannelId); this.players.playerMap.delete(activeChannelId);
if (activeChannelId !== targetChannelId) this.players.playerMap.delete(targetChannelId);
this.players.detachPlayer(player, targetChannelId); if (homeChannelId !== activeChannelId) this.players.playerMap.delete(homeChannelId);
await player.leave().catch(() => {}); await player.leave().catch(() => {});
player.destroy(); player.destroy();
const respawnBaseDelay = this.config?.timers?.leave247RejoinDelay ?? 5000;
const respawnStagger = this.config?.timers?.rejoin247Delay ?? 3000;
if (mode === "auto") { if (mode === "auto") {
msg.reply(embed(this.t(msg, "responses.leave.leftRejoin247", { channel: targetChannelId, prefix: set?.get("prefix") ?? "%" }))); msg.reply(embed(this.t(msg, "responses.leave.leftRejoin247", { channel: targetChannelId, prefix: set?.get("prefix") ?? "%" })));
this.players.schedule247Respawns(guildId, [homeChannelId, ...other247AutoChannels], { const leave247Delay = this.config?.timers?.leave247RejoinDelay ?? 5000;
baseDelay: respawnBaseDelay, setTimeout(() => {
stagger: respawnStagger, if (this._spawnPlayer) {
source: "leave", this._spawnPlayer(guildId, homeChannelId).catch(e =>
}); logger.warn("[leave] 247 rejoin failed for", homeChannelId, e.message)
);
}
}, leave247Delay);
// ── Rejoin other 24/7 auto channels that may have been disconnected ──
// If the gateway sent a guild-level leave, all other 24/7 auto channels
// also lost their connections. Schedule a rejoin for each one with a
// staggered delay to avoid overloading the global join queue.
if (other247AutoChannels.length > 0) {
const rejoinBaseDelay = leave247Delay;
const rejoinStagger = this.config?.timers?.rejoin247Delay ?? 3000;
for (let i = 0; i < other247AutoChannels.length; i++) {
const otherChannelId = other247AutoChannels[i];
const otherPlayer = this.players.playerMap.get(otherChannelId);
// Only rejoin if the player is gone (was collateral-disconnected)
if (!otherPlayer || otherPlayer._destroyed) {
// Clean up the dead player from the map
if (otherPlayer) {
this.players.playerMap.delete(otherChannelId);
try { otherPlayer.destroy(); } catch (_) {}
}
const delay = rejoinBaseDelay + (i + 1) * rejoinStagger;
logger.recovery(
`[leave] Scheduling 247 auto-rejoin for collateral-disconnected channel ${otherChannelId} in ${delay}ms`
);
setTimeout(() => {
if (this._spawnPlayer) {
this._spawnPlayer(guildId, otherChannelId).catch(e =>
logger.warn("[leave] 247 collateral rejoin failed for", otherChannelId, e.message)
);
}
}, delay);
}
}
}
} else { } else {
// Mode is "on" — bot left, won't rejoin automatically for this channel.
// But still check if other 24/7 auto channels need rejoining.
msg.reply(embed(this.t(msg, "responses.leave.left247On", { prefix: set?.get("prefix") ?? "%" }))); msg.reply(embed(this.t(msg, "responses.leave.left247On", { prefix: set?.get("prefix") ?? "%" })));
this.players.schedule247Respawns(guildId, other247AutoChannels, {
baseDelay: respawnBaseDelay, if (other247AutoChannels.length > 0) {
stagger: respawnStagger, const rejoinDelay = this.config?.timers?.leave247RejoinDelay ?? 5000;
source: "leave", const rejoinStagger = this.config?.timers?.rejoin247Delay ?? 3000;
}); for (let i = 0; i < other247AutoChannels.length; i++) {
const otherChannelId = other247AutoChannels[i];
const otherPlayer = this.players.playerMap.get(otherChannelId);
if (!otherPlayer || otherPlayer._destroyed) {
if (otherPlayer) {
this.players.playerMap.delete(otherChannelId);
try { otherPlayer.destroy(); } catch (_) {}
}
const delay = rejoinDelay + (i + 1) * rejoinStagger;
logger.recovery(
`[leave] Scheduling 247 auto-rejoin for collateral-disconnected channel ${otherChannelId} in ${delay}ms`
);
setTimeout(() => {
if (this._spawnPlayer) {
this._spawnPlayer(guildId, otherChannelId).catch(e =>
logger.warn("[leave] 247 collateral rejoin failed for", otherChannelId, e.message)
);
}
}, delay);
}
}
}
} }
} else { } else {
await this.leaveChannel(activeChannelId, guildId, msg); await this.leaveChannel(activeChannelId, guildId, msg);
+145 -364
View File
@@ -9,436 +9,217 @@ export const command = new CommandBuilder()
.addAliases("info") .addAliases("info")
.setCategory("util"); .setCategory("util");
const CACHE_TTL_MS = 5 * 60 * 1000; // ── Stats cache ───────────────────────────────────────────────────────────────
const GUILD_FETCH_TIMEOUT_MS = 4_000;
const REST_PAGE_TIMEOUT_MS = 1_000;
const LASTFM_TIMEOUT_MS = 3_000;
let cachedStats = null; const CACHE_TTL_MS = 5 * 60 * 1000; // refresh every 5 minutes
let cacheExpiresAt = 0;
let inflightStatsPromise = null;
function isAbortError(err) { let cachedStats = null; // { guildCount, userCount } or null
const name = String(err?.name ?? ""); let cacheExpiresAt = 0;
const code = String(err?.code ?? ""); let inflightPromise = null;
const message = String(err?.message ?? err ?? "");
return name === "AbortError" ||
code === "ABORT_ERR" ||
message.includes("This operation was aborted");
}
function getMessageGuildId(message) { /**
return message?.channel?.channel?.guildId ?? * Accurate guild count — same multi-layer strategy as ErinJS:
message?.message?.guildId ?? * 1. Try client.fetchTotalGuildCount() (shard-aware, if available)
message?.guildId ?? * 2. Try client.fetchAllStats().guilds (shard-aware, if available)
null; * 3. Paginate REST API via /users/@me/guilds?limit=200
} * 4. Fallback to client.guilds.size (local shard only)
*/
function createTranslator(remix) { async function fetchAccurateGuildCount(client) {
return (message, key, data = {}) => { // Strategy 1: built-in shard-aware method
const guildId = getMessageGuildId(message); if (typeof client.fetchTotalGuildCount === "function") {
return remix?.locale?.translate?.(guildId, key, data) ?? key;
};
}
function withTimeout(promise, ms, fallback) {
return Promise.race([
Promise.resolve(promise),
new Promise((resolve) => setTimeout(() => resolve(fallback), ms)),
]);
}
async function runLimited(tasks, limit = 6) {
const results = new Array(tasks.length);
let index = 0;
async function worker() {
while (index < tasks.length) {
const current = index++;
try {
results[current] = await tasks[current]();
} catch (_) {
results[current] = null;
}
}
}
const workers = Array.from({ length: Math.min(limit, tasks.length) }, () => worker());
await Promise.all(workers);
return results;
}
function getCachedGuildCount(client) {
return Number(client?.guilds?.size ?? 0);
}
function getFastCachedUserCount() {
return Number(cachedStats?.userCount ?? 0);
}
function getCachedUserCount(client) {
const uniqueUsers = new Set();
for (const guild of client?.guilds?.values?.() ?? []) {
const members = guild?.members;
const iterable = typeof members?.values === "function"
? members.values()
: Array.isArray(members)
? members
: Object.values(members ?? {});
for (const member of iterable) {
const id = member?.id ?? member?.user?.id ?? null;
if (id) uniqueUsers.add(String(id));
}
}
return uniqueUsers.size;
}
async function fetchGuildCount(client) {
if (typeof client?.user?.fetchGuilds === "function") {
try { try {
const guilds = await withTimeout(client.user.fetchGuilds(), GUILD_FETCH_TIMEOUT_MS, null); const count = await client.fetchTotalGuildCount();
if (Array.isArray(guilds)) return guilds.length; if (typeof count === "number" && count >= 0) return count;
if (typeof guilds?.size === "number") return guilds.size; } catch {}
if (typeof guilds?.values === "function") return [...guilds.values()].length;
} catch (_) {}
} }
if (typeof client?.fetchTotalGuildCount === "function") { // Strategy 2: built-in stats aggregator
if (typeof client.fetchAllStats === "function") {
try { try {
const total = await withTimeout(client.fetchTotalGuildCount(), GUILD_FETCH_TIMEOUT_MS, null); const stats = await client.fetchAllStats();
if (typeof total === "number" && total >= 0) return total;
} catch (_) {}
}
if (typeof client?.fetchAllStats === "function") {
try {
const stats = await withTimeout(client.fetchAllStats(), GUILD_FETCH_TIMEOUT_MS, null);
if (typeof stats?.guilds === "number" && stats.guilds >= 0) return stats.guilds; if (typeof stats?.guilds === "number" && stats.guilds >= 0) return stats.guilds;
} catch (_) {} } catch {}
} }
if (client?.rest && typeof client.rest.get === "function") { // Strategy 3: REST API pagination — gets all guilds across shards
if (client.rest && typeof client.rest.get === "function") {
try { try {
let total = 0; let total = 0;
let after = null; let after = undefined;
for (let page = 0; page < 500; page++) {
for (let page = 0; page < 25; page++) {
const route = `/users/@me/guilds?limit=200${after ? `&after=${after}` : ""}`; const route = `/users/@me/guilds?limit=200${after ? `&after=${after}` : ""}`;
const response = await withTimeout(client.rest.get(route), REST_PAGE_TIMEOUT_MS, null); const response = await client.rest.get(route);
if (!response) break;
const batch = Array.isArray(response) ? response : (response?.guilds ?? []); const batch = Array.isArray(response) ? response : (response?.guilds ?? []);
total += batch.length; total += batch.length;
if (batch.length < 200) break; if (batch.length < 200) break;
after = batch[batch.length - 1]?.id;
after = batch[batch.length - 1]?.id ?? null;
if (!after) break; if (!after) break;
} }
return total;
if (total > 0) return total; } catch {}
} catch (_) {}
} }
return getCachedGuildCount(client); // Strategy 4: fallback — local shard cache only
return client.guilds?.size ?? 0;
} }
function collectIdsFromMembers(guild) { /**
const ids = new Set(); * Accurate user count — sum memberCount across all guilds.
const members = guild?.members; * Uses guild.memberCount from the GUILD_CREATE payload (O(1), no API calls).
const iterable = typeof members?.values === "function" * Falls back to guild.members.size if memberCount is missing.
? members.values() */
: Array.isArray(members) function computeUserCount(client) {
? members let total = 0;
: Object.values(members ?? {}); for (const [, guild] of client.guilds) {
total += guild.memberCount ?? guild.members?.size ?? 0;
for (const member of iterable) {
const id = member?.id ?? member?.user?.id ?? null;
if (id) ids.add(String(id));
} }
return total;
return ids;
}
async function fetchGuildMemberIds(guild) {
if (typeof guild?.members?.fetch !== "function") {
return collectIdsFromMembers(guild);
}
try {
const ids = new Set();
let after = undefined;
for (let page = 0; page < 1000; page++) {
const raw = await guild.members.fetch({ limit: 1000, after });
const batch = Array.isArray(raw)
? raw
: typeof raw?.values === "function"
? [...raw.values()]
: Object.values(raw ?? {});
for (const member of batch) {
const id = member?.id ?? member?.user?.id ?? null;
if (id) ids.add(String(id));
}
if (batch.length < 1000) break;
after = batch.reduce((max, member) => {
const id = String(member?.id ?? member?.user?.id ?? "");
return id > max ? id : max;
}, "0");
if (!after) break;
}
return ids;
} catch (_) {
return collectIdsFromMembers(guild);
}
}
async function fetchUserCount(client) {
const guilds = [...(client?.guilds?.values?.() ?? [])];
if (guilds.length === 0) return 0;
const idSets = await runLimited(
guilds.map((guild) => () => fetchGuildMemberIds(guild)),
8
);
const uniqueUsers = new Set();
for (const idSet of idSets) {
if (!idSet || typeof idSet[Symbol.iterator] !== "function") continue;
for (const id of idSet) uniqueUsers.add(String(id));
}
return uniqueUsers.size;
} }
async function refreshStats(client) { async function refreshStats(client) {
try { try {
cachedStats = { const [guildCount, userCount] = await Promise.all([
guildCount: await fetchGuildCount(client), fetchAccurateGuildCount(client),
userCount: await fetchUserCount(client), Promise.resolve(computeUserCount(client)),
}; ]);
} catch (_) { cachedStats = { guildCount, userCount };
cachedStats = { } catch (err) {
guildCount: getCachedGuildCount(client), console.error("[stats] refreshStats failed:", err);
userCount: getCachedUserCount(client), // Keep old cache instead of overwriting with bad data
}; if (cachedStats) {
} finally { cacheExpiresAt = Date.now() + CACHE_TTL_MS;
cacheExpiresAt = Date.now() + CACHE_TTL_MS; inflightPromise = null;
inflightStatsPromise = null; return cachedStats;
}
cachedStats = { guildCount: client.guilds?.size ?? 0, userCount: 0 };
} }
cacheExpiresAt = Date.now() + CACHE_TTL_MS;
inflightPromise = null;
return cachedStats; return cachedStats;
} }
function getStats(client) { function getStats(client) {
if (cachedStats && Date.now() < cacheExpiresAt) { if (cachedStats && Date.now() < cacheExpiresAt) return Promise.resolve(cachedStats);
return Promise.resolve(cachedStats); if (!inflightPromise) inflightPromise = refreshStats(client);
} return inflightPromise;
if (!inflightStatsPromise) {
inflightStatsPromise = refreshStats(client);
}
return inflightStatsPromise;
}
function getLastfmSnapshot(lastfm) {
return {
scrobbleCount: Number(lastfm?._totalScrobblesCache ?? 0),
linkedUsers: Number(lastfm?._linkedUsersCache ?? 0),
};
} }
function getLivePlayerCount(playerMap) { function getLivePlayerCount(playerMap) {
let count = 0; let live = 0;
for (const player of playerMap?.values?.() ?? []) { for (const [, player] of playerMap ?? []) {
if (!player || player._destroyed || player.leaving || player._isJoining) continue; if (!player || player._destroyed || player.leaving) continue;
if (player._isJoining) continue;
const room = player?.connection?.room; const conn = player.connection;
if (room && !room.isConnected && (room.connectionState === 0 || room.connectionState === "disconnected")) { if (!conn) continue;
continue;
const room = conn.room;
if (room) {
const isConnected = room.isConnected;
const connectionState = room.connectionState;
if (!isConnected && (connectionState === 0 || connectionState === "disconnected")) continue;
} }
if (!player.connection) continue; live++;
count++;
} }
return count; return live;
} }
function buildEmbed(t, message, stats) { // ── Embed builder ─────────────────────────────────────────────────────────────
const num = (value) => Utils.formatNumber(Number(value ?? 0));
const maybeLoading = (value, loading) => loading ? "..." : value;
const lines = [ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) {
`${t(message, "responses.stats.servers")} — \`${num(stats.guildCount)}\``, const num = (v) => Utils.formatNumber(v);
`${t(message, "responses.stats.users")} — \`${maybeLoading(num(stats.userCount), stats.loading)}\``, const ld = (v) => loading ? "..." : v;
`${t(message, "responses.stats.players")} — \`${num(stats.playerCount)}\``,
const description = [
`${t(msg, "responses.stats.servers")} — \`${num(guildCount)}\``,
`${t(msg, "responses.stats.users")} — \`${ld(num(userCount))}\``,
`${t(msg, "responses.stats.players")} — \`${num(playerCount)}\``,
]; ];
if (stats.lastfmEnabled) { // Add Last.fm stats if the integration is enabled
lines.push(`${t(message, "responses.stats.scrobbles")} — \`${maybeLoading(num(stats.scrobbleCount), stats.loading)}\``); if (lastfmEnabled) {
lines.push(`${t(message, "responses.stats.linkedUsers")} — \`${maybeLoading(num(stats.linkedUsers), stats.loading)}\``); description.push(`${t(msg, "responses.stats.scrobbles")} — \`${ld(num(scrobbleCount))}\``);
description.push(`${t(msg, "responses.stats.linkedUsers")} — \`${ld(num(linkedUsers))}\``);
} }
lines.push( description.push(
`${t(message, "responses.stats.ping")} — \`${maybeLoading(`${num(stats.ping)}ms`, stats.loading)}\``, `${t(msg, "responses.stats.ping")} — \`${ld(`${num(ping)}ms`)}\``,
`${t(message, "responses.stats.uptime")} — \`${stats.uptime}\``, `${t(msg, "responses.stats.uptime")} — \`${uptime}\``,
`${t(message, "responses.stats.build")} — [\`${stats.comHash}\`](${stats.comLink})` `${t(msg, "responses.stats.build")} — [\`${comHash}\`](${comLink})`,
reason ? `${t(msg, "responses.stats.lastRestart")} — \`${reason}\`` : null,
``,
t(msg, "responses.stats.supportKofi"),
t(msg, "responses.stats.community"),
); );
if (stats.reason) { const desc = description.filter(l => l !== null).join("\n");
lines.push(`${t(message, "responses.stats.lastRestart")} — \`${stats.reason}\``);
}
lines.push("", t(message, "responses.stats.supportKofi"), t(message, "responses.stats.community")); const builder = new EmbedBuilder()
const embed = new EmbedBuilder()
.setColor(getGlobalColor()) .setColor(getGlobalColor())
.setAuthor({ name: t(message, "responses.stats.title") }) .setAuthor({ name: t(msg, "responses.stats.title") })
.setDescription(lines.join("\n")) .setDescription(desc)
.setFooter({ text: stats.footer || t(message, "responses.stats.title") }); .setFooter({ text: footer || t(msg, "responses.stats.title") });
if (typeof embed.setTimestamp === "function") { if (typeof builder.setTimestamp === "function") builder.setTimestamp();
embed.setTimestamp(); return builder;
}
return embed;
} }
async function editOrReply(messageRef, payload, fallbackMessage) { // ── Runner ────────────────────────────────────────────────────────────────────
try {
if (typeof messageRef?.edit === "function") {
await messageRef.edit(payload);
return true;
}
if (typeof messageRef?.message?.edit === "function") {
await messageRef.message.edit(payload);
return true;
}
} catch (err) {
console.error("[stats] edit failed:", err);
}
try {
await fallbackMessage.reply(payload);
return false;
} catch (err) {
if (!isAbortError(err)) {
console.error("[stats] fallback reply failed:", err);
}
return false;
}
}
async function safeReply(message, payload) {
try {
return await message.reply(payload);
} catch (err) {
if (!isAbortError(err)) {
throw err;
}
console.warn("[stats] reply aborted by Fluxer timeout");
return null;
}
}
export async function run(message) { export async function run(message) {
const t = createTranslator(this);
const lastfm = this.lastfm; const lastfm = this.lastfm;
const lastfmEnabled = lastfm?.enabled ?? false; const lastfmEnabled = lastfm?.enabled ?? false;
const lastfmSnapshot = getLastfmSnapshot(lastfm);
const baseStats = { const shared = {
guildCount: getCachedGuildCount(this.client), guildCount: this.client.guilds.size,
userCount: getFastCachedUserCount(),
playerCount: getLivePlayerCount(this.players.playerMap), playerCount: getLivePlayerCount(this.players.playerMap),
scrobbleCount: lastfmSnapshot.scrobbleCount, scrobbleCount: 0,
linkedUsers: lastfmSnapshot.linkedUsers, linkedUsers: 0,
lastfmEnabled, lastfmEnabled,
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000), uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
comHash: this.comHash, comHash: this.comHash,
comLink: this.comLink, comLink: this.comLink,
reason: this.config.restart ?? null, reason: this.config.restart ?? null,
footer: this.config.customStatsFooter || null, footer: this.config.customStatsFooter || null,
ping: 0,
loading: !cachedStats,
}; };
const cachedOrFallbackStats = cachedStats ?? { // Fetch Last.fm stats (non-blocking for initial reply)
guildCount: baseStats.guildCount, const scrobblePromise = lastfmEnabled ? lastfm.getTotalScrobbles() : Promise.resolve(0);
userCount: getCachedUserCount(this.client), const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0);
};
try { const hasCached = cachedStats !== null;
const start = Date.now();
const reply = await safeReply(message, {
embeds: [
buildEmbed(t, message, {
...baseStats,
guildCount: cachedOrFallbackStats.guildCount,
userCount: cachedOrFallbackStats.userCount,
}),
],
});
if (!reply) return;
const ping = Date.now() - start; // Measure real round-trip latency
const start = Date.now();
const msg = await message.reply({
embeds: [buildEmbed((...a) => this.t(...a), message, {
...shared,
guildCount: hasCached ? cachedStats.guildCount : shared.guildCount,
userCount: hasCached ? cachedStats.userCount : 0,
ping: 0,
loading: !hasCached,
})]
});
const ping = Date.now() - start;
const statsPromise = getStats(this.client).catch(() => cachedOrFallbackStats); const [stats, scrobbleCount, linkedUsers] = await Promise.all([
const scrobblePromise = lastfmEnabled getStats(this.client),
? withTimeout( scrobblePromise,
lastfm.getStoredTotalScrobbles?.() ?? Promise.resolve(lastfmSnapshot.scrobbleCount), linkedPromise,
LASTFM_TIMEOUT_MS, ]);
lastfmSnapshot.scrobbleCount
).catch(() => lastfmSnapshot.scrobbleCount)
: Promise.resolve(0);
const linkedPromise = lastfmEnabled
? withTimeout(
lastfm.getLinkedUsersCount?.() ?? Promise.resolve(lastfmSnapshot.linkedUsers),
LASTFM_TIMEOUT_MS,
lastfmSnapshot.linkedUsers
).catch(() => lastfmSnapshot.linkedUsers)
: Promise.resolve(0);
const [stats, scrobbleCount, linkedUsers] = await Promise.all([ await msg.edit({
statsPromise, embeds: [buildEmbed((...a) => this.t(...a), message, {
scrobblePromise, ...shared,
linkedPromise, guildCount: stats.guildCount,
]); userCount: stats.userCount,
scrobbleCount,
await editOrReply(reply, { linkedUsers,
embeds: [ ping,
buildEmbed(t, message, { loading: false,
...baseStats, })]
guildCount: stats?.guildCount ?? cachedOrFallbackStats.guildCount, }).catch((err) => console.error("[stats] editEmbed failed:", err));
userCount: stats?.userCount ?? cachedOrFallbackStats.userCount,
scrobbleCount,
linkedUsers,
ping,
loading: false,
}),
],
}, message);
} catch (err) {
if (!isAbortError(err)) {
console.error("[stats] run failed:", err);
}
const fallback = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription("Failed to load full stats. Please try again in a moment.");
await safeReply(message, { embeds: [fallback] }).catch(() => {});
}
} }
+19 -33
View File
@@ -606,7 +606,6 @@ export class Remix {
*/ */
_attachWsErrorHandlers() { _attachWsErrorHandlers() {
try { try {
if (this._wsErrorHandlersAttached) return;
const wsManager = this.client?.ws; const wsManager = this.client?.ws;
if (!wsManager) return; if (!wsManager) return;
@@ -658,7 +657,7 @@ export class Remix {
}); });
} }
this._wsErrorHandlersAttached = true; logger.player("[WS] Proactive error handlers attached to gateway sockets.");
} catch (e) { } catch (e) {
logger.warn("[WS] Failed to attach WS error handlers:", e.message); logger.warn("[WS] Failed to attach WS error handlers:", e.message);
} }
@@ -721,11 +720,10 @@ export class Remix {
} }
this.markIntentionalLeave(cleanId); this.markIntentionalLeave(cleanId);
const playerEntry = this.players.findPlayerEntryByChannelId?.(cleanId) ?? null;
const player = playerEntry?.player ?? null;
const player = this.players.playerMap.get(cleanId);
if (player) { if (player) {
this.players.detachPlayer?.(player, cleanId); this.players.playerMap.delete(cleanId);
await player.leave().catch(() => {}); await player.leave().catch(() => {});
player.destroy(); player.destroy();
} }
@@ -743,22 +741,28 @@ export class Remix {
if (other247AutoChannels.length > 0) { if (other247AutoChannels.length > 0) {
const rejoinBaseDelay = this.T?.leave247RejoinDelay ?? 5000; const rejoinBaseDelay = this.T?.leave247RejoinDelay ?? 5000;
const rejoinStagger = this.T?.rejoin247Delay ?? 3000; const rejoinStagger = this.T?.rejoin247Delay ?? 3000;
const channelsToRespawn = []; for (let i = 0; i < other247AutoChannels.length; i++) {
for (const otherChannelId of other247AutoChannels) { const otherChannelId = other247AutoChannels[i];
const otherPlayer = this.players.findPlayerEntryByChannelId?.(otherChannelId)?.player ?? null; const otherPlayer = this.players.playerMap.get(otherChannelId);
// Only rejoin if the player is gone (was collateral-disconnected)
if (!otherPlayer || otherPlayer._destroyed) { if (!otherPlayer || otherPlayer._destroyed) {
if (otherPlayer) { if (otherPlayer) {
this.players.detachPlayer?.(otherPlayer, otherChannelId); this.players.playerMap.delete(otherChannelId);
try { otherPlayer.destroy(); } catch (_) {} try { otherPlayer.destroy(); } catch (_) {}
} }
channelsToRespawn.push(otherChannelId); const delay = rejoinBaseDelay + (i + 1) * rejoinStagger;
logger.recovery(
`[leaveChannel] Scheduling 247 auto-rejoin for collateral-disconnected channel ${otherChannelId} in ${delay}ms`
);
setTimeout(() => {
if (this._spawnPlayer) {
this._spawnPlayer(guildId, otherChannelId).catch(e =>
logger.warn("[leaveChannel] 247 collateral rejoin failed for", otherChannelId, e.message)
);
}
}, delay);
} }
} }
this.players.schedule247Respawns?.(guildId, channelsToRespawn, {
baseDelay: rejoinBaseDelay,
stagger: rejoinStagger,
source: "leaveChannel",
});
} }
return true; return true;
@@ -908,21 +912,8 @@ const isIgnorableWsCrash = (err) => {
); );
}; };
const isAbortError = (err) => {
const name = String(err?.name ?? "");
const code = String(err?.code ?? "");
const message = String(err?.message ?? err ?? "");
return name === "AbortError" ||
code === "ABORT_ERR" ||
message.includes("This operation was aborted");
};
process.on("unhandledRejection", (reason, p) => { process.on("unhandledRejection", (reason, p) => {
if (reason?.message?.includes("AudioSource is closed")) return; if (reason?.message?.includes("AudioSource is closed")) return;
if (isAbortError(reason)) {
logger.warn("[Error_Handling] Suppressed AbortError from a timed-out request.");
return;
}
logger.error("[Error_Handling] Unhandled Rejection/Catch"); logger.error("[Error_Handling] Unhandled Rejection/Catch");
logger.error("Reason:", reason, p); logger.error("Reason:", reason, p);
}); });
@@ -932,16 +923,11 @@ process.on("uncaughtException", (err, origin) => {
logger.warn("Error:", err?.stack ?? err, origin); logger.warn("Error:", err?.stack ?? err, origin);
return; return;
} }
if (isAbortError(err)) {
logger.warn("[Error_Handling] Suppressed AbortError from a timed-out request.");
return;
}
logger.error("[Error_Handling] Uncaught Exception/Catch"); logger.error("[Error_Handling] Uncaught Exception/Catch");
logger.error("Error:", err, origin); logger.error("Error:", err, origin);
process.exit(1); process.exit(1);
}); });
process.on("uncaughtExceptionMonitor", (err, origin) => { process.on("uncaughtExceptionMonitor", (err, origin) => {
if (isAbortError(err)) return;
logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)"); logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)");
logger.error("Error:", err, origin); logger.error("Error:", err, origin);
}); });
+11 -9
View File
@@ -1255,18 +1255,15 @@ export class GatewayHandler {
`guild is 401-banned (${Math.round((banExpiry - Date.now()) / 1000)}s remaining).` `guild is 401-banned (${Math.round((banExpiry - Date.now()) / 1000)}s remaining).`
); );
// Remove the old player entry and destroy it // Remove the old player entry and destroy it
const bannedPlayer = remix.players.playerMap.get(cleanOld);
remix.players.playerMap.delete(cleanOld); remix.players.playerMap.delete(cleanOld);
try { bannedPlayer?.destroy(); } catch (_) {} try { remix.players.playerMap.get(cleanOld)?.destroy(); } catch (_) {}
return; return;
} }
// Match the specific player by channel ID // Match the specific player by channel ID
const player = remix.players.playerMap.get(cleanOld); const player = remix.players.playerMap.get(cleanOld);
if (player && !player.leaving) { if (player && !player.leaving) {
logger.voice247( logger.voice247("[247] Fluxer gateway disconnected us. Forcing player recovery...");
`[247] Fluxer gateway disconnected ${cleanOld} in guild ${guildId} — scheduling 24/7 respawn.`
);
// Set a gateway disconnect cooldown for this guild to // Set a gateway disconnect cooldown for this guild to
// prevent recovery cascades. If recovery rejoins and the // prevent recovery cascades. If recovery rejoins and the
@@ -1276,12 +1273,17 @@ export class GatewayHandler {
// Auto-clear the cooldown after 30 seconds // Auto-clear the cooldown after 30 seconds
setTimeout(() => this._gatewayDisconnectCooldown.delete(cleanGuild), 30_000); setTimeout(() => this._gatewayDisconnectCooldown.delete(cleanGuild), 30_000);
// Mark the disconnect reason before shutting the player down. // Mark the disconnect reason on the player for smarter recovery
player._lastDisconnectReason = "gateway"; player._lastDisconnectReason = "gateway";
player._lastDisconnectTime = Date.now(); player._lastDisconnectTime = Date.now();
remix.players.playerMap.delete(cleanOld);
try { player.destroy({ disconnect: false }); } catch (_) {} if (typeof player._recoverConnection === "function") {
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect"); player._recoverConnection();
} else {
remix.players.playerMap.delete(cleanOld);
try { player.destroy(); } catch (_) {}
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect");
}
} else { } else {
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect"); this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect");
} }
+3 -21
View File
@@ -864,29 +864,11 @@ export class LastFmManager {
try { try {
const pool = await this._getPool(); const pool = await this._getPool();
const [rows] = await pool.execute( const [rows] = await pool.execute(
"SELECT COUNT(*) AS total FROM lastfm_users" "SELECT linked_users FROM lastfm_stats WHERE id = 1"
); );
const count = Number(rows[0]?.total ?? 0); return Number(rows[0]?.linked_users ?? 0);
this._linkedUsersCache = count;
return count;
} catch { } catch {
return this._linkedUsersCache ?? 0; return 0;
}
}
async getStoredTotalScrobbles() {
if (!this.enabled) return 0;
try {
const pool = await this._getPool();
const [rows] = await pool.execute(
"SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users"
);
const total = Number(rows[0]?.total ?? this._totalScrobblesCache ?? 0);
this._totalScrobblesCache = total;
this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000;
return total;
} catch {
return this._totalScrobblesCache ?? 0;
} }
} }
+201 -48
View File
@@ -521,19 +521,191 @@ export default class Player extends EventEmitter {
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
async _recoverConnection() { async _recoverConnection() {
if (this._destroyed || this.leaving || this._recoveryPending) return; // bail immediately if the player has been destroyed or a recovery is
this._isRecovering = false; // already in-flight or scheduled (covers the gap between attempts).
if (this._isRecovering || this._recoveryPending || this._destroyed) return;
const targetChannelId = this._getRecoveryChannelId();
if (!targetChannelId) {
logger.warn(`[Player] Recovery aborted for guild ${this._guildId} - no channel target available.`);
this.emit("autoleave");
return;
}
// ── 401 Permission-based recovery guard ──────────────────────────────
// If the last disconnect was due to a 401 Unauthorized error, don't
// keep retrying — 401 is a permission problem, not a transient failure.
// Retrying just creates more 401 errors and recovery loops.
// Instead, give up on recovery and let the 24/7 system schedule a
// delayed respawn.
if (this._lastDisconnectReason === "401") {
const timeSinceDisconnect = Date.now() - this._lastDisconnectTime;
if (timeSinceDisconnect < 60_000) {
logger.warn(
`[Player] Skipping recovery for guild ${this._guildId} — ` +
`last disconnect was 401 Unauthorized (${timeSinceDisconnect / 1000}s ago). ` +
`Delegating to 24/7 respawn system.`
);
this._isRecovering = false;
this._recoveryPending = false;
this.emit("autoleave");
return;
}
// If more than 60s have passed since the 401, try again — permissions
// may have been restored.
logger.player(
`[Player] 401 was ${timeSinceDisconnect / 1000}s ago — retrying recovery ` +
`(permissions may have been restored).`
);
}
this._isRecovering = true;
this._recoveryPending = true; this._recoveryPending = true;
this._recoveryAttempts = 0;
if (this._recoveryTimer) { this._recoveryAttempts = (this._recoveryAttempts ?? 0) + 1;
clearTimeout(this._recoveryTimer); const MAX_RECOVERY = 5;
this._recoveryTimer = null; if (this._recoveryAttempts > MAX_RECOVERY) {
logger.error(`[Player] Recovery failed after ${MAX_RECOVERY} attempts for guild ${this._guildId} — giving up.`);
this._isRecovering = false;
this._recoveryPending = false;
this._recoveryAttempts = 0;
this.emit("autoleave");
return;
}
// Exponential backoff: 2s, 4s, 8s, 16s, 32s (was linear: 2s, 4s, 6s, 8s, 10s)
// If last disconnect was a gateway force-disconnect, use longer backoff
// to avoid the recovery cascade where rejoining causes another disconnect.
let backoffMs;
if (this._lastDisconnectReason === "gateway") {
// Gateway force-disconnects need longer recovery time to avoid cascading
backoffMs = Math.min(5000 * Math.pow(2, this._recoveryAttempts - 1), 60_000);
} else {
backoffMs = Math.min(2000 * Math.pow(2, this._recoveryAttempts - 1), 30_000);
}
logger.mediaplayer(`[Player] Recovery attempt ${this._recoveryAttempts}/${MAX_RECOVERY} for ${this._guildId} (backoff ${backoffMs}ms, reason: ${this._lastDisconnectReason ?? "unknown"})`);
await Utils.sleep(backoffMs);
// re-check after await — player may have been destroyed during backoff
if (this._destroyed) {
this._isRecovering = false;
return;
}
// Wait for _isJoining to clear — if another operation (e.g. spawnPlayer or
// a concurrent _recoverConnection from a different event path) is currently
// calling join(), we must not race against it. Poll every 500ms for up to
// 15s, then give up on this attempt and schedule a retry.
let waited = 0;
while (this._isJoining && waited < 15_000) {
logger.mediaplayer(`[Player] Waiting for _isJoining to clear before recovery attempt...`);
await Utils.sleep(500);
waited += 500;
}
if (this._isJoining) {
logger.warn("[Player] _isJoining still busy after 15s — deferring recovery attempt.");
this._isRecovering = false;
this._recoveryPending = false;
// Schedule a retry via setTimeout so we don't stack synchronous calls
this._recoveryTimer = setTimeout(() => {
this._recoveryTimer = null;
this._recoverConnection().catch(() => {});
}, 2000);
return;
}
logger.mediaplayer(`[Player] Attempting to recover voice connection for ${this._guildId}`);
try {
if (this.connection) {
// Clean up the old connection. FluxerVoiceConnection.disconnect()
// handles native @fluxerjs/voice disconnect + LiveKit room close.
// We also need to send a gateway leave signal so the gateway
// processes the leave before we attempt to rejoin.
try { await this.connection.disconnect(); } catch (_) {}
// Explicitly send a gateway leave signal via @fluxerjs/voice so
// the gateway knows the bot left the channel. Without this, the
// gateway may still think the bot is in the channel and won't
// send a fresh VOICE_SERVER_UPDATE on the next joinVoiceChannel().
try {
const vm = getVoiceManager(this.client);
if (vm && typeof vm.updateVoiceState === "function") {
// IMPORTANT: Always use guild-scoped leave. An unscoped
// updateVoiceState(null, opts) disconnects ALL guilds' voice
// connections, causing cascading failures.
const guildIdForLeave = this._guildId ?? this._resolveGuildId();
if (guildIdForLeave) {
try {
vm.updateVoiceState(guildIdForLeave, null, { self_deaf: false, self_mute: false });
} catch (e1) {
// Older @fluxerjs/voice may not accept 3-arg form
try { vm.updateVoiceState(guildIdForLeave, null); } catch (e2) {}
}
logger.mediaplayer(`[Player] Sent guild-scoped gateway leave signal for guild ${guildIdForLeave} before recovery rejoin`);
} else {
logger.warn(`[Player] Cannot send guild-scoped leave — no guildId available. Skipping to avoid disconnecting all guilds.`);
}
}
} catch (e) {
logger.warn(`[Player] Gateway leave signal failed: ${e?.message}`);
}
// Also remove the stale connection from FluxerRevoice's map
// so the next _revoice.join() doesn't return the dead connection.
if (this._revoice && this._channelId) {
try { this._revoice.deleteConnection(this._channelId); } catch (_) {}
}
}
await Utils.sleep(3000);
if (this.leaving || this._destroyed) return;
logger.mediaplayer(`[Player] Rejoining channel ${targetChannelId}`);
await this.join(targetChannelId);
// Do NOT re-read room.isConnected/room.connectionState here —
// join() already awaited ConnectionStateChanged and only resolved when
// the room was truly connected, so reaching this line means success.
// The old check using room.state (which doesn't exist in @livekit/rtc-node)
// always threw "unexpected state: undefined" and emitted autoleave,
// causing the infinite reconnect storm in the logs.
this._isRecovering = false;
this._recoveryPending = false;
this._recoveryAttempts = 0;
if (this._recoveryTimer) {
clearTimeout(this._recoveryTimer);
this._recoveryTimer = null;
}
// Keep _home247Channel in sync with the channel we successfully recovered to.
if (this._channelId) this._home247Channel = this._channelId;
const current = this.queue.getCurrent();
if (current) {
logger.player(`[Player] Resuming track after recovery: ${current.title}`);
this.queue.data.unshift(current);
this.queue.current = null;
this._playingNext = false;
await this.playNext();
} else if (!this.queue.isEmpty()) {
this._playingNext = false;
await this.playNext();
}
} catch (e) {
logger.error("[Player] Recovery failed:", e.message);
this._isRecovering = false;
// _recoveryPending stays true during the retry delay to block duplicate
// calls from stacking up (e.g. two rapid disconnect events).
if (!this._destroyed && !this.leaving) {
const delay = Math.min(2000 * (this._recoveryAttempts ?? 1), 30_000);
if (this._recoveryTimer) clearTimeout(this._recoveryTimer);
this._recoveryTimer = setTimeout(() => {
this._recoveryTimer = null;
this._recoveryPending = false;
if (!this._destroyed && !this.leaving) this._recoverConnection();
}, delay);
} else {
this._recoveryPending = false;
}
} }
logger.warn(
`[Player] Voice connection lost for guild ${this._guildId} ` +
`(reason: ${this._lastDisconnectReason ?? "unknown"}). Recovery is disabled; leaving player stopped.`
);
this.emit("autoleave");
} }
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
@@ -1190,7 +1362,7 @@ export default class Player extends EventEmitter {
settled = true; settled = true;
resolve(); resolve();
} }
}, 1_200); }, 3_000);
const onStateChange = (cs) => { const onStateChange = (cs) => {
if (settled) return; if (settled) return;
@@ -1219,7 +1391,7 @@ export default class Player extends EventEmitter {
cleanup(); cleanup();
reject(new Error(`LiveKit disconnected (connectionState: ${room.connectionState})`)); reject(new Error(`LiveKit disconnected (connectionState: ${room.connectionState})`));
} }
}, 150); }, 500);
// Immediate check using correct API // Immediate check using correct API
if (room.isConnected) { if (room.isConnected) {
@@ -1302,8 +1474,8 @@ export default class Player extends EventEmitter {
const playerReady = await this._ensureMediaPlayer(); const playerReady = await this._ensureMediaPlayer();
if (!playerReady) { if (!playerReady) {
logger.mediaplayer("[Player] First MediaPlayer attempt failed, retrying after short delay..."); logger.mediaplayer("[Player] First MediaPlayer attempt failed, retrying after delay...");
await Utils.sleep(750); await Utils.sleep(3000);
if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry"); if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry");
const roomAlive = this.connection?.room?.isConnected ?? false; const roomAlive = this.connection?.room?.isConnected ?? false;
if (!roomAlive) { if (!roomAlive) {
@@ -1332,22 +1504,10 @@ export default class Player extends EventEmitter {
} catch (e) { } catch (e) {
const causeStr = e.cause ? ` (Cause: ${e.cause})` : ""; const causeStr = e.cause ? ` (Cause: ${e.cause})` : "";
const joinMsg = String(e?.message ?? e ?? ""); logger.error("[Player] Join failed:", e.message, causeStr);
const isPermissionJoinFailure =
joinMsg.includes("401") ||
joinMsg.includes("Unauthorized") ||
joinMsg.includes("no permissions to access the room") ||
joinMsg.includes("signal failure: client error") ||
joinMsg.includes("active 401 cooldown");
if (isPermissionJoinFailure) {
logger.warn(`[Player] Join blocked for ${channelId}: ${joinMsg}`);
} else {
logger.error("[Player] Join failed:", joinMsg, causeStr);
}
// Track the disconnect reason for smarter recovery decisions // Track the disconnect reason for smarter recovery decisions
if (joinMsg.includes("401") || joinMsg.includes("Unauthorized")) { if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
this._lastDisconnectReason = "401"; this._lastDisconnectReason = "401";
this._lastDisconnectTime = Date.now(); this._lastDisconnectTime = Date.now();
} }
@@ -1364,7 +1524,6 @@ export default class Player extends EventEmitter {
async leave() { async leave() {
if (!this.connection) return false; if (!this.connection) return false;
let leftCleanly = false;
try { try {
this.leaving = true; this.leaving = true;
this._stopInactivityTimer(); this._stopInactivityTimer();
@@ -1394,27 +1553,23 @@ export default class Player extends EventEmitter {
} }
await this.connection.leave(); await this.connection.leave();
leftCleanly = true;
} catch (e) {
logger.warn("[Player] leave warning:", e.message);
try {
await this.connection?.disconnect?.();
} catch (_) {}
} finally {
this.queue.reset(); this.queue.reset();
this.connection = null; this.connection = null;
this._paused = false; this._paused = false;
this._pausedAt = null; this._pausedAt = null;
this._playingNext = false; this._playingNext = false;
this.leaving = false; this.leaving = false;
} catch (e) {
logger.error("[Player] leave error:", e.message);
return false;
} }
if (leftCleanly) this.emit("leave"); this.emit("leave");
return leftCleanly; return true;
} }
destroy(options = {}) { destroy() {
if (this._destroyed) return; if (this._destroyed) return;
const skipDisconnect = options?.disconnect === false;
this._destroyed = true; this._destroyed = true;
try { try {
@@ -1446,13 +1601,11 @@ export default class Player extends EventEmitter {
this._stopMediaPlayer().catch(() => {}).then(() => { this._stopMediaPlayer().catch(() => {}).then(() => {
if (connToDestroy) { if (connToDestroy) {
try { connToDestroy.removeAllListeners?.(); } catch (_) {} try { connToDestroy.removeAllListeners?.(); } catch (_) {}
if (!skipDisconnect) { const disconnectPromise = connToDestroy.disconnect?.();
const disconnectPromise = connToDestroy.disconnect?.(); if (disconnectPromise instanceof Promise) {
if (disconnectPromise instanceof Promise) { disconnectPromise.catch((err) => {
disconnectPromise.catch((err) => { logger.error("[Player] Deferred disconnect failed:", err.message);
logger.error("[Player] Deferred disconnect failed:", err.message); });
});
}
} }
} }
}); });
+41 -118
View File
@@ -350,78 +350,6 @@ export class PlayerManager {
return this.locale.translate(guildId, key, replacements); return this.locale.translate(guildId, key, replacements);
} }
findPlayerEntryByChannelId(channelId) {
const cleanChannelId = cleanId(channelId);
if (!cleanChannelId) return null;
const direct = this.playerMap.get(cleanChannelId);
if (direct) return { mapKey: cleanChannelId, player: direct };
for (const [mapKey, player] of this.playerMap.entries()) {
const activeChannelId = getPlayerChannelId(player, mapKey);
const homeChannelId = cleanId(player?._home247Channel);
if (activeChannelId === cleanChannelId || homeChannelId === cleanChannelId) {
return { mapKey: cleanId(mapKey), player };
}
}
return null;
}
findGuildPlayers(guildId) {
const cleanGuildId = cleanId(guildId);
if (!cleanGuildId) return [];
return [...this.playerMap.entries()].filter(([mapKey, player]) => {
if (!player || player._destroyed) return false;
const fallbackChannel = this.commands.client?.channels?.get?.(cleanId(mapKey)) ?? null;
return getPlayerGuildId(player, fallbackChannel) === cleanGuildId;
});
}
detachPlayer(player, fallbackChannelId = null) {
const activeChannelId = getPlayerChannelId(player, fallbackChannelId) || cleanId(fallbackChannelId);
const homeChannelId = cleanId(player?._home247Channel) || activeChannelId;
const keysToRemove = [...new Set([
cleanId(fallbackChannelId),
activeChannelId,
homeChannelId,
].filter(Boolean))];
for (const key of keysToRemove) {
this.playerMap.delete(key);
const pendingScrobble = this._pendingScrobbleTimers.get(key);
if (pendingScrobble) {
clearTimeout(pendingScrobble.timer);
this._pendingScrobbleTimers.delete(key);
}
}
return { activeChannelId, homeChannelId, removedKeys: keysToRemove };
}
schedule247Respawns(guildId, channelIds, opts = {}) {
if (typeof this.spawnPlayer !== "function") return;
const cleanGuildId = cleanId(guildId);
const uniqueChannels = [...new Set((channelIds ?? []).map(cleanId).filter(Boolean))];
if (!cleanGuildId || uniqueChannels.length === 0) return;
const baseDelay = Math.max(0, Number(opts.baseDelay ?? this.timers?.leave247RejoinDelay ?? 5_000));
const stagger = Math.max(0, Number(opts.stagger ?? this.timers?.rejoin247Delay ?? 3_000));
const source = opts.source ?? "247";
uniqueChannels.forEach((channelId, index) => {
const delay = baseDelay + (index * stagger);
logger.recovery(`[${source}] Scheduling 24/7 respawn for ${channelId} in ${delay}ms`);
setTimeout(() => {
this.spawnPlayer(cleanGuildId, channelId).catch((err) => {
logger.warn(`[${source}] 24/7 respawn failed for ${channelId}:`, err?.message ?? err);
});
}, delay);
});
}
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
// Voice Channel Detection // Voice Channel Detection
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
@@ -444,16 +372,18 @@ export class PlayerManager {
const seedObserved = (channelId) => { const seedObserved = (channelId) => {
const cleanChannelId = cleanId(channelId); const cleanChannelId = cleanId(channelId);
if (!cleanChannelId) return null; if (!cleanChannelId) return null;
const current = this.observedVoiceUsers?.get?.(userId) ?? null; if (!this.observedVoiceUsers?.has(userId)) {
if (
cleanId(current?.guildId) !== cleanGuild ||
cleanId(current?.channelId) !== cleanChannelId
) {
this.observedVoiceUsers?.set(userId, { channelId: cleanChannelId, guildId: cleanGuild }); this.observedVoiceUsers?.set(userId, { channelId: cleanChannelId, guildId: cleanGuild });
} }
return cleanChannelId; return cleanId(this.observedVoiceUsers?.get(userId)?.channelId) || cleanChannelId;
}; };
const observed = this.observedVoiceUsers?.get?.(userId);
if (cleanId(observed?.guildId) === cleanGuild) {
const observedChannelId = cleanId(observed?.channelId);
if (observedChannelId) return observedChannelId;
}
try { try {
const vm = getVoiceManager(this.commands.client); const vm = getVoiceManager(this.commands.client);
const voiceChannelId = vm?.getVoiceChannelId?.(guildId, userId); const voiceChannelId = vm?.getVoiceChannelId?.(guildId, userId);
@@ -549,13 +479,6 @@ export class PlayerManager {
} catch (_) {} } catch (_) {}
} }
} }
const observed = this.observedVoiceUsers?.get?.(userId);
if (cleanId(observed?.guildId) === cleanGuild) {
const observedChannelId = cleanId(observed?.channelId);
if (observedChannelId) return observedChannelId;
}
return null; return null;
} }
@@ -596,12 +519,7 @@ export class PlayerManager {
} }
// Also check if a join is in-progress for this channel // Also check if a join is in-progress for this channel
if (this._pendingJoins.has(cleanUserChannelId)) { if (this._pendingJoins.has(cleanUserChannelId)) {
const pendingPlayer = await this._waitForPendingJoin(cleanUserChannelId); return null; // A player is being created — caller should retry
if (pendingPlayer) {
pendingPlayer.textChannel = message.channel;
return pendingPlayer;
}
return null;
} }
} }
@@ -674,22 +592,6 @@ export class PlayerManager {
return null; return null;
} }
async _waitForPendingJoin(channelId, timeoutMs = 5_000) {
const cleanChannelId = cleanId(channelId);
const startedAt = Date.now();
while (this._pendingJoins.has(cleanChannelId) && (Date.now() - startedAt) < timeoutMs) {
const player = this.playerMap.get(cleanChannelId)
?? [...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId);
if (player) return player;
await new Promise((resolve) => setTimeout(resolve, 100));
}
return this.playerMap.get(cleanChannelId)
?? [...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId)
?? null;
}
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
// Channel Selection Prompt // Channel Selection Prompt
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
@@ -796,19 +698,28 @@ export class PlayerManager {
if (!cid) { if (!cid) {
const guildId = getMessageGuildId(msg); const guildId = getMessageGuildId(msg);
if (guildId) { if (guildId) {
const matchedEntry = this.findGuildPlayers(guildId)[0] ?? null; const matchedEntry = [...this.playerMap.entries()].find(([, player]) =>
getPlayerGuildId(player) === cleanId(guildId)
);
cid = getPlayerChannelId(matchedEntry?.[1], matchedEntry?.[0]) || matchedEntry?.[0] || null; cid = getPlayerChannelId(matchedEntry?.[1], matchedEntry?.[0]) || matchedEntry?.[0] || null;
} }
} }
const cleanChannelId = cleanId(cid); const cleanChannelId = cleanId(cid);
const playerEntry = cleanChannelId ? this.findPlayerEntryByChannelId(cleanChannelId) : null; const player = cleanChannelId
const player = playerEntry?.player ?? null; ? this.playerMap.get(cleanChannelId) ??
[...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId)
: null;
if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice"))); if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice")));
this.detachPlayer(player, cleanChannelId); const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
this.playerMap.delete(activeChannelId);
// Clean up pending scrobble timer
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft"))); await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
await player.leave().catch(() => {}); await player.leave();
player.destroy(); player.destroy();
} }
@@ -869,7 +780,8 @@ export class PlayerManager {
}); });
player.on("autoleave", () => { player.on("autoleave", () => {
const { activeChannelId, homeChannelId } = this.detachPlayer(player, cleanChannelId); const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
const ch = player.textChannel; const ch = player.textChannel;
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 }));
@@ -895,15 +807,26 @@ export class PlayerManager {
? get247ChannelMode(this.settings.getServer(guildId), matchChannel) ? get247ChannelMode(this.settings.getServer(guildId), matchChannel)
: "off"; : "off";
// Remove player from map and destroy
this.playerMap.delete(activeChannelId);
// Clean up pending scrobble timer
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
if (homeChannelId !== activeChannelId) this.playerMap.delete(homeChannelId);
player.destroy(); player.destroy();
if (isIn247List && (mode247 === "on" || mode247 === "auto")) { if (isIn247List && (mode247 === "on" || mode247 === "auto")) {
// 24/7 is active — rejoin after a short delay (same as RecoveryManager.spawnPlayer autoleave)
const delay = this.timers?.rejoin247Delay ?? 3000; const delay = this.timers?.rejoin247Delay ?? 3000;
this.schedule247Respawns(guildId, [homeChannelId], { if (this.spawnPlayer) {
baseDelay: delay, logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} (mode ${mode247}) in ${delay}ms`);
stagger: 0, setTimeout(() => {
source: "AutoLeave", this.spawnPlayer(guildId, homeChannelId).catch(e =>
}); logger.warn("[AutoLeave] 24/7 rejoin failed for", homeChannelId, e.message)
);
}, delay);
}
} else { } else {
// Not 24/7 — send inactivity message // Not 24/7 — send inactivity message
const prefix = (() => { const prefix = (() => {
+78 -112
View File
@@ -5,15 +5,17 @@ import Player from "./Player.mjs";
import { get247ChannelMode } from "./constants/Helpers247.mjs"; import { get247ChannelMode } from "./constants/Helpers247.mjs";
/** /**
* RecoveryManager — handles player spawning without background recovery loops. * RecoveryManager — handles 24/7 auto-join on boot and player spawning.
* *
* The boot-time recovery system (session persistence via recovery.json) has * The boot-time recovery system (session persistence via recovery.json) has
* been removed. On restart the bot starts clean; only 24/7 channels configured * been removed. On restart the bot starts clean; only 24/7 channels configured
* in each guild's settings are automatically rejoined. * in each guild's settings are automatically rejoined.
* *
* This module still provides: * This module still provides:
* - spawnPlayer() — create a Player and join a voice channel when explicitly requested * - spawnPlayer() — create a Player, join a voice channel (used by 24/7)
* - scheduleSpawn() — delayed player spawn (used by 24/7 autoleave rejoin)
* - cleanStaleGuild() — purge all state for a guild the bot left * - cleanStaleGuild() — purge all state for a guild the bot left
* - tryAutoJoin() — auto-join 24/7 channels when bot + settings are ready
*/ */
export class RecoveryManager { export class RecoveryManager {
/** /**
@@ -28,7 +30,6 @@ export class RecoveryManager {
aloneCheckInterval: timers.aloneCheckInterval ?? 30_000, aloneCheckInterval: timers.aloneCheckInterval ?? 30_000,
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
rejoin247Delay: timers.rejoin247Delay ?? 3_000, rejoin247Delay: timers.rejoin247Delay ?? 3_000,
startupGuildGrace: timers.startupGuildGrace ?? 45_000,
}; };
// ── Internal state ──────────────────────────────────────────────────────── // ── Internal state ────────────────────────────────────────────────────────
@@ -40,7 +41,6 @@ export class RecoveryManager {
// ── Ready flags ─────────────────────────────────────────────────────────── // ── Ready flags ───────────────────────────────────────────────────────────
this.botReady = false; this.botReady = false;
this.settingsReady = false; this.settingsReady = false;
this._botReadyAt = 0;
// ── Auto-join guard ─────────────────────────────────────────────────────── // ── Auto-join guard ───────────────────────────────────────────────────────
this._autoJoinRunning = false; this._autoJoinRunning = false;
@@ -54,7 +54,6 @@ export class RecoveryManager {
/** @type {Map<string, number>} Guild ID → consecutive 401 retry count. /** @type {Map<string, number>} Guild ID → consecutive 401 retry count.
* Used for exponential backoff: 1st retry after 15s, 2nd after 45s, 3rd = ban. */ * Used for exponential backoff: 1st retry after 15s, 2nd after 45s, 3rd = ban. */
this._guild401Retries = new Map(); this._guild401Retries = new Map();
this._spawnQueue = Promise.resolve();
// ── Expose convenience methods on the Remix instance ────────────────────── // ── Expose convenience methods on the Remix instance ──────────────────────
remix._spawnPlayer = this.spawnPlayer.bind(this); remix._spawnPlayer = this.spawnPlayer.bind(this);
@@ -69,78 +68,6 @@ export class RecoveryManager {
return String(value ?? "").replace(/\D/g, ""); return String(value ?? "").replace(/\D/g, "");
} }
_inStartupGuildGrace() {
return this._botReadyAt > 0 && (Date.now() - this._botReadyAt) < this.T.startupGuildGrace;
}
_isGuildAvailable(guildId) {
const { remix } = this;
const cleanGuildId = String(guildId).replace(/\D/g, "");
return remix.client.guilds.has(guildId) || remix.client.guilds.has(cleanGuildId);
}
_enqueueSpawn(guildId, channelId, reason = "spawn") {
const cleanChannelId = this.normalizeChannelId(channelId);
if (!cleanChannelId) return Promise.resolve();
const run = async () => {
try {
await this.spawnPlayer(guildId, cleanChannelId);
} catch (e) {
logger.warn(`[PlayerSpawn] Scheduled ${reason} failed for ${cleanChannelId}:`, e?.message ?? e);
}
};
const queued = this._spawnQueue.then(run, run);
this._spawnQueue = queued.catch(() => {});
return queued;
}
_disable247Channel(guildId, channelId, reason = "disabled") {
const { remix } = this;
const cleanGuildId = String(guildId).replace(/\D/g, "");
const cleanChannelId = this.normalizeChannelId(channelId);
if (!cleanGuildId || !cleanChannelId) return false;
const set = remix.settingsMgr.getServer(guildId) ?? remix.settingsMgr.getServer(cleanGuildId);
if (!set) return false;
const raw = set.get("stay_247");
if (!raw || raw === "none") return false;
const channels = Array.isArray(raw)
? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)
: [String(raw).replace(/\D/g, "")].filter(Boolean);
const nextChannels = channels.filter(id => id !== cleanChannelId);
const changed = nextChannels.length !== channels.length;
if (!changed) return false;
set.set("stay_247", nextChannels.length > 0 ? nextChannels : "none");
const modes = set.get("stay_247_modes");
if (modes && typeof modes === "object" && !Array.isArray(modes)) {
delete modes[cleanChannelId];
set.set("stay_247_modes", modes);
}
if (nextChannels.length === 0) {
set.set("stay_247_mode", "off");
} else {
const first = nextChannels[0];
const nextMode = (modes && typeof modes === "object" && !Array.isArray(modes))
? (modes[first] ?? "auto")
: "auto";
set.set("stay_247_mode", nextMode);
}
logger.warn(
`[247] Removed channel ${cleanChannelId} from stay_247 in guild ${cleanGuildId} (${reason}).`
);
return true;
}
/** /**
* Clean up all state for a guild the bot is no longer a member of. * Clean up all state for a guild the bot is no longer a member of.
* *
@@ -202,7 +129,9 @@ export class RecoveryManager {
const timer = setTimeout(() => { const timer = setTimeout(() => {
this.scheduledSpawns.delete(cleanChannelId); this.scheduledSpawns.delete(cleanChannelId);
this._enqueueSpawn(guildId, cleanChannelId, reason); this.spawnPlayer(guildId, cleanChannelId).catch(e => {
logger.warn(`[PlayerSpawn] Scheduled ${reason} failed for ${cleanChannelId}:`, e?.message ?? e);
});
}, Math.max(0, delayMs)); }, Math.max(0, delayMs));
this.scheduledSpawns.set(cleanChannelId, { timer, guildId, reason }); this.scheduledSpawns.set(cleanChannelId, { timer, guildId, reason });
@@ -237,9 +166,13 @@ export class RecoveryManager {
// messages. The GuildCreate handler will schedule the 24/7 spawn for // messages. The GuildCreate handler will schedule the 24/7 spawn for
// late-arriving guilds. cleanStaleGuild is only appropriate when we // late-arriving guilds. cleanStaleGuild is only appropriate when we
// know for sure the bot was kicked (i.e. a GuildDelete was received). // know for sure the bot was kicked (i.e. a GuildDelete was received).
if (!this._isGuildAvailable(guildId)) { if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGuildId)) {
if (this._autoJoinRunning || !this._autoJoinDone || this._inStartupGuildGrace()) { if (this._autoJoinRunning || !this._autoJoinDone) {
// Startup phase — guild cache not populated yet, just skip quietly. // Startup phase — guild cache not populated yet, just skip
logger.recovery(
`[PlayerSpawn] Skipping channel ${cleanChannelId} in guild ${cleanGuildId} — ` +
`guild cache not populated yet (startup race). GuildCreate will schedule spawn.`
);
} else { } else {
// Runtime — bot was actually removed from the guild // Runtime — bot was actually removed from the guild
logger.recovery( logger.recovery(
@@ -357,11 +290,8 @@ export class RecoveryManager {
// ── Autoleave handler ─────────────────────────────────────────────────── // ── Autoleave handler ───────────────────────────────────────────────────
p.on("autoleave", async () => { p.on("autoleave", async () => {
const { activeChannelId, homeChannelId } = remix.players.detachPlayer?.(p, cleanChannelId) const activeChannelId = String(p._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId;
?? { const homeChannelId = String(p._home247Channel ?? activeChannelId).replace(/\D/g, "") || activeChannelId;
activeChannelId: String(p._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId,
homeChannelId: String(p._home247Channel ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId,
};
const raw2 = remix.settingsMgr.getServer(guildId).get("stay_247"); const raw2 = remix.settingsMgr.getServer(guildId).get("stay_247");
const channels2 = (!raw2 || raw2 === "none") const channels2 = (!raw2 || raw2 === "none")
@@ -378,15 +308,15 @@ export class RecoveryManager {
? get247ChannelMode(remix.settingsMgr.getServer(guildId), matchChannel) ? get247ChannelMode(remix.settingsMgr.getServer(guildId), matchChannel)
: "off"; : "off";
// Remove player from map and destroy it now that we've read the state.
remix.players.playerMap.delete(activeChannelId);
if (activeChannelId !== cleanChannelId) remix.players.playerMap.delete(cleanChannelId);
p.destroy(); p.destroy();
if (matchChannel && (mode2 === "on" || mode2 === "auto")) { if (matchChannel && (mode2 === "on" || mode2 === "auto")) {
remix.players.schedule247Respawns?.(guildId, [homeChannelId], { this.scheduleSpawn(guildId, homeChannelId, this.T.rejoin247Delay, "247-autoleave");
baseDelay: this.T.rejoin247Delay,
stagger: 0,
source: "247-autoleave",
});
} else { } else {
// 24/7 is off — send inactivity message with hint to enable 247
try { try {
const prefix = remix.handler?.getPrefix?.(guildId) ?? "%"; const prefix = remix.handler?.getPrefix?.(guildId) ?? "%";
const guild = remix.client.guilds.get(guildId); const guild = remix.client.guilds.get(guildId);
@@ -494,29 +424,62 @@ export class RecoveryManager {
logger.warn("[PlayerSpawn] Failed to join channel", cleanChannelId, "guild", guildId, e.message); logger.warn("[PlayerSpawn] Failed to join channel", cleanChannelId, "guild", guildId, e.message);
// ── 401 Unauthorized handling ───────────────────────────────────── // ── 401 Unauthorized handling ─────────────────────────────────────
const errMsg = String(e?.message ?? e ?? ""); const is401Error = /\b401\b/.test(e.message) ||
const isCooldownBlock = errMsg.includes("active 401 cooldown"); e.message?.includes("Unauthorized") ||
const is401Error = !isCooldownBlock && ( e.message?.includes("no permissions to access the room") ||
/\b401\b/.test(errMsg) || e.message?.includes("signal failure: client error");
errMsg.includes("Unauthorized") ||
errMsg.includes("no permissions to access the room") ||
errMsg.includes("signal failure: client error")
);
if (is401Error) { if (is401Error) {
this._disable247Channel(cleanGuildId, cleanChannelId, "401 room permission failure"); // Bot not in guild cache — but during startup, the cache might not
logger.warn( // be populated yet. Same race as the pre-flight check.
`[PlayerSpawn] 401 for guild ${cleanGuildId} on channel ${cleanChannelId}. ` + if (!remix.client.guilds.has(guildId) && !remix.client.guilds.has(cleanGuildId)) {
"Channel removed from 24/7 autojoin; leaving it disconnected until re-enabled manually." if (this._autoJoinRunning || !this._autoJoinDone) {
); logger.warn(
return; `[PlayerSpawn] 401 on guild ${guildId} — guild cache not populated yet (startup race). Will retry.`
} );
// Schedule a retry — don't clean up
const retryCount = (this._guild401Retries.get(cleanGuildId) ?? 0) + 1;
this._guild401Retries.set(cleanGuildId, retryCount);
if (retryCount < 3) {
this.scheduleSpawn(guildId, cleanChannelId, 15_000, `401-startup-retry-${retryCount}`);
}
return;
}
// Runtime — bot was actually removed
logger.warn(
`[PlayerSpawn] 401 on guild ${guildId} — bot no longer in server. Cleaning up.`
);
this.cleanStaleGuild(guildId, "401 and bot not in guild");
return;
}
if (isCooldownBlock) { // Bot IS still in the guild — the 401 may be transient (gateway slow
// to provision voice room). Retry with exponential backoff instead of
// permanently giving up on the first failure.
const retryCount = (this._guild401Retries.get(cleanGuildId) ?? 0) + 1;
this._guild401Retries.set(cleanGuildId, retryCount);
if (retryCount >= 3) {
// After 3 consecutive 401s, ban this guild for 5 minutes to avoid
// infinite retry loops. The FluxerRevoice 45s cooldown + this ban
// prevent wasting resources on guilds where voice is truly broken.
const banDuration = 5 * 60 * 1000; // 5 minutes
this._guild401Ban.set(cleanGuildId, Date.now() + banDuration);
this._guild401Retries.delete(cleanGuildId);
logger.warn(
`[PlayerSpawn] 401 for guild ${cleanGuildId} — ` +
`${retryCount} consecutive failures. Banning for 5 minutes.`
);
return;
}
// Exponential backoff: 1st retry after 15s, 2nd after 45s
const backoffMs = retryCount === 1 ? 15_000 : 45_000;
logger.warn( logger.warn(
`[PlayerSpawn] Cooldown blocked autojoin for channel ${cleanChannelId} in guild ${cleanGuildId}. ` + `[PlayerSpawn] 401 for guild ${cleanGuildId} — ` +
"Keeping 24/7 setting unchanged." `transient? Retry ${retryCount}/3 in ${backoffMs / 1000}s.`
); );
this.scheduleSpawn(guildId, cleanChannelId, backoffMs, `401-retry-${retryCount}`);
return; return;
} }
@@ -542,16 +505,14 @@ export class RecoveryManager {
async tryAutoJoin() { async tryAutoJoin() {
if (!this.botReady || !this.settingsReady) return; if (!this.botReady || !this.settingsReady) return;
if (this._autoJoinRunning || this._autoJoinDone) return; if (this._autoJoinRunning || this._autoJoinDone) return;
if (!this._botReadyAt) this._botReadyAt = Date.now();
this._autoJoinRunning = true; this._autoJoinRunning = true;
const { remix } = this; const { remix } = this;
const joinList = []; const joinList = [];
// Collect all 24/7 channels from loaded guild settings
for (const [guildId, serverSettings] of remix.settingsMgr.guilds) { for (const [guildId, serverSettings] of remix.settingsMgr.guilds) {
try { try {
if (!this._isGuildAvailable(guildId)) continue;
const raw = serverSettings.get("stay_247"); const raw = serverSettings.get("stay_247");
if (!raw || raw === "none") continue; if (!raw || raw === "none") continue;
@@ -573,6 +534,11 @@ export class RecoveryManager {
`[AutoJoin] Found ${joinList.length} 24/7 channel(s) to join.` `[AutoJoin] Found ${joinList.length} 24/7 channel(s) to join.`
); );
// Schedule all 24/7 spawns immediately (no stagger). The FluxerRevoice
// global join queue handles serialization — only one join is in-flight
// at a time across all guilds, with a 3s gap between each. Staggering
// here is no longer needed and just adds unnecessary delay before the
// joins start queuing.
for (let i = 0; i < joinList.length; i++) { for (let i = 0; i < joinList.length; i++) {
const { guildId, channelId } = joinList[i]; const { guildId, channelId } = joinList[i];
this.scheduleSpawn(guildId, channelId, 0, "247-autojoin"); this.scheduleSpawn(guildId, channelId, 0, "247-autojoin");
+14 -8
View File
@@ -194,9 +194,10 @@ export class FluxerRevoice extends EventEmitter {
/** @type {number} Minimum delay between ANY two joins (ms), even across guilds. /** @type {number} Minimum delay between ANY two joins (ms), even across guilds.
* This delay runs AFTER the previous join completes and BEFORE the next * This delay runs AFTER the previous join completes and BEFORE the next
* one starts, giving the Fluxer gateway time to clean up the previous * one starts, giving the Fluxer gateway time to clean up the previous
* voice session. Keep this short for snappy manual joins while still * voice session. 3 seconds is needed because the gateway's Erlang backend
* preserving serialization across the whole bot. */ * needs time to process the voice state transition before a new join
_globalJoinDelay = 1_000; * can succeed without 401 errors. */
_globalJoinDelay = 3_000;
/** @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();
@@ -210,9 +211,12 @@ export class FluxerRevoice extends EventEmitter {
/** @type {number} Minimum time between guild joins (ms) — enforced on top of /** @type {number} Minimum time between guild joins (ms) — enforced on top of
* the per-join delay. If a new join is requested within this window, we * the per-join delay. If a new join is requested within this window, we
* wait the remaining time before proceeding. Keep this lower than the old * wait the remaining time before proceeding. Increased from 7000 to 8000
* recovery-focused value so user-triggered joins don't feel sluggish. */ * because 7000ms was insufficient to prevent 401 errors when the bot
_guildMinJoinInterval = 3_000; * re-joins a channel in the same guild quickly after a disconnect,
* especially during boot recovery when multiple guilds compete for
* gateway attention. */
_guildMinJoinInterval = 8000;
/** @type {Map<string, number>} Guild IDs that recently had a 401 error. /** @type {Map<string, number>} Guild IDs that recently had a 401 error.
* Used to add an even longer backoff before retrying joins in that guild. */ * Used to add an even longer backoff before retrying joins in that guild. */
@@ -386,8 +390,10 @@ export class FluxerRevoice extends EventEmitter {
existing._connected = false; existing._connected = false;
try { existing.removeAllListeners(); } catch (_) {} try { existing.removeAllListeners(); } catch (_) {}
// Brief delay to let the gateway process the leave before we rejoin. // 4. Brief delay to let the gateway process the leave before we rejoin.
await new Promise(r => setTimeout(r, 750)); // Increased from 1500ms to 2000ms to give the Erlang gateway backend
// more time to clean up the previous voice session.
await new Promise(r => setTimeout(r, 2000));
} }
/** /**