Compare commits

..
15 Commits
Author SHA1 Message Date
NoLogicAlan fa5bc68f16 fix(player, voice): resolve queue loop recycling, 24/7 backoff cooldown, and command routing (#10, #11) 2026-10-21 04:29:20 +03:00
NoLogicAlan cf278ed68c fix: correct unknown command name reporting and silence background voice pings (#10) 2026-10-21 04:14:10 +03:00
NoLogicAlan f2bfff59b5 fix(voice): prevent 24/7 rejoin spam when bot is not in guild or voice times out
- Check guild membership before BootRecovery and Watchdog sweeps; keep settings intact if bot is not in server
- Wire up RejoinBackoff to apply exponential cooldown when voice joins time out
- Stop redundant retry loops and deduplicate join failure logs
2026-10-21 03:38:12 +03:00
NoLogicAlan 355f6b1129 build(docker): bump mysql from 8.0 to 8.4 LTS (#8) 2026-10-21 03:28:20 +03:00
NoLogicAlan 3115f94629 fix(settings): persist all debounced keys on rapid option updates (#5) 2026-10-21 03:24:15 +03:00
NoLogicAlan 87accdacba feat: add optional instanceUrl support for self-hosted Fluxer instances 2026-10-21 03:13:04 +03:00
NoLogicAlan e9a58f422a chore: switch container entrypoint to run shard.mjs 2026-10-21 03:08:06 +03:00
NoLogicAlan 6439f07204 fix: add 403 killswitch, 429 backoff, and rate limits to ErrorChannel 2026-10-21 02:49:39 +03:00
NoLogicAlan 2932f9110e ROLLBACK 2026-10-21 02:13:09 +03:00
NoLogicAlan fbe052b9da chore: switch container entrypoint from shard to start 2026-10-21 02:05:25 +03:00
NoLogicAlan 0a2bbc75d8 TEST 2026-10-21 01:57:29 +03:00
NoLogicAlan 5b4d1b0aa3 ... 2026-10-21 01:50:50 +03:00
NoLogicAlan b068e3e95c ... 2026-10-21 01:42:25 +03:00
NoLogicAlan 4dd9f2ade6 ... 2026-10-21 01:35:39 +03:00
NoLogicAlan 7c5f783855 ..SHARDING 2026-10-21 01:29:23 +03:00
16 changed files with 249 additions and 90 deletions

No files matched your search

+1 -1
View File
@@ -18,7 +18,7 @@ import { logger } from "../src/core/Logger.mjs";
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("stats") .setName("stats")
.setDescription("Display stats about the bot like the uptime.", "commands.stats") .setDescription("Display stats about the bot like the uptime.", "commands.stats")
.addAliases("info") .addAliases("info", "botinfo", "about")
.setCategory("util"); .setCategory("util");
/** Cache is considered fresh for this long; older values trigger a background refresh. */ /** Cache is considered fresh for this long; older values trigger a background refresh. */
+2
View File
@@ -1,6 +1,8 @@
{ {
"Comment": "Fluxer music bot configuration. Requires Node.js >= 22.13.0. Run 'node --version' to verify.", "Comment": "Fluxer music bot configuration. Requires Node.js >= 22.13.0. Run 'node --version' to verify.",
"token": "your bot token", "token": "your bot token",
"instanceUrl": null,
"instanceUrl-Comment": "Optional base URL of a self-hosted Fluxer instance (e.g. 'https://chat.example.com'). Leave null or omit to connect to the official fluxer.app.",
"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.", "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.",
+1 -1
View File
@@ -41,4 +41,4 @@ HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"] ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"]
CMD ["node", "index.mjs"] CMD ["node", "shard.mjs"]
+2 -1
View File
@@ -5,6 +5,7 @@ services:
dockerfile: docker/Dockerfile dockerfile: docker/Dockerfile
container_name: remix-bot container_name: remix-bot
restart: unless-stopped restart: unless-stopped
command: node shard.mjs
depends_on: depends_on:
mysql: mysql:
condition: service_healthy condition: service_healthy
@@ -23,7 +24,7 @@ services:
- remix-net - remix-net
mysql: mysql:
image: mysql:8.0 image: mysql:8.4
container_name: remix-mysql container_name: remix-mysql
restart: unless-stopped restart: unless-stopped
environment: environment:
+4
View File
@@ -25,4 +25,8 @@ if [ "$1" = "node" ] && [ "$2" = "shard.mjs" ]; then
echo "[Docker] Starting Remix bot (sharded supervisor)..." echo "[Docker] Starting Remix bot (sharded supervisor)..."
fi fi
if [ "$1" = "npm" ] && [ "$2" = "run" ] && [ "$3" = "shard" ]; then
echo "[Docker] Starting Remix bot (sharded supervisor via npm run shard)..."
fi
exec "$@" exec "$@"
+1 -1
View File
@@ -159,7 +159,7 @@ export class CommandHandler extends EventEmitter {
} }
if (!this.commandNames.includes(args[0].toLowerCase())) { if (!this.commandNames.includes(args[0].toLowerCase())) {
this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix$helpCmd", guildId) }), msg); this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: `${prefix}${args[0]}` }), msg);
return; return;
} }
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg); return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
+12 -2
View File
@@ -156,7 +156,7 @@ class Remix {
intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000, intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000,
}; };
const client = new Client({ const clientOptions = {
waitForGuilds: true, waitForGuilds: true,
cache: { cache: {
guilds: 10_000, guilds: 10_000,
@@ -167,7 +167,17 @@ class Remix {
}, },
...config["fluxer.js"], ...config["fluxer.js"],
presence: presenceContents.length === 0 ? undefined : buildRuntimePresence(presenceContents[0]), presence: presenceContents.length === 0 ? undefined : buildRuntimePresence(presenceContents[0]),
}); };
if (config.instanceUrl) {
const url = String(config.instanceUrl).trim().replace(/\/+$/, "");
if (url) {
clientOptions.instance = { api: url };
logger.info(`[Startup] Self-hosted instance configured: ${url}`);
}
}
const client = new Client(clientOptions);
client.setMaxListeners(50); client.setMaxListeners(50);
this.client = client; this.client = client;
+13 -2
View File
@@ -188,6 +188,18 @@ const BotVoiceMixin = {
return; return;
} }
const guild = this.client?.guilds?.get?.(cleanG);
if (!guild) {
logger.voice247(`[247] Bot is not currently in guild ${cleanG} — skipping rejoin for ${cleanCh} (setting kept intact)`);
return;
}
const backoffRemaining = this.gatewayHandler?.rejoinBackoff?.remainingMs?.(cleanCh) ?? 0;
if (backoffRemaining > 0 && delayMs === null) {
logger.voice247(`[247] Channel ${cleanCh} in backoff cooldown (${Math.round(backoffRemaining / 1000)}s left) — skipping immediate rejoin`);
return;
}
if (!this._247RejoinTimers) this._247RejoinTimers = new Map(); if (!this._247RejoinTimers) this._247RejoinTimers = new Map();
if (this._247RejoinTimers.has(cleanCh)) return; if (this._247RejoinTimers.has(cleanCh)) return;
@@ -407,8 +419,7 @@ const BotVoiceMixin = {
this.players._pendingJoins.delete(cleanChannelId); this.players._pendingJoins.delete(cleanChannelId);
} }
this.players.playerMap.delete(cleanChannelId); this.players.playerMap.delete(cleanChannelId);
try { player.destroy(); } catch(e) { logger.warn("[_spawnPlayer] Cleanup destroy error:", e?.message); } try { player.destroy(); } catch(e) {}
logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message);
throw err; throw err;
} }
}, },
+97 -12
View File
@@ -52,9 +52,33 @@ let _dropped = 0;
let _flushing = false; let _flushing = false;
let _announced = false; let _announced = false;
const _forwardDedup = new Map(); let _forwardDedup = new Map();
const _crashDedup = new Map(); let _crashDedup = new Map();
let _lastFailLog = 0; let _lastFailLog = 0;
let _rateLimitedUntil = 0;
let _consecutiveFailures = 0;
let _lastCrashReportTime = 0;
const CRASH_MIN_INTERVAL_MS = 5_000;
const MAX_CONSECUTIVE_FAILURES = 5;
/** @private Check if we are currently rate-limited before sending. */
function _isRateLimited() {
return Date.now() < _rateLimitedUntil;
}
/** @private Apply an explicit rate-limit backoff delay. */
function _applyRateLimit(seconds = 15) {
const ms = Math.max(10_000, Number(seconds) * 1_000);
_rateLimitedUntil = Date.now() + ms;
console.warn(`[ErrorChannel] Rate limit (429) active — backing off all error channel sends for ${Math.round(ms / 1000)}s.`);
}
/** @private Handle permanent permission failures (403/404) by permanently disabling the reporter. */
function _disablePermissionFailure(status) {
_enabled = false;
_queue = [];
console.error(`[ErrorChannel] FATAL: Bot lacks permission (HTTP ${status}) for channel ${_channelId}. ErrorChannel has been PERMANENTLY DISABLED to prevent API flooding.`);
}
const _originals = { error: null, warn: null, info: null }; const _originals = { error: null, warn: null, info: null };
@@ -123,7 +147,12 @@ function _announceOnce() {
* @returns {Promise<boolean>} True when the message was delivered. * @returns {Promise<boolean>} True when the message was delivered.
*/ */
export async function reportCrash(title, err, { fatal = false } = {}) { export async function reportCrash(title, err, { fatal = false } = {}) {
if (!_enabled || !_channelId) return false; if (!_enabled || !_channelId || _isRateLimited()) return false;
const now = Date.now();
if (now - _lastCrashReportTime < CRASH_MIN_INTERVAL_MS) {
return false;
}
_lastCrashReportTime = now;
try { try {
const body = _formatArgs([err]).split("```").join("‹›"); const body = _formatArgs([err]).split("```").join("‹›");
const now = Date.now(); const now = Date.now();
@@ -236,11 +265,20 @@ async function _runFlush() {
_flushing = true; _flushing = true;
try { try {
while (_queue.length > 0) { while (_queue.length > 0) {
if (!_enabled) {
_queue = [];
break;
}
if (_isRateLimited()) {
const waitMs = Math.max(1_000, _rateLimitedUntil - Date.now() + 500);
await _sleep(waitMs);
continue;
}
const content = _queue.shift(); const content = _queue.shift();
await _sendQuietly(content); await _sendQuietly(content);
await _sleep(_minIntervalMs); await _sleep(_minIntervalMs);
} }
if (_dropped > 0) { if (_dropped > 0 && _enabled) {
const n = _dropped; const n = _dropped;
_dropped = 0; _dropped = 0;
await _sendQuietly(`📦 ${n} additional error log message(s) were dropped during a flood to protect rate limits.`); await _sendQuietly(`📦 ${n} additional error log message(s) were dropped during a flood to protect rate limits.`);
@@ -265,35 +303,82 @@ async function _sendQuietly(content) {
/** @private Send through the client's REST client when available, else raw fetch. */ /** @private Send through the client's REST client when available, else raw fetch. */
async function _send(content) { async function _send(content) {
if (!_enabled || _isRateLimited()) return;
const rest = _client?.rest; const rest = _client?.rest;
if (typeof rest?.post === "function") { if (typeof rest?.post === "function") {
await rest.post(`/channels/${_channelId}/messages`, { body: { content } }); try {
return; await rest.post(`/channels/${_channelId}/messages`, { body: { content } });
_consecutiveFailures = 0;
return;
} catch (err) {
const status = err?.statusCode ?? err?.status;
if (status === 403 || status === 404) {
_disablePermissionFailure(status);
throw err;
}
if (status === 429) {
const retryAfter = err?.retryAfter ?? 15;
_applyRateLimit(retryAfter);
throw err;
}
throw err;
}
} }
await _sendRaw(content); await _sendRaw(content);
} }
/** @private Send via client REST, retrying once via raw fetch when that throws. */ /** @private Send via client REST, retrying once via raw fetch when that throws. */
async function _sendWithFallback(content) { async function _sendWithFallback(content) {
if (!_enabled || _isRateLimited()) return;
try { try {
await _send(content); await _send(content);
} catch (_) { } catch (_) {
if (!_enabled || _isRateLimited()) return;
await _sendRaw(content); await _sendRaw(content);
} }
} }
/** @private Send via a direct Fluxer REST call (Authorization: Bot <token>). */ /** @private Send via a direct Fluxer REST call (Authorization: Bot <token>). */
async function _sendRaw(content) { async function _sendRaw(content) {
const res = await fetch(`${API_BASE}/channels/${_channelId}/messages`, { if (!_enabled || _isRateLimited()) return;
method: "POST", let res;
headers: { "Authorization": `Bot ${_token}`, "Content-Type": "application/json" }, try {
body: JSON.stringify({ content }), res = await fetch(`${API_BASE}/channels/${_channelId}/messages`, {
signal: AbortSignal.timeout(SEND_TIMEOUT_MS), method: "POST",
}); headers: { "Authorization": `Bot ${_token}`, "Content-Type": "application/json" },
body: JSON.stringify({ content }),
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
});
} catch (err) {
_consecutiveFailures++;
if (_consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
_applyRateLimit(30);
}
throw err;
}
if (res.status === 403 || res.status === 404) {
_disablePermissionFailure(res.status);
throw new Error(`Fluxer API HTTP ${res.status}: Permission denied or channel not found`);
}
if (res.status === 429) {
const rawRetry = res.headers.get("retry-after");
const retrySec = Number(rawRetry) || 15;
_applyRateLimit(retrySec);
throw new Error(`Fluxer API HTTP 429: Rate limited, retry after ${retrySec}s`);
}
if (!res.ok) { if (!res.ok) {
_consecutiveFailures++;
if (_consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
_applyRateLimit(30);
}
const text = await res.text().catch(() => ""); const text = await res.text().catch(() => "");
throw new Error(`Fluxer API HTTP ${res.status}: ${text.slice(0, 200)}`); throw new Error(`Fluxer API HTTP ${res.status}: ${text.slice(0, 200)}`);
} }
_consecutiveFailures = 0;
} }
/** @private Human-readable process uptime. */ /** @private Human-readable process uptime. */
+27 -5
View File
@@ -172,6 +172,9 @@ export class RemoteSettingsManager extends SettingsManager {
/** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */ /** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */
_debounceTimers = new Map(); _debounceTimers = new Map();
/** @private @type {Map<string, Set<string>>} Pending changed setting keys per guild ID. */
_pendingKeys = new Map();
/** @private @type {boolean} True after shutdown() is called. */ /** @private @type {boolean} True after shutdown() is called. */
_shuttingDown = false; _shuttingDown = false;
@@ -210,6 +213,7 @@ export class RemoteSettingsManager extends SettingsManager {
.filter(Boolean); .filter(Boolean);
for (const [, timer] of this._debounceTimers) clearTimeout(timer); for (const [, timer] of this._debounceTimers) clearTimeout(timer);
this._debounceTimers.clear(); this._debounceTimers.clear();
this._pendingKeys.clear();
if (pendingServers.length > 0) { if (pendingServers.length > 0) {
logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`); logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`);
} }
@@ -478,18 +482,35 @@ export class RemoteSettingsManager extends SettingsManager {
if (key === 'stay_247') { if (key === 'stay_247') {
const existing = this._debounceTimers.get(server.id); const existing = this._debounceTimers.get(server.id);
if (existing) { clearTimeout(existing); this._debounceTimers.delete(server.id); } if (existing) { clearTimeout(existing); this._debounceTimers.delete(server.id); }
this._pendingKeys.delete(server.id);
this.remoteSave(s).catch(e => logger.error('[Settings] immediate save error:', e.message)); this.remoteSave(s).catch(e => logger.error('[Settings] immediate save error:', e.message));
return; return;
} }
if (!this._pendingKeys.has(server.id)) {
this._pendingKeys.set(server.id, new Set());
}
this._pendingKeys.get(server.id).add(key);
const existing = this._debounceTimers.get(server.id); const existing = this._debounceTimers.get(server.id);
if (existing) clearTimeout(existing); if (existing) clearTimeout(existing);
this._debounceTimers.set(server.id, setTimeout(() => { this._debounceTimers.set(server.id, setTimeout(async () => {
this._debounceTimers.delete(server.id); this._debounceTimers.delete(server.id);
const pending = this._pendingKeys.get(server.id);
this._pendingKeys.delete(server.id);
const target = this.guilds.get(server.id); const target = this.guilds.get(server.id);
if (target) { if (!target || !pending || pending.size === 0) return;
this.remoteUpdate(target, key).catch(e =>
logger.error(`[Settings] debounced update error (guild ${server.id}, key "${key}"):`, e?.message) try {
); if (pending.size === 1) {
const [singleKey] = pending;
await this.remoteUpdate(target, singleKey);
} else {
await this.remoteSave(target);
}
} catch (e) {
logger.error(`[Settings] debounced update error (guild ${server.id}):`, e?.message);
} }
}, 80)); }, 80));
} }
@@ -529,6 +550,7 @@ export class RemoteSettingsManager extends SettingsManager {
removeServer(id) { removeServer(id) {
const timer = this._debounceTimers.get(id); const timer = this._debounceTimers.get(id);
if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); } if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); }
this._pendingKeys.delete(id);
this.guilds.delete(id); this.guilds.delete(id);
} }
} }
+11 -21
View File
@@ -44,7 +44,6 @@ const PlaybackMixin = {
if (!this._paused) { if (!this._paused) {
this._lastPlayedTrack = this.queue.getCurrent() ?? songData; this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
if (!this.queue.songLoop) this.queue.current = null;
this._playingNext = false; this._playingNext = false;
this.playNext().catch(e => logger.error("[Player] auto-advance playNext error:", e.message)); this.playNext().catch(e => logger.error("[Player] auto-advance playNext error:", e.message));
} }
@@ -99,13 +98,14 @@ const PlaybackMixin = {
* generation counter ensures an older run's cleanup never clears the * generation counter ensures an older run's cleanup never clears the
* in-flight flag of a newer run (which previously allowed double-advances). * in-flight flag of a newer run (which previously allowed double-advances).
* @this {import('./Player.mjs').Player} * @this {import('./Player.mjs').Player}
* @param {object} [opts] - Advancement options forwarded to Queue.next.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async playNext() { async playNext(opts = {}) {
if (this._playingNext) return; if (this._playingNext) return;
this._playingNext = true; this._playingNext = true;
const generation = (this._playNextGeneration = (this._playNextGeneration ?? 0) + 1); const generation = (this._playNextGeneration = (this._playNextGeneration ?? 0) + 1);
try { await this._doPlayNext(); } try { await this._doPlayNext(opts); }
finally { if (generation === this._playNextGeneration) this._playingNext = false; } finally { if (generation === this._playNextGeneration) this._playingNext = false; }
}, },
@@ -114,13 +114,14 @@ const PlaybackMixin = {
* track options, announces, starts playback via the bridge, arms the * track options, announces, starts playback via the bridge, arms the
* track-end timer, and handles the queue-end path. * track-end timer, and handles the queue-end path.
* @this {import('./Player.mjs').Player} * @this {import('./Player.mjs').Player}
* @param {object} [opts] - Advancement options forwarded to Queue.next.
*/ */
async _doPlayNext() { async _doPlayNext(opts = {}) {
this._bridgeStop(); this._bridgeStop();
const currentBeforeNext = this.queue.getCurrent(); const currentBeforeNext = this.queue.getCurrent();
if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext; if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext;
const songData = this.queue.next(); const songData = this.queue.next(opts);
if (!songData) { if (!songData) {
this.emit("stopplay"); this.emit("stopplay");
this.emit("queueEnd"); this.emit("queueEnd");
@@ -352,24 +353,13 @@ const PlaybackMixin = {
this._playingNext = false; this._playingNext = false;
this._lastPlayedTrack = this.queue.getCurrent() ?? this._lastPlayedTrack; this._lastPlayedTrack = this.queue.getCurrent() ?? this._lastPlayedTrack;
this.emit("trackSkip", this._lastPlayedTrack); this.emit("trackSkip", this._lastPlayedTrack);
if (!this.queue.isEmpty() && !this.leaving) { if (!this.leaving) {
this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message)); this.playNext()
.catch(e => logger.error("[Player] TrackEnd playNext error:", e.message))
.finally(() => { this._skipping = false; });
} else { } else {
this.queue.current = null; this._skipping = false;
if (!this._wasRadio && !this._queueEndedSent) {
this._queueEndedSent = true;
this.emit("queueEnd");
if (!this._autoplay) {
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
}
}
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
} }
this._skipping = false;
}, },
/** /**
+18 -35
View File
@@ -608,7 +608,7 @@ class Player extends EventEmitter {
} catch (e) { } catch (e) {
const causeStr = e.cause ? ` (Cause: ${e.cause})` : ""; const causeStr = e.cause ? ` (Cause: ${e.cause})` : "";
logger.error("[Player] Join failed:", e.message, causeStr); logger.player("[Player] Join failed:", e.message, causeStr);
if (this._voiceConn) { if (this._voiceConn) {
try { await this._voiceConn.disconnect(); } catch(err) { logger.warn("[Player] voiceConn disconnect on join failure:", err?.message); } try { await this._voiceConn.disconnect(); } catch(err) { logger.warn("[Player] voiceConn disconnect on join failure:", err?.message); }
@@ -799,32 +799,20 @@ class Player extends EventEmitter {
this._radioAnnounced = false; this._radioAnnounced = false;
this._activeTrackOpt = null; this._activeTrackOpt = null;
this._clearTrackEndTimer(); this._clearTrackEndTimer();
this.queue.current = null;
this._bridgeStop(); this._bridgeStop();
this.emit("trackSkip", this._lastPlayedTrack); this.emit("trackSkip", this._lastPlayedTrack);
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
this._queueEndedSent = true;
this.emit("queueEnd");
if (!this._autoplay) {
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
}
}
this._playingNext = false; this._playingNext = false;
if (!this.queue.isEmpty() && !this.leaving) { if (!this.leaving) {
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); this.playNext({ ignoreSongLoop: true })
.catch(e => logger.error("[Player] playNext error:", e.message))
.finally(() => { this._skipping = false; });
} else { } else {
this.emit("stopplay"); this._skipping = false;
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
} }
this._skipping = false;
return ":track_next: Skipped"; return ":track_next: Skipped";
} }
@@ -840,34 +828,29 @@ class Player extends EventEmitter {
if (idx < 0 || idx >= this.queue.size()) if (idx < 0 || idx >= this.queue.size())
return `:negative_squared_cross_mark: Position ${position} out of range (queue has ${this.queue.size()} tracks).`; return `:negative_squared_cross_mark: Position ${position} out of range (queue has ${this.queue.size()} tracks).`;
this._lastPlayedTrack = this.queue.getCurrent(); this._lastPlayedTrack = this.queue.getCurrent();
this.queue.data.splice(0, idx); const skipped = [this._lastPlayedTrack, ...this.queue.data.splice(0, idx)];
if (this.queue.loop) {
this.queue.data.push(...skipped);
}
this.queue.current = null; this.queue.current = null;
this._skipping = true; this._skipping = true;
this._radioAnnounced = false;
this._activeTrackOpt = null;
this._clearTrackEndTimer();
this._bridgeStop(); this._bridgeStop();
this.emit("trackSkip", this._lastPlayedTrack); this.emit("trackSkip", this._lastPlayedTrack);
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
this._queueEndedSent = true;
this.emit("queueEnd");
if (!this._autoplay) {
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
}
}
this._playingNext = false; this._playingNext = false;
if (!this.queue.isEmpty() && !this.leaving) { if (!this.leaving) {
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); this.playNext({ ignoreSongLoop: true })
.catch(e => logger.error("[Player] playNext error:", e.message))
.finally(() => { this._skipping = false; });
} else { } else {
this.emit("stopplay"); this._skipping = false;
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
} }
this._skipping = false;
return `:track_next: Skipped to position ${position}`; return `:track_next: Skipped to position ${position}`;
} }
+4 -2
View File
@@ -40,12 +40,14 @@ export class Queue extends EventEmitter {
/** /**
* Advance to the next track in the queue. If songLoop is active, returns * Advance to the next track in the queue. If songLoop is active, returns
* the current track. If queue loop is active, re-appends the current track. * the current track. If queue loop is active, re-appends the current track.
* @param {object} [options]
* @param {boolean} [options.ignoreSongLoop=false] - Bypass songLoop (used when explicitly skipping).
* @returns {object|null} The next track, or null if the queue is empty. * @returns {object|null} The next track, or null if the queue is empty.
*/ */
next() { next({ ignoreSongLoop = false } = {}) {
const previous = this.current; const previous = this.current;
if (this.songLoop && this.current) return this.current; if (!ignoreSongLoop && this.songLoop && this.current) return this.current;
if (this.loop && this.current) this.data.push(this.current); if (this.loop && this.current) this.data.push(this.current);
if (this.isEmpty()) { if (this.isEmpty()) {
+17 -2
View File
@@ -19,6 +19,7 @@ import VoiceStateRouting from "./VoiceStateRouting.mjs";
import GuildSync from "./GuildSync.mjs"; import GuildSync from "./GuildSync.mjs";
import RejoinManager from "./RejoinManager.mjs"; import RejoinManager from "./RejoinManager.mjs";
import Watchdog247 from "./Watchdog247.mjs"; import Watchdog247 from "./Watchdog247.mjs";
import RejoinBackoff from "./RejoinBackoff.mjs";
const RAW_GATEWAY_INTEREST = const RAW_GATEWAY_INTEREST =
/"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/; /"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/;
@@ -41,6 +42,8 @@ class GatewayHandler {
this.presenceContents = remix.config.presenceContents ?? []; this.presenceContents = remix.config.presenceContents ?? [];
this.presenceInterval = remix.config.presenceInterval ?? 30_000; this.presenceInterval = remix.config.presenceInterval ?? 30_000;
this.rejoinBackoff = new RejoinBackoff();
this.wsListenerAttached = false; this.wsListenerAttached = false;
this.presenceTimer = null; this.presenceTimer = null;
this.presenceIndex = 0; this.presenceIndex = 0;
@@ -521,6 +524,16 @@ class GatewayHandler {
for (let i = 0; i < channelsToRejoin.length; i++) { for (let i = 0; i < channelsToRejoin.length; i++) {
const { guildId, channelId, mode } = channelsToRejoin[i]; const { guildId, channelId, mode } = channelsToRejoin[i];
const cleanG = cleanId(guildId);
const cleanC = cleanId(channelId);
const guild = remix.client?.guilds?.get?.(cleanG);
if (!guild) {
logger.voice247(
`[BootRecovery] Bot is not currently in guild ${cleanG} — skipping channel ${cleanC} (setting kept intact).`
);
continue;
}
if (i > 0) { if (i > 0) {
let staggerDelay = baseStagger; let staggerDelay = baseStagger;
@@ -581,13 +594,15 @@ class GatewayHandler {
const player = await this._attemptRejoin(channelId, guildId, 3, 5_000, "BootRecovery"); const player = await this._attemptRejoin(channelId, guildId, 3, 5_000, "BootRecovery");
if (player) { if (player) {
this.rejoinBackoff?.recordSuccess?.(channelId);
logger.voice247( logger.voice247(
`[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` `[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]`
); );
} else { } else {
this.rejoinBackoff?.recordFailure?.(channelId);
logger.warn( logger.warn(
`[BootRecovery] Failed to rejoin channel ${channelId} in guild ${guildId} after retries — ` + `[BootRecovery] Could not rejoin channel ${channelId} in guild ${guildId} — ` +
`keeping 24/7 setting intact, will retry on next disconnect/restart.` `keeping 24/7 setting intact (backed off).`
); );
} }
} }
+23 -4
View File
@@ -56,10 +56,16 @@ const RejoinManager = {
continue; continue;
} }
logger.warn( const failCount = this.rejoinBackoff?.failures?.(channelId) ?? 0;
`[${context}] Failed to rejoin channel ${channelId} (attempt ${attempt}/${maxRetries}): ${errMsg}` + if (failCount >= 2) {
(attempt > 1 ? ` (after ${attempt} attempts)` : '') logger.voice247(
); `[${context}] Background rejoin failed for channel ${channelId} (failure #${failCount + 1}): ${errMsg} — keeping 24/7 setting intact.`
);
} else {
logger.warn(
`[${context}] Failed to rejoin channel ${channelId}: ${errMsg} — keeping 24/7 setting intact.`
);
}
return null; return null;
} }
} }
@@ -79,6 +85,17 @@ const RejoinManager = {
const cleanGuildId = cleanId(guildId); const cleanGuildId = cleanId(guildId);
const cleanChannelId = cleanId(channelId); const cleanChannelId = cleanId(channelId);
const guild = remix.client?.guilds?.get?.(cleanGuildId);
if (!guild) {
logger.voice247(`[Rejoin] Bot is not currently in guild ${cleanGuildId} — skipping ${cleanChannelId} (setting kept intact).`);
return;
}
if (this.rejoinBackoff?.remainingMs?.(cleanChannelId) > 0) {
logger.voice247(`[Rejoin] Channel ${cleanChannelId} in backoff cooldown — skipping.`);
return;
}
if (this._rejoinInProgress.has(cleanChannelId)) { if (this._rejoinInProgress.has(cleanChannelId)) {
logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`); logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`);
return; return;
@@ -131,6 +148,7 @@ const RejoinManager = {
const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin"); const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin");
if (player) { if (player) {
this._rejoinAttempts.delete(cleanChannelId); this._rejoinAttempts.delete(cleanChannelId);
this.rejoinBackoff?.recordSuccess?.(cleanChannelId);
try { try {
await remix.restorePlayerStateForChannel?.(cleanGuildId, cleanChannelId, player); await remix.restorePlayerStateForChannel?.(cleanGuildId, cleanChannelId, player);
} catch (err) { } catch (err) {
@@ -138,6 +156,7 @@ const RejoinManager = {
} }
} else { } else {
this._rejoinAttempts.delete(cleanChannelId); this._rejoinAttempts.delete(cleanChannelId);
this.rejoinBackoff?.recordFailure?.(cleanChannelId);
} }
return player; return player;
} finally { } finally {
+16 -1
View File
@@ -167,7 +167,22 @@ const Watchdog247 = {
} }
for (const { guildId, channelId } of savedChannels) { for (const { guildId, channelId } of savedChannels) {
if (remix.intentionalLeaves?.has?.(channelId)) { const cleanG = cleanId(guildId);
const cleanCh = cleanId(channelId);
const guild = remix.client?.guilds?.get?.(cleanG);
if (!guild) {
// Bot is not in this guild — keep 24/7 setting intact for future invite, but skip sweep
skipped++;
continue;
}
if (this.rejoinBackoff?.remainingMs?.(cleanCh) > 0) {
skipped++;
continue;
}
if (remix.intentionalLeaves?.has?.(cleanCh)) {
skipped++; skipped++;
continue; continue;
} }