This commit is contained in:
NoLogicAlan committed 2026-05-14 16:59:23 +03:00
1 parent a78edeaa9a
commit 4a62defe1b
6 files changed
+142 -171

No files matched your search

+1 -2
View File
@@ -28,8 +28,7 @@ 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.playerMap.get(cid) const p = this.players.findPlayerEntryByChannelId(cid)?.player ?? null;
?? [...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);
+25 -107
View File
@@ -1,5 +1,4 @@
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";
@@ -23,22 +22,6 @@ 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
@@ -49,15 +32,7 @@ export async function run(msg, data) {
?? msg.message?.serverId; ?? msg.message?.serverId;
const cleanGuildId = cleanId(guildId); const cleanGuildId = cleanId(guildId);
// Gather all active players in this guild. const guildPlayers = this.players.findGuildPlayers(cleanGuildId);
// 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
@@ -94,11 +69,8 @@ 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 player = this.players.playerMap.get(targetChannelId) const playerEntry = this.players.findPlayerEntryByChannelId(targetChannelId);
?? guildPlayers.find(([mapKey, p]) => const player = playerEntry?.player ?? null;
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
@@ -142,90 +114,36 @@ export async function run(msg, data) {
return mode === "auto"; return mode === "auto";
}); });
if (ch247.has(activeChannelId) || ch247.has(homeChannelId)) { const matchChannel = ch247.has(homeChannelId) ? homeChannelId
const matchChannel = ch247.has(homeChannelId) ? homeChannelId : ch247.has(activeChannelId) ? activeChannelId
: ch247.has(activeChannelId) ? activeChannelId : null;
: null; const mode = matchChannel ? get247ChannelMode(set, matchChannel) : "off";
const mode = matchChannel ? get247ChannelMode(set, matchChannel) : "off";
if (matchChannel) {
this.markIntentionalLeave(activeChannelId); this.markIntentionalLeave(activeChannelId);
this.players.playerMap.delete(activeChannelId); if (homeChannelId !== activeChannelId) this.markIntentionalLeave(homeChannelId);
if (activeChannelId !== targetChannelId) this.players.playerMap.delete(targetChannelId);
if (homeChannelId !== activeChannelId) this.players.playerMap.delete(homeChannelId); this.players.detachPlayer(player, targetChannelId);
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") ?? "%" })));
const leave247Delay = this.config?.timers?.leave247RejoinDelay ?? 5000; this.players.schedule247Respawns(guildId, [homeChannelId, ...other247AutoChannels], {
setTimeout(() => { baseDelay: respawnBaseDelay,
if (this._spawnPlayer) { stagger: respawnStagger,
this._spawnPlayer(guildId, homeChannelId).catch(e => source: "leave",
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, {
if (other247AutoChannels.length > 0) { baseDelay: respawnBaseDelay,
const rejoinDelay = this.config?.timers?.leave247RejoinDelay ?? 5000; stagger: respawnStagger,
const rejoinStagger = this.config?.timers?.rejoin247Delay ?? 3000; source: "leave",
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);
+13 -18
View File
@@ -721,10 +721,11 @@ 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.playerMap.delete(cleanId); this.players.detachPlayer?.(player, cleanId);
await player.leave().catch(() => {}); await player.leave().catch(() => {});
player.destroy(); player.destroy();
} }
@@ -742,28 +743,22 @@ 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;
for (let i = 0; i < other247AutoChannels.length; i++) { const channelsToRespawn = [];
const otherChannelId = other247AutoChannels[i]; for (const otherChannelId of other247AutoChannels) {
const otherPlayer = this.players.playerMap.get(otherChannelId); const otherPlayer = this.players.findPlayerEntryByChannelId?.(otherChannelId)?.player ?? null;
// Only rejoin if the player is gone (was collateral-disconnected)
if (!otherPlayer || otherPlayer._destroyed) { if (!otherPlayer || otherPlayer._destroyed) {
if (otherPlayer) { if (otherPlayer) {
this.players.playerMap.delete(otherChannelId); this.players.detachPlayer?.(otherPlayer, otherChannelId);
try { otherPlayer.destroy(); } catch (_) {} try { otherPlayer.destroy(); } catch (_) {}
} }
const delay = rejoinBaseDelay + (i + 1) * rejoinStagger; channelsToRespawn.push(otherChannelId);
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;
+10 -6
View File
@@ -1364,6 +1364,7 @@ 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();
@@ -1393,19 +1394,22 @@ 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;
} }
this.emit("leave"); if (leftCleanly) this.emit("leave");
return true; return leftCleanly;
} }
destroy() { destroy() {
+83 -32
View File
@@ -350,6 +350,78 @@ 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
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
@@ -724,28 +796,19 @@ export class PlayerManager {
if (!cid) { if (!cid) {
const guildId = getMessageGuildId(msg); const guildId = getMessageGuildId(msg);
if (guildId) { if (guildId) {
const matchedEntry = [...this.playerMap.entries()].find(([, player]) => const matchedEntry = this.findGuildPlayers(guildId)[0] ?? null;
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 player = cleanChannelId const playerEntry = cleanChannelId ? this.findPlayerEntryByChannelId(cleanChannelId) : null;
? this.playerMap.get(cleanChannelId) ?? const player = playerEntry?.player ?? null;
[...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")));
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; this.detachPlayer(player, 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(); await player.leave().catch(() => {});
player.destroy(); player.destroy();
} }
@@ -806,8 +869,7 @@ export class PlayerManager {
}); });
player.on("autoleave", () => { player.on("autoleave", () => {
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; const { activeChannelId, homeChannelId } = this.detachPlayer(player, 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 }));
@@ -833,26 +895,15 @@ 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;
if (this.spawnPlayer) { this.schedule247Respawns(guildId, [homeChannelId], {
logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} (mode ${mode247}) in ${delay}ms`); baseDelay: delay,
setTimeout(() => { stagger: 0,
this.spawnPlayer(guildId, homeChannelId).catch(e => source: "AutoLeave",
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 = (() => {
+10 -6
View File
@@ -357,8 +357,11 @@ export class RecoveryManager {
// ── Autoleave handler ─────────────────────────────────────────────────── // ── Autoleave handler ───────────────────────────────────────────────────
p.on("autoleave", async () => { p.on("autoleave", async () => {
const activeChannelId = String(p._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId; const { activeChannelId, homeChannelId } = remix.players.detachPlayer?.(p, 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")
@@ -375,13 +378,14 @@ 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")) {
this.scheduleSpawn(guildId, homeChannelId, this.T.rejoin247Delay, "247-autoleave"); remix.players.schedule247Respawns?.(guildId, [homeChannelId], {
baseDelay: this.T.rejoin247Delay,
stagger: 0,
source: "247-autoleave",
});
} else { } else {
try { try {
const prefix = remix.handler?.getPrefix?.(guildId) ?? "%"; const prefix = remix.handler?.getPrefix?.(guildId) ?? "%";