hotfix(rollback to)

This commit is contained in:
NoLogicAlan committed 2026-05-14 21:47:41 +03:00
1 parent 7cf97b0aed
commit d92cfb6e28
4 files changed
+202 -215

No files matched your search

+57 -17
View File
@@ -1,12 +1,19 @@
{ {
"Comment": "Fluxer music bot configuration. IMPORTANT: Node.js >= 22.0.0 is required (moonlink.js v5 dependency). Run 'node --version' to verify.",
"token": "your bot token", "token": "your bot token",
"fluxer.js": { "fluxer.js": {
"rest": { "rest": {
"Comment": "REST client options. 'timeout' is ms before a request to api.fluxer.app is aborted (default: 15000). Raise if you see DOMException AbortError in logs.",
"timeout": 30000, "timeout": 30000,
"retries": 3 "retries": 3
} }
}, },
"fluxer-api": {
"Comment": "Configuration options for a fluxer REST client if self-hosting. See: https://docs.fluxer.app"
},
"prefix": "your desired prefix (such as %)", "prefix": "your desired prefix (such as %)",
"presenceInterval": null,
"presenceContents-Comment": "Each entry can be a plain string (e.g. 'Ping for Prefix') or an object. Objects support: text (required), emoji_name (unicode emoji or custom emoji name), emoji_id (snowflake ID for custom guild emojis only), activity ({ name, type, url? }). Activity types: 0=Playing, 1=Streaming, 2=Listening, 3=Watching, 5=Competing. For custom guild emojis, provide both emoji_name AND emoji_id. For unicode emojis, only emoji_name is needed.",
"presenceContents": [ "presenceContents": [
{ {
"text": "Ping for Prefix | Hosted by https://kyun.sh/", "text": "Ping for Prefix | Hosted by https://kyun.sh/",
@@ -18,9 +25,13 @@
"text": "Ping for Prefix", "text": "Ping for Prefix",
"emoji_name": "🎧", "emoji_name": "🎧",
"activity": { "name": "music", "type": 2 } "activity": { "name": "music", "type": 2 }
},
{
"text": "Ping for Prefix | By RedTech & NoLogicAlan",
"emoji_name": "🎶",
"activity": { "name": "RedTech & NoLogicAlan", "type": 2 }
} }
], ],
"presenceInterval": 30000,
"spotify": { "spotify": {
"clientId": "your spotify client id", "clientId": "your spotify client id",
"clientSecret": "your spotify client secret" "clientSecret": "your spotify client secret"
@@ -29,12 +40,34 @@
"host": "localhost", "host": "localhost",
"port": 3000, "port": 3000,
"password": "youshallnotpass", "password": "youshallnotpass",
"requestTimeout": 60000 "requestTimeout": 60000,
"Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors."
},
"comment-radio": {
"message": "If you have radio stations you'd like to connect, add them to the array below. Radio stations must be rendered like following:",
"station": {
"name": "zamrock",
"detailedName": "ᘔᗩᗰᘔᗩᗰᖴOᖴᒪIᖴE",
"thumbnail": "https://zamrock.net/wp-content/uploads/2024/06/Zamrock_rd_logo_0004-1.gif",
"url": "url to stream from; this will be kept private",
"description": "Genre: Zamrock, provided by [Zamrock.net](https://zamrock.net/)",
"author": {
"name": "Zamrock",
"url": "https://zamrock.net"
},
"keyWords": ["radio", "zamrock", "psychedelic", "blues", "rock"]
}
}, },
"radio": [], "radio": [],
"cache": { "cache": {
"guilds": { "enabled": true, "max": 5000 }, "guilds": {
"members": { "enabled": true, "max": 10000 } "enabled": true,
"max": 5000
},
"members": {
"enabled": true,
"max": 10000
}
}, },
"helpCatalog": true, "helpCatalog": true,
"helpPagination": true, "helpPagination": true,
@@ -48,7 +81,9 @@
"webPort": 80, "webPort": 80,
"dashboard": { "dashboard": {
"enabled": false, "enabled": false,
"redis": { "url": "redis://localhost:6379" } "redis": {
"url": "redis://localhost:6379"
}
}, },
"dashboardUrl": "The url the dashboard is accessible with.", "dashboardUrl": "The url the dashboard is accessible with.",
"ssl": { "ssl": {
@@ -57,43 +92,48 @@
"useSSL": false, "useSSL": false,
"httpPort": 80 "httpPort": 80
}, },
"sessionSecret": "secret for the expressjs session middleware", "sessionSecret": "secret for the expressjs session middleware; https://www.npmjs.com/package/express-session#user-content-secret",
"geniusToken": "Genius access token (optional, used for lyrics)", "geniusToken": "Genius access token (Used for lyrics); optional",
"lastfm": { "lastfm": {
"Comment": "Last.fm integration: auto-scrobble songs, play loved/top/recent tracks. Register at https://www.last.fm/api/account/create",
"apiKey": "your_lastfm_api_key", "apiKey": "your_lastfm_api_key",
"apiSecret": "your_lastfm_api_secret", "apiSecret": "your_lastfm_api_secret",
"scrobbleThreshold": 0.5, "scrobbleThreshold": 0.5,
"scrobbleMinMs": 240000 "scrobbleMinMs": 240000,
"Comment2": "scrobbleThreshold: fraction of track duration before scrobbling (0.5 = 50%). scrobbleMinMs: minimum ms played before scrobble (default 4 min). Both must be met."
}, },
"owners": ["user id for owner-only commands"], "owners": ["user id for owner-only commands", "another user id"],
"playerAFKTimeout": 60000,
"Comment": "The above specifies the time in ms after which a player goes inactive; Optional.",
"customStatsFooter": "Text shown in the footer of the %stats embed; optional.", "customStatsFooter": "Text shown in the footer of the %stats embed; optional.",
"embedColor": "0xe9196c", "embedColor": "0xe9196c",
"logging": { "logging": {
"Comment": "Control which log categories appear in the console. Set 'enabled' to false to silence everything except errors. Set any category to false to silence just that group.",
"enabled": true, "enabled": true,
"player": true, "player": true,
"inactivity": false, "inactivity": true,
"voice247": true,
"voiceState": false, "voiceState": false,
"mediaplayer": true, "voice247": true,
"mediaplayer": false,
"commands": true, "commands": true,
"guild": true, "guild": true,
"recovery": false, "recovery": false,
"settings": false, "settings": true,
"worker": false, "worker": false,
"moonlink": false, "moonlink": false,
"voice": false,
"dashboard": false, "dashboard": false,
"redis": false "redis": false
}, },
"timers": { "timers": {
"Comment": "All timing values in milliseconds (ms). 1000ms = 1 second, 60000ms = 1 minute.",
"inactivityTimeout": 180000, "inactivityTimeout": 180000,
"aloneCheckInterval": 30000, "aloneCheckInterval": 10000,
"aloneCheckDebounce": 500, "aloneCheckDebounce": 400,
"rejoin247Delay": 2000, "rejoin247Delay": 2000,
"leave247RejoinDelay": 3000, "leave247RejoinDelay": 3000,
"playerUpdateInterval": 5000, "playerUpdateInterval": 5000,
"searchSessionTimeout": 30000, "searchSessionTimeout": 30000,
"playerSessionTimeout": 300000, "playerSessionTimeout": 300000,
"intentionalLeaveTTL": 10000 "intentionalLeaveTTL": 8000
} }
} }
+84 -103
View File
@@ -2,7 +2,7 @@ import { Events, GatewayOpcodes } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice"; import { getVoiceManager } from "@fluxerjs/voice";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
import { ServerSettings } from "./Settings.mjs"; import { ServerSettings } from "./Settings.mjs";
import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs"; import { get247ChannelMode } from "./constants/Helpers247.mjs";
import mysql from "mysql2"; import mysql from "mysql2";
/** /**
@@ -23,7 +23,7 @@ export class GatewayHandler {
const timers = remix.config.timers ?? {}; const timers = remix.config.timers ?? {};
this.T = { this.T = {
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
rejoin247Delay: timers.rejoin247Delay ?? 2_000, rejoin247Delay: timers.rejoin247Delay ?? 3_000,
}; };
// ── Presence rotation config ───────────────────────────────────────────── // ── Presence rotation config ─────────────────────────────────────────────
@@ -57,7 +57,7 @@ export class GatewayHandler {
/** @type {Map<string, {guild, timer}>} guildId → deferred cleanup data */ /** @type {Map<string, {guild, timer}>} guildId → deferred cleanup data */
this._deferredGuildDeletes = new Map(); this._deferredGuildDeletes = new Map();
/** @type {number} How long to defer GuildDelete processing during startup (ms) */ /** @type {number} How long to defer GuildDelete processing during startup (ms) */
this._startupDeleteGraceMs = 10_000; this._startupDeleteGraceMs = 15_000;
/** @type {boolean} Whether we're still in the startup grace period */ /** @type {boolean} Whether we're still in the startup grace period */
this._inStartupGrace = true; this._inStartupGrace = true;
} }
@@ -587,7 +587,10 @@ export class GatewayHandler {
if (deferred) { if (deferred) {
clearTimeout(deferred.timer); clearTimeout(deferred.timer);
this._deferredGuildDeletes.delete(guildId); this._deferredGuildDeletes.delete(guildId);
// Silently cancel — no need to log every guild that comes back during startup logger.guild(
`[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` +
`guild came back (GuildCreate received during grace period).`
);
} }
// Part 1: Voice state population // Part 1: Voice state population
@@ -716,12 +719,18 @@ export class GatewayHandler {
// come back via GUILD_CREATE moments later. Defer cleanup during // come back via GUILD_CREATE moments later. Defer cleanup during
// the startup grace period; if GuildCreate arrives first, cancel. // the startup grace period; if GuildCreate arrives first, cancel.
if (this._inStartupGrace) { if (this._inStartupGrace) {
// Silently buffer — log one summary after all deferrals are collected logger.guild(
`[GuildDelete] Deferring cleanup for server ${guildId} ` +
`(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).`
);
// Cancel any existing deferred timer for this guild
const existing = this._deferredGuildDeletes.get(guildId); const existing = this._deferredGuildDeletes.get(guildId);
if (existing) clearTimeout(existing.timer); if (existing) clearTimeout(existing.timer);
const timer = setTimeout(() => { const timer = setTimeout(() => {
this._deferredGuildDeletes.delete(guildId); this._deferredGuildDeletes.delete(guildId);
// Grace period expired without GuildCreate — this guild is really gone
logger.guild(`[GuildDelete] Confirmed removal from server ${guildId} — cleaning up.`);
this._processGuildDelete(guildId); this._processGuildDelete(guildId);
}, this._startupDeleteGraceMs); }, this._startupDeleteGraceMs);
@@ -1088,17 +1097,45 @@ export class GatewayHandler {
} }
} }
// Bot disconnected unexpectedly — emit autoleave on the player // Bot disconnected unexpectedly — check 24/7 before destroying player
if (!channelId && oldChannelId && guildId) { if (!channelId && oldChannelId && guildId) {
try { try {
const cleanOld = String(oldChannelId).replace(/\D/g, ""); const cleanOld = String(oldChannelId).replace(/\D/g, "");
const cleanGuild = String(guildId).replace(/\D/g, "");
if (remix.intentionalLeaves.has(cleanOld)) { if (remix.intentionalLeaves.has(cleanOld)) {
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`); logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`);
} else { } else {
const player = remix.players.playerMap.get(cleanOld); const player = remix.players.playerMap.get(cleanOld);
if (player && !player.leaving && !player._destroyed) { if (player && !player.leaving && !player._destroyed) {
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — emitting autoleave.`); // ── 24/7 channel protection ────────────────────────────────────
player.emit("autoleave"); // If this channel has 24/7 enabled (mode "on" or "auto"), the
// gateway may have sent a spurious VOICE_STATE_UPDATE with
// channel_id=null when the bot joined a channel in another guild.
// Instead of destroying the player, schedule a rejoin so the bot
// stays in the 24/7 channel.
const is247 = player._is247Enabled?.();
if (is247) {
logger.voice247(
`[VoiceState] Bot unexpectedly disconnected from 24/7 channel ${cleanOld} ` +
`(guild ${cleanGuild}) — scheduling rejoin instead of autoleave.`
);
// Clean up the dead player/connection first
remix.players.playerMap.delete(cleanOld);
try { player.destroy(); } catch (_) {}
// Schedule a rejoin after a short delay
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
setTimeout(() => {
if (remix._spawnPlayer) {
logger.voice247(`[VoiceState] Rejoining 24/7 channel ${cleanOld} after unexpected disconnect`);
remix._spawnPlayer(cleanGuild, cleanOld).catch(e =>
logger.warn(`[VoiceState] 24/7 rejoin failed for ${cleanOld}:`, e.message)
);
}
}, rejoinDelay);
} else {
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — emitting autoleave.`);
player.emit("autoleave");
}
} }
} }
} catch (e) { } catch (e) {
@@ -1121,26 +1158,25 @@ export class GatewayHandler {
// End the startup grace period after the configured delay. // End the startup grace period after the configured delay.
// Any deferred GuildDelete events that weren't cancelled by a GuildCreate // Any deferred GuildDelete events that weren't cancelled by a GuildCreate
// are processed in one batch here. // will be processed at this point.
setTimeout(() => { setTimeout(() => {
this._inStartupGrace = false; this._inStartupGrace = false;
const pending = this._deferredGuildDeletes; const pending = this._deferredGuildDeletes.size;
if (pending.size > 0) { if (pending > 0) {
const ids = [...pending.keys()]; logger.guild(
// Clear all individual deferred timers — we'll process them all at once `[GuildDelete] Startup grace period ended. ` +
for (const [, data] of pending) { `${pending} deferred deletion(s) will be processed by their timers.`
clearTimeout(data.timer); );
} } else {
pending.clear(); logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`);
this._processGuildDelete(ids);
} }
}, this._startupDeleteGraceMs); }, this._startupDeleteGraceMs);
// ── Boot 24/7 auto-rejoin ──────────────────────────────────────────────── // ── Boot 24/7 auto-rejoin ────────────────────────────────────────────────
// After a reboot/crash, automatically rejoin all voice channels that have // After a reboot/crash, automatically rejoin all voice channels that have
// 24/7 mode enabled (stay_247 setting with mode "on" or "auto"). // 24/7 mode enabled (stay_247 setting with mode "on" or "auto").
// Minimal delay — Moonlink is already ready by onReady time. // Delayed slightly to let the gateway settle and Moonlink initialise.
setTimeout(() => this.rejoin247Channels(), 2_000); setTimeout(() => this.rejoin247Channels(), 5_000);
} }
/** /**
@@ -1200,8 +1236,7 @@ export class GatewayHandler {
// Verify the channel still exists // Verify the channel still exists
const ch = remix.client?.channels?.get?.(channelId); const ch = remix.client?.channels?.get?.(channelId);
if (!ch) { if (!ch) {
logger.voice247(`[BootRecovery] Channel ${channelId} no longer exists — removing 24/7 state`); logger.voice247(`[BootRecovery] Channel ${channelId} no longer exists — skipping`);
this._remove247ForChannel(guildId, channelId);
return; return;
} }
@@ -1209,101 +1244,47 @@ export class GatewayHandler {
await remix._spawnPlayer(guildId, channelId); await remix._spawnPlayer(guildId, channelId);
logger.voice247(`[BootRecovery] Successfully rejoined 24/7 channel ${channelId}`); logger.voice247(`[BootRecovery] Successfully rejoined 24/7 channel ${channelId}`);
} catch (e) { } catch (e) {
const msg = e?.message ?? ""; logger.warn(`[BootRecovery] Failed to rejoin 24/7 channel ${channelId}: ${e.message}`);
// 401 Unauthorized means the bot lost access to the channel (kicked,
// lost permissions, or channel deleted). Auto-remove the 24/7 state
// so we don't keep retrying on every reboot.
if (msg.includes("401") || msg.includes("Unauthorized") ||
msg.includes("NOT_LOGGED_IN") || msg.includes("Forbidden")) {
logger.warn(`[BootRecovery] 401 for channel ${channelId} — bot lacks access, removing 24/7 state`);
this._remove247ForChannel(guildId, channelId);
} else {
logger.warn(`[BootRecovery] Failed to rejoin 24/7 channel ${channelId}: ${msg}`);
}
} }
}, delay); }, delay);
} }
} }
/**
* Remove 24/7 state for a specific channel when the bot can't access it.
* This prevents repeated 401 failures on every reboot.
*
* @param {string} guildId
* @param {string} channelId Clean (digits-only) channel ID
*/
_remove247ForChannel(guildId, channelId) {
const { remix } = this;
const set = remix.settingsMgr?.getServer?.(guildId);
if (!set) return;
const raw = set.get("stay_247");
if (!raw || raw === "none") return;
const channels = Array.isArray(raw)
? new Set(raw.map(id => String(id).replace(/\D/g, "")))
: new Set([String(raw).replace(/\D/g, "")]);
const cleanCh = String(channelId).replace(/\D/g, "");
if (!channels.has(cleanCh)) return;
channels.delete(cleanCh);
// Use the shared helper to remove the per-channel mode entry and update the guild-wide mode
remove247ChannelMode(set, cleanCh, channels);
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
logger.voice247(`[BootRecovery] Removed 24/7 for channel ${cleanCh} in guild ${guildId} (inaccessible)`);
}
// ── GuildDelete cleanup (extracted for deferred processing) ──────────────── // ── GuildDelete cleanup (extracted for deferred processing) ────────────────
/** /**
* Perform the actual cleanup for guild(s) that the bot was removed from. * Perform the actual cleanup for a guild that the bot was removed from.
* Accepts a single guildId (string) or an array of guildIds for batch * Extracted from the GuildDelete handler so it can be called after the
* processing (used when the startup grace period expires with multiple * startup grace period expires.
* deferred deletes). Logs ONE summary line with all cleaned guild IDs. * @param {string} guildId
* @param {string|string[]} guildIds
*/ */
_processGuildDelete(guildIds) { _processGuildDelete(guildId) {
const ids = Array.isArray(guildIds) ? guildIds : [guildIds];
const { remix } = this; const { remix } = this;
const cleanedIds = []; const cleanGuildId = String(guildId).replace(/\D/g, "");
let totalDestroyedPlayers = 0;
for (const guildId of ids) { for (const [channelId, player] of remix.players.playerMap) {
const cleanGuildId = String(guildId).replace(/\D/g, ""); if (String(player._guildId ?? "").replace(/\D/g, "") === cleanGuildId) {
let destroyedPlayers = 0; remix.players.playerMap.delete(channelId);
try { player.leave().catch(() => {}); } catch (_) {}
for (const [channelId, player] of remix.players.playerMap) { try { player.destroy(); } catch (_) {}
if (String(player._guildId ?? "").replace(/\D/g, "") === cleanGuildId) { logger.guild(`[GuildDelete] Destroyed player for channel ${channelId}.`);
remix.players.playerMap.delete(channelId);
try { player.leave().catch(() => {}); } catch (_) {}
try { player.destroy(); } catch (_) {}
destroyedPlayers++;
}
} }
for (const [userId, info] of [...remix.observedVoiceUsers]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceUsers.delete(userId);
}
for (const [userId, info] of [...remix.observedVoiceBots]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceBots.delete(userId);
}
for (const [stateKey, info] of [...this._prevVoiceState]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId)
this._prevVoiceState.delete(stateKey);
}
remix.settingsMgr.removeServer(guildId);
remix._announcementChannelCache.delete(guildId);
cleanedIds.push(guildId);
totalDestroyedPlayers += destroyedPlayers;
} }
if (cleanedIds.length > 0) { for (const [userId, info] of [...remix.observedVoiceUsers]) {
const extra = totalDestroyedPlayers > 0 ? ` (${totalDestroyedPlayers} player(s) destroyed)` : ""; if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceUsers.delete(userId);
logger.guild(`[GuildDelete] Cleaned up ${cleanedIds.length} server(s): ${cleanedIds.join(", ")}${extra}`);
} }
for (const [userId, info] of [...remix.observedVoiceBots]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceBots.delete(userId);
}
for (const [stateKey, info] of [...this._prevVoiceState]) {
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId)
this._prevVoiceState.delete(stateKey);
}
remix.settingsMgr.removeServer(guildId);
remix._announcementChannelCache.delete(guildId);
logger.guild(`[GuildDelete] Cleanup complete for server ${guildId}.`);
} }
} }
+2 -2
View File
@@ -1003,7 +1003,7 @@ export default class Player extends EventEmitter {
if (this._destroyed) return; if (this._destroyed) return;
if (this._isJoining) { if (this._isJoining) {
logger.mediaplayer(`[Player] Busy joining. Ignoring: ${channelId}`); logger.player(`[Player] Busy joining. Ignoring: ${channelId}`);
return; return;
} }
if (this.connection && this._channelId === channelId) { if (this.connection && this._channelId === channelId) {
@@ -1289,7 +1289,7 @@ export default class Player extends EventEmitter {
if (e.message?.includes("401") || e.message?.includes("Unauthorized")) { if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
// Track 401 errors for logging purposes // Track 401 errors for logging purposes
logger.warn(`[Player] Join failed with 401 Unauthorized for guild ${this._guildId ?? this._resolveGuildId() ?? 'unknown'}`); logger.warn(`[Player] Join failed with 401 Unauthorized for guild ${this._guildId}`);
} }
if (this.connection) { if (this.connection) {
+59 -93
View File
@@ -31,42 +31,44 @@ import { Room, RoomEvent, ConnectionState } from "@livekit/rtc-node";
import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice"; import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice";
import { logger } from "./Logger.mjs"; import { logger } from "./Logger.mjs";
// Suppress LiveKit SDK's verbose pino/JSON logs (lk-rtc, [voice LiveKitRtc]). // ── Suppress LiveKit SDK's pino logger (console.log monkey-patch) ───────────
// setLogLevel was removed in newer @livekit/rtc-node versions. // The @livekit/rtc-node SDK uses pino for logging, which writes JSON lines
// The LiveKit SDK uses pino which writes JSON directly to process.stdout.write, // like {"level":20,"time":...,"name":"lk-rtc","msg":"..."} directly to
// bypassing console.log entirely. We must patch BOTH to fully suppress noise. // console.log. These are noisy and not useful for debugging. Since we can't
// This works without env vars and across all versions. // use environment variables (no .env, zip deployment), we monkey-patch
// console.log to filter out pino's structured log lines from "lk-rtc".
// ── Patch 1: console.log ────────────────────────────────────────────────── //
// Catches [voice LiveKitRtc] lines and any SDK logs that go through console. // How it works:
const _origConsoleLog = console.log; // 1. Save the original console.log
console.log = function (...args) { // 2. Replace console.log with a wrapper that checks if the argument is a
const msg = args.length > 0 ? String(args[0]) : ''; // JSON string from pino (starts with '{' and contains "lk-rtc")
if (msg.includes('lk-rtc') || msg.includes('[voice LiveKitRtc]') || // 3. If it is, silently drop it (or log at trace level if logger is available)
msg.includes('Connect callback received') || msg.includes('connected to room') || // 4. Otherwise, pass through to the original console.log
msg.includes('Room disconnected') || msg.includes('emitting disconnect') || {
msg.includes('room reconnecting') || msg.includes('SignalResumed')) { const _originalConsoleLog = console.log;
return; console.log = function (...args) {
} // Fast path: if the first arg is a string that looks like a pino JSON log
return _origConsoleLog.apply(console, args); if (args.length === 1 && typeof args[0] === "string" && args[0].startsWith("{")) {
}; try {
const parsed = JSON.parse(args[0]);
// ── Patch 2: process.stdout.write ───────────────────────────────────────── // Drop pino logs from LiveKit SDK ("lk-rtc" name)
// Catches pino JSON logs ({"level":20,"name":"lk-rtc",...}) that bypass if (parsed.name === "lk-rtc") return;
// console.log entirely. pino writes NDJSON directly to stdout. } catch (_) {
const _origStdoutWrite = process.stdout.write.bind(process.stdout); // Not valid JSON — pass through
process.stdout.write = function (chunk, encoding, callback) { }
if (typeof chunk === 'string') {
if (chunk.includes('"lk-rtc"') || chunk.includes('[voice LiveKitRtc]')) {
// Swallow the noisy LiveKit SDK output.
// If callback was provided, call it immediately so the caller
// doesn't hang waiting for the write to "complete".
if (typeof callback === 'function') callback();
return true;
} }
} // Suppress LiveKit SDK's human-readable log lines:
return _origStdoutWrite(chunk, encoding, callback); // [voice LiveKitRtc] connected to room
}; // [voice LiveKitRtc] Room disconnected
// [voice LiveKitRtc] emitting disconnect
// [voice LiveKitRtc] Room reconnecting...
// [voice LiveKitRtc] Room reconnected
if (args.length >= 1 && typeof args[0] === "string" && args[0].includes("[voice LiveKitRtc]")) {
return; // silently drop
}
_originalConsoleLog.apply(console, args);
};
}
// ConnectionState enum values for reference: // ConnectionState enum values for reference:
// ConnectionState.CONN_DISCONNECTED = 0 // ConnectionState.CONN_DISCONNECTED = 0
@@ -507,7 +509,7 @@ export class FluxerRevoice extends EventEmitter {
const elapsed = Date.now() - lastJoin; const elapsed = Date.now() - lastJoin;
if (elapsed < this._guildMinJoinInterval) { if (elapsed < this._guildMinJoinInterval) {
const extraWait = this._guildMinJoinInterval - elapsed; const extraWait = this._guildMinJoinInterval - elapsed;
logger.mediaplayer( logger.player(
`[FluxerRevoice] Guild ${guildId} was joined ${elapsed}ms ago — ` + `[FluxerRevoice] Guild ${guildId} was joined ${elapsed}ms ago — ` +
`waiting additional ${extraWait}ms to avoid 401 race` `waiting additional ${extraWait}ms to avoid 401 race`
); );
@@ -524,7 +526,7 @@ export class FluxerRevoice extends EventEmitter {
`aborting join for channel ${channelId} to avoid guaranteed failure. ` `aborting join for channel ${channelId} to avoid guaranteed failure. `
); );
} }
logger.mediaplayer( logger.player(
`[FluxerRevoice] Guild ${guildId} has 401 cooldown — ` + `[FluxerRevoice] Guild ${guildId} has 401 cooldown — ` +
`waiting ${Math.round(cooldownRemaining / 1000)}s before attempting join` `waiting ${Math.round(cooldownRemaining / 1000)}s before attempting join`
); );
@@ -549,16 +551,18 @@ export class FluxerRevoice extends EventEmitter {
// up fully and rejoin instead of returning a dead connection that will // up fully and rejoin instead of returning a dead connection that will
// fail with "LiveKit disconnected (connectionState: 0)". // fail with "LiveKit disconnected (connectionState: 0)".
if (existing && !existing._destroyed && existing.room && existing.room.isConnected) { if (existing && !existing._destroyed && existing.room && existing.room.isConnected) {
logger.mediaplayer(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`); logger.player(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`);
return existing; return existing;
} }
logger.mediaplayer( logger.player(
`[FluxerRevoice] Stale connection for ${channelId} — cleaning up and rejoining` `[FluxerRevoice] Stale connection for ${channelId} ` +
`(isConnected: ${existing?.room?.isConnected ?? false}, ` +
`destroyed: ${existing?._destroyed ?? true}) — cleaning up and rejoining`
); );
await this._destroyStaleConnection(channelId, existing); await this._destroyStaleConnection(channelId, existing);
} }
logger.mediaplayer(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`); logger.player(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`);
// Fetch the channel object from the client cache (or REST) // Fetch the channel object from the client cache (or REST)
let channel = this.client.channels?.get?.(channelId); let channel = this.client.channels?.get?.(channelId);
@@ -576,48 +580,34 @@ export class FluxerRevoice extends EventEmitter {
// Resolve the guild ID for this channel (used for guild-scoped leave signals) // Resolve the guild ID for this channel (used for guild-scoped leave signals)
const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null; const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null;
// Use the official @fluxerjs/voice API: voiceManager.join(channel) // Use @fluxerjs/voice to join the channel via the Fluxer gateway.
// This handles the VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE flow // This handles the VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE flow
// and creates a LiveKit connection with the returned credentials. // and creates a LiveKit connection with the returned credentials.
// Per Fluxer docs: voiceManager.join(channel) is the recommended API.
let nativeConnection; let nativeConnection;
try { try {
const vm = getVoiceManager(this.client); nativeConnection = await joinVoiceChannel(this.client, channel);
if (vm && typeof vm.join === "function") {
// Official API — voiceManager.join(channel)
nativeConnection = await vm.join(channel);
} else {
// Fallback for older @fluxerjs/voice versions that don't have vm.join()
nativeConnection = await joinVoiceChannel(this.client, channel);
}
} catch (e) { } catch (e) {
// If the error is 401 Unauthorized (or FluxerAPIError equivalent), // If the error is 401 Unauthorized, set a cooldown for this guild
// set a cooldown for this guild so subsequent join attempts wait longer. // so subsequent join attempts wait longer before retrying.
// Fluxer uses FluxerAPIError / FluxerError for API errors, but the if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
// underlying LiveKit/gateway error may still surface as "401" or
// "Unauthorized" in the message. Check both patterns.
const errMsg = e?.message ?? String(e ?? "");
const is401 = errMsg.includes("401") || errMsg.includes("Unauthorized") ||
errMsg.includes("NOT_LOGGED_IN") || errMsg.includes("Forbidden");
if (is401) {
const gId = channelGuildId ?? this._resolveGuildForChannel(channelId); const gId = channelGuildId ?? this._resolveGuildForChannel(channelId);
if (gId) { if (gId) {
// Set 15-second cooldown for this guild to prevent rapid 401 retries // Set 15-second cooldown for this guild to prevent rapid 401 retries
this._guild401Cooldown.set(gId, Date.now() + 15_000); this._guild401Cooldown.set(gId, Date.now() + 15_000);
logger.warn( logger.warn(
`[FluxerRevoice] 401/auth error for channel ${channelId} — ` + `[FluxerRevoice] 401 error for channel ${channelId} — ` +
`setting 15s cooldown for guild ${gId}: ${errMsg}` `setting 15s cooldown for guild ${gId}`
); );
} }
} }
throw new Error(`Fluxer voice join failed for ${channelId}: ${errMsg}`); throw new Error(`Fluxer voice join failed for ${channelId}: ${e.message}`);
} }
if (!nativeConnection) { if (!nativeConnection) {
throw new Error(`Fluxer voice join returned null for ${channelId}`); throw new Error(`Fluxer voice join returned null for ${channelId}`);
} }
logger.mediaplayer(`[FluxerRevoice] Gateway join successful, extracting LiveKit room...`); logger.player(`[FluxerRevoice] Gateway join successful, extracting LiveKit room...`);
// The @fluxerjs/voice connection wraps a LiveKit Room. // The @fluxerjs/voice connection wraps a LiveKit Room.
// Extract it so we can use it with revoice.js's MediaPlayer. // Extract it so we can use it with revoice.js's MediaPlayer.
@@ -626,7 +616,7 @@ export class FluxerRevoice extends EventEmitter {
// Try to get the LiveKit Room from the native connection // Try to get the LiveKit Room from the native connection
if (nativeConnection.room) { if (nativeConnection.room) {
room = nativeConnection.room; room = nativeConnection.room;
logger.mediaplayer(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`); logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
} }
// (non-LiveKit) which we don't support for music playback. // (non-LiveKit) which we don't support for music playback.
@@ -691,7 +681,7 @@ export class FluxerRevoice extends EventEmitter {
throw new Error(`LiveKit room in disconnected state: ${stateLabel(finalCS)}`); throw new Error(`LiveKit room in disconnected state: ${stateLabel(finalCS)}`);
} }
logger.mediaplayer(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`); logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
// Record the successful join time for this guild so future joins // Record the successful join time for this guild so future joins
// can enforce the minimum interval and avoid 401 races. // can enforce the minimum interval and avoid 401 races.
@@ -718,7 +708,7 @@ export class FluxerRevoice extends EventEmitter {
room.on(RoomEvent.Disconnected, (reason) => { room.on(RoomEvent.Disconnected, (reason) => {
const isIntentional = this._intentionalDisconnects.has(String(channelId)); const isIntentional = this._intentionalDisconnects.has(String(channelId));
const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected"); const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected");
logger.mediaplayer(`[FluxerRevoice] Room disconnected: ${reasonLabel}${isIntentional ? " (bot-initiated, recovery suppressed)" : ""}`); logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}${isIntentional ? " (bot-initiated, recovery suppressed)" : ""}`);
this._intentionalDisconnects.delete(String(channelId)); this._intentionalDisconnects.delete(String(channelId));
connection._connected = false; connection._connected = false;
connection._destroyed = true; connection._destroyed = true;
@@ -743,11 +733,11 @@ export class FluxerRevoice extends EventEmitter {
}); });
room.on(RoomEvent.Reconnecting, () => { room.on(RoomEvent.Reconnecting, () => {
logger.mediaplayer("[FluxerRevoice] Room reconnecting..."); logger.player("[FluxerRevoice] Room reconnecting...");
}); });
room.on(RoomEvent.Reconnected, () => { room.on(RoomEvent.Reconnected, () => {
logger.mediaplayer("[FluxerRevoice] Room reconnected"); logger.player("[FluxerRevoice] Room reconnected");
connection._connected = true; connection._connected = true;
}); });
@@ -772,30 +762,6 @@ export class FluxerRevoice extends EventEmitter {
// Track the connection // Track the connection
this.connections.set(channelId, connection); this.connections.set(channelId, connection);
// ── serverLeave event (official Fluxer reconnection API) ────────────
// Per Fluxer docs: connection.on?.('serverLeave') fires when LiveKit
// disconnects the bot. This is the recommended way to handle reconnects.
if (typeof nativeConnection?.on === "function") {
try {
nativeConnection.on("serverLeave", async () => {
const isIntentional = this._intentionalDisconnects.has(String(channelId));
if (isIntentional) {
logger.mediaplayer(`[FluxerRevoice] serverLeave for ${channelId} — intentional, skipping reconnect`);
return;
}
logger.mediaplayer(`[FluxerRevoice] serverLeave for ${channelId} — server disconnected, will reconnect via 24/7 recovery`);
// Don't reconnect here directly — the VoiceStateUpdate handler
// in GatewayHandler.mjs handles bot disconnect recovery.
// Just mark the connection as disconnected so recovery picks it up.
connection._connected = false;
this.connections.delete(channelId);
connection.emit("disconnect");
});
} catch (_) {
// nativeConnection.on may not be available in all versions
}
}
// Auto-leave when room empties (if requested) // Auto-leave when room empties (if requested)
if (_leaveIfEmpty) { if (_leaveIfEmpty) {
connection.on("userleave", () => { connection.on("userleave", () => {