This commit is contained in:
NoLogicAlan committed 2026-05-12 23:18:42 +03:00
1 parent 4e1d23fd57
commit 0714d30a6f
5 files changed
+105 -94

No files matched your search

+10 -56
View File
@@ -52,6 +52,7 @@ let VALID_LOCALES = new Set(["en"]);
/** Volume constraints */
const VOLUME_MIN = 1;
const VOLUME_MAX = 200;
const MAX_247_CHANNELS = 10;
// ── Helpers ───────────────────────────────────────────────────────────────────
@@ -497,67 +498,20 @@ async function handle247(ctx, message, value) {
));
}
// Save the user's channel
// Save only the channel the user explicitly toggled.
// Multi-voice 24/7 should be opt-in per voice channel, not "whatever
// channels the bot currently happens to be in".
const id = cleanId(userChannelId);
const channels = get247Channels(set);
const cleanGuildId = cleanId(guildId);
if (!channels.has(id) && channels.size >= MAX_247_CHANNELS) {
return message.reply(embed(
`You can save up to ${MAX_247_CHANNELS} 24/7 voice channels in one server. ` +
`Use \`${set.get("prefix") ?? "%"}247 off\` in one of the saved channels first.`
));
}
channels.add(id);
set247ChannelMode(set, id, resolved);
// Also save ALL other channels the bot is already in within this guild.
// We check two sources: playerMap (active players) and guild voice states
// (raw connections that might not have a player object yet).
const botId = ctx.client?.user?.id ? cleanId(ctx.client.user.id) : null;
// Source 1: playerMap — channels with active Player objects
for (const [chId, player] of ctx.players.playerMap.entries()) {
if (!player || player._destroyed) continue;
const pGuildId = cleanId(player._guildId ?? "");
const pChannelId = cleanId(player._channelId ?? chId);
if (pGuildId === cleanGuildId && pChannelId && !channels.has(pChannelId)) {
channels.add(pChannelId);
set247ChannelMode(set, pChannelId, resolved);
}
}
// Source 2: guild voice_states — catches channels the bot is connected to
// even if the playerMap entry is missing or keyed differently.
try {
const guild = ctx.client?.guilds?.get?.(guildId)
?? ctx.client?.guilds?.get?.(cleanGuildId);
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
if (voiceStates && botId) {
const entries = Array.isArray(voiceStates)
? voiceStates
: typeof voiceStates.values === "function"
? [...voiceStates.values()]
: Object.values(voiceStates);
for (const state of entries) {
const stateUserId = cleanId(state?.userId ?? state?.user_id ?? state?.id);
const stateChannelId = cleanId(state?.channelId ?? state?.channel_id);
if (stateUserId === botId && stateChannelId && !channels.has(stateChannelId)) {
channels.add(stateChannelId);
set247ChannelMode(set, stateChannelId, resolved);
}
}
}
} catch (_) {}
// Source 3: observedVoiceBots — the bot's tracked voice connections
try {
if (ctx.observedVoiceBots && botId) {
for (const [, info] of ctx.observedVoiceBots) {
if (cleanId(info?.guildId) === cleanGuildId) {
const botChannelId = cleanId(info?.channelId);
if (botChannelId && !channels.has(botChannelId)) {
channels.add(botChannelId);
set247ChannelMode(set, botChannelId, resolved);
}
}
}
}
} catch (_) {}
save247Channels(set, channels);
const playerExists = ctx.players.playerMap.has(id) ||
+51
View File
@@ -974,8 +974,41 @@ export class GatewayHandler {
// multi-voice guilds, which broke recovery for all channels.
const cleanId = String(channelId).replace(/\D/g, "");
const cleanOld = String(oldChannelId).replace(/\D/g, "");
const moveSet = remix.settingsMgr.getServer(guildId);
const moveRaw = moveSet?.get("stay_247");
const saved247Channels = (!moveRaw || moveRaw === "none")
? []
: Array.isArray(moveRaw)
? moveRaw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)
: [String(moveRaw).replace(/\D/g, "")].filter(id => id.length >= 15);
if (saved247Channels.length > 1) {
logger.voice247(
`[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanId} ` +
`because guild ${guildId} already has multiple saved 24/7 channels ` +
`[${saved247Channels.join(", ")}]`
);
return;
}
const existingPlayer = remix.players.playerMap.get(cleanOld);
const newChannelAlreadySaved = (() => {
try {
const set = remix.settingsMgr.getServer(guildId);
const raw = set?.get("stay_247");
if (!raw || raw === "none") return false;
const saved = Array.isArray(raw)
? raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)
: [String(raw).replace(/\D/g, "")].filter(id => id.length >= 15);
return saved.includes(cleanId);
} catch (_) {
return false;
}
})();
const newChannelPendingSpawn =
this.recoveryManager?.pendingSpawns?.has?.(cleanId) ||
remix.players?._pendingJoins?.has?.(cleanId) ||
false;
const targetChannel = client.channels.get(cleanId)
?? client.channels.get?.(cleanId)
?? null;
@@ -988,6 +1021,17 @@ export class GatewayHandler {
let rekeyed = false;
if (existingPlayer && cleanId !== cleanOld) {
if (newChannelAlreadySaved || newChannelPendingSpawn) {
// Multi-voice case: joining/spawning another channel in the same
// guild can look like a move event for the bot user. In that
// situation we must NOT re-key the old player or rewrite stay_247,
// otherwise one saved channel gets collapsed into the newer one.
logger.voice247(
`[247] Keeping both channels ${cleanOld} and ${cleanId} ` +
`(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
);
rekeyed = false;
} else
if (guildIsAmbiguous) {
// Multi-voice guild: we need to re-key the playerMap so that
// lookups by the new channelId work. First check that no OTHER
@@ -1077,6 +1121,13 @@ export class GatewayHandler {
? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15))
: new Set();
if (channels.has(cleanOld) && cleanOld !== cleanId && cleanId.length >= 15) {
if (channels.has(cleanId) || newChannelAlreadySaved || newChannelPendingSpawn) {
logger.voice247(
`[247] Preserved stay_247 channels ${cleanOld} and ${cleanId} ` +
`(saved=${channels.has(cleanId) || newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
);
return;
}
// Replace the old channel with the new one in stay_247.
// Previously this kept BOTH channels, causing unbounded growth
// in the stay_247 list (e.g. guild 1480202154270605526 ended up
+9 -1
View File
@@ -500,7 +500,15 @@ export class Channel {
* @returns {Function}
*/
onMessageUser(callback, user) {
const oid = this.handler.observeUserMessagesChannel(user.id, this.channel, callback);
const resolvedUserId = user?.id
?? user?._id
?? user?.user?.id
?? null;
const resolvedChannel = this.channel ?? null;
if (!resolvedUserId || !resolvedChannel?.id) {
return () => {};
}
const oid = this.handler.observeUserMessagesChannel(resolvedUserId, resolvedChannel, callback);
return () => {
this.handler.unobserveUserMessagesChannel(oid);
};
+3 -2
View File
@@ -622,6 +622,7 @@ export class PlayerManager {
return new Promise(resolve => {
let unsubscribeReactions;
let unsubscribeMessages;
const promptUser = msg.author ?? msg.message?.author ?? null;
const cleanup = () => {
unsubscribeMessages?.();
@@ -646,7 +647,7 @@ export class PlayerManager {
const cid = channel._id ?? channel.id;
this.initPlayer(msg, cid, (p) => resolve(p));
},
msg.author
promptUser
);
}
@@ -667,7 +668,7 @@ export class PlayerManager {
clearTimeout(timeout);
cleanup();
this.initPlayer(m, channel, (p) => resolve(p));
}, msg.author);
}, promptUser);
});
}
+32 -35
View File
@@ -113,26 +113,30 @@ export class FluxerVoiceConnection extends EventEmitter {
// handler knows not to trigger recovery
if (this._voice && this.channelId) {
this._voice.markIntentionalDisconnect(this.channelId);
// Prefer a channel-scoped gateway leave before tearing down the room.
// The native disconnect path can be guild-scoped in some environments,
// which drops every voice connection in the guild.
const guildId = this._voice._resolveGuildForChannel?.(this.channelId) ?? null;
this._voice._leaveGateway?.(this.channelId, guildId);
}
this._destroyed = true;
this._connected = false;
// Method 1: Use @fluxerjs/voice native connection disconnect
if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
try {
await this._nativeConn.disconnect();
} catch (e) {
logger.warn("[FluxerVoiceConnection] Native disconnect error:", e?.message);
}
}
// Method 2: Close LiveKit Room directly as fallback
// Close the LiveKit room directly after sending the leave signal.
// This keeps the disconnect scoped to the target channel.
if (this.room) {
try {
await this.room.disconnect();
} catch (e) {
// Room may already be closed
}
} else if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
// Fallback only when no room object is available.
try {
await this._nativeConn.disconnect();
} catch (e) {
logger.warn("[FluxerVoiceConnection] Native disconnect error:", e?.message);
}
}
this.emit("disconnect");
@@ -363,9 +367,17 @@ export class FluxerRevoice extends EventEmitter {
this.connections.delete(channelId);
// Mark as intentional so the LiveKit disconnect handler doesn't trigger recovery
this.markIntentionalDisconnect(channelId);
const staleGuildId = this._resolveGuildForChannel(channelId);
this._leaveGateway(channelId, staleGuildId);
// 2. Disconnect the native @fluxerjs/voice connection (sends gateway leave)
if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") {
// 2. Close the LiveKit Room directly
if (existing.room) {
try {
await existing.room.disconnect();
} catch (_) {
// Room may already be closed
}
} else if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") {
try {
await existing._nativeConn.disconnect();
} catch (e) {
@@ -373,28 +385,12 @@ export class FluxerRevoice extends EventEmitter {
}
}
// 3. Close the LiveKit Room directly
if (existing.room) {
try {
await existing.room.disconnect();
} catch (_) {
// Room may already be closed
}
}
// 4. Mark as destroyed and clean up listeners
// 3. Mark as destroyed and clean up listeners
existing._destroyed = true;
existing._connected = false;
try { existing.removeAllListeners(); } catch (_) {}
// 5. Send an explicit gateway leave signal so the gateway knows we left.
// This is critical: if the gateway still thinks we're in the channel,
// the next joinVoiceChannel() won't receive VOICE_SERVER_UPDATE and
// the rejoin will fail.
const staleGuildId = this._resolveGuildForChannel(channelId);
this._leaveGateway(channelId, staleGuildId);
// 6. 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.
// 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));
@@ -687,16 +683,17 @@ export class FluxerRevoice extends EventEmitter {
// connection instead of returning this dead one.
this.connections.delete(channelId);
// Send gateway leave signal so the gateway knows we're gone.
// Without this, the gateway may still think the bot is in the channel
// and won't send a fresh VOICE_SERVER_UPDATE on rejoin.
if (!isIntentional) {
// Unexpected disconnects still need a gateway leave signal so the
// next join gets a fresh voice session.
this._leaveGateway(channelId, channelGuildId);
// Try to disconnect the native @fluxerjs/voice connection as well,
// in case it still has resources open.
// Best-effort cleanup for the native wrapper. Skip this on intentional
// leaves because it can collapse multi-voice into a guild-wide leave.
if (nativeConnection && typeof nativeConnection.disconnect === "function") {
try { nativeConnection.disconnect(); } catch (_) {}
}
}
connection.emit("disconnect");
});