feat(leave): add optional channel argument to /leave command

- %leave now accepts an optional `channel` option; defaults to the
  user's current voice channel when omitted
- Updated locale strings to describe the new behaviour and provide
  clearer error messages (noVoiceChannel, specifyChannel, noPlayerInChannel)

fix(PlayerManager): improve voice-state resolution after reboot

- Added VoiceManager.voiceStates as a fallback lookup when
  getVoiceChannelId() returns null on startup
- Multi-player guilds now check LiveKit remote participants to
  determine which channel a user is actually in
- Filter out destroyed players when resolving guild player list

fix(PlayerManager): deduplicate Last.fm scrobble timers

- Added _pendingScrobbleTimers map to prevent duplicate scrobbles
  when startplay fires multiple times for the same channel
- Timers are now properly cleared on song skip and player stop

fix(RecoveryManager): restore textChannel after reboot for 24/7 mode

- Spawned players after reboot now resolve an announcement channel
  from server settings or the first available text channel, so song
  announcements aren't silently dropped

fix(Player): remove unused worker semaphore and dead media-player code

- Removed _workerSemaphore / _workerQueue / _workerPool semaphore logic
- Removed no-op _setupMediaPlayerMonitoring and _cleanupMediaPlayer methods
- Removed unused spotifyConfig field

fix(CommandHandler): skip Flag instances during option processing
This commit is contained in:
NoLogicAlan committed 2026-05-12 19:01:03 +03:00
1 parent 7a4009f5c3
commit 9cfa8e2e6c
10 files changed
+188 -100

No files matched your search

+1
View File
@@ -586,6 +586,7 @@ export class CommandHandler extends EventEmitter {
}
if (!o) continue;
if (o instanceof Flag) continue;
if (opts.findIndex(op => op.uid === o.uid) !== -1) continue;
let value = args[argIndex];
if ((args[argIndex] || "").startsWith('"') && (STRING_TYPES.includes(o.type))) {
+2 -57
View File
@@ -243,8 +243,6 @@ export class Queue extends EventEmitter {
return `Moved **${track.title}** from position ${from + 1} to ${to + 1}.`;
}
addFirst(data) { return this.add(data, true); }
add(data, top = false) {
this.emit("queue", { type: "add", data: { append: !top, data } });
return top ? this.data.unshift(data) : this.data.push(data);
@@ -311,8 +309,6 @@ export default class Player extends EventEmitter {
client = null;
settings = null;
config = {};
spotifyConfig = null;
// revoice.js instances
/** @type {import("revoice.js").MediaPlayer|null} */
_mediaPlayer = null;
@@ -377,7 +373,6 @@ export default class Player extends EventEmitter {
this.queue = new Queue();
this.client = opts.client;
this.config = opts.config ?? {};
this.spotifyConfig = opts.config?.spotify;
this.settings = opts.settings ?? null;
this.settingsMgr = opts.settingsMgr ?? null;
this._observedVoiceUsers = opts.observedVoiceUsers ?? null;
@@ -739,17 +734,7 @@ export default class Player extends EventEmitter {
// @fluxerjs channels do NOT have a .members property.
// Use the guild's member manager and filter by voice state instead.
const guild = this.client?.guilds?.get?.(this._guildId);
if (guild?.members) {
for (const member of guild.members.values()) {
// GuildMember doesn't expose voice channelId directly in @fluxerjs,
// so fall through to the voice_states raw data check below.
if (!member?.user?.bot) {
// We can't determine channel from member alone — skip here
// and rely on _observedVoiceUsers or voice_states instead.
}
}
}
// Fallback: iterate raw voice_states on the guild object.
// Iterate raw voice_states on the guild object.
const voiceStates = guild?.voice_states;
if (voiceStates) {
const entries = Array.isArray(voiceStates)
@@ -892,8 +877,6 @@ export default class Player extends EventEmitter {
try {
this._mediaPlayer = new MediaPlayer();
this._mediaPlayer.setMaxListeners(0);
this._setupMediaPlayerMonitoring();
await this._mediaPlayer.publishToRoom(room);
logger.mediaplayer("[Player] MediaPlayer published successfully");
return true;
@@ -914,18 +897,6 @@ export default class Player extends EventEmitter {
}
}
_setupMediaPlayerMonitoring() {
// No-op: recovery is fully handled by connection.on("disconnect") in join().
}
async _cleanupMediaPlayer() {
try {
await this._mediaPlayer?.stop();
} catch (_) {}
this._mediaPlayer = null;
}
async _stopMediaPlayer() {
this._streamingStopped = true;
@@ -1624,12 +1595,6 @@ export default class Player extends EventEmitter {
this._workerPool = null;
}
while (this._workerQueue.length > 0) {
const resolve = this._workerQueue.shift();
resolve();
}
this._workerSemaphore = 0;
const connToDestroy = this.connection;
this.connection = null;
this._mediaPlayer = null;
@@ -2124,27 +2089,7 @@ export default class Player extends EventEmitter {
// Worker Management
// ═══════════════════════════════════════════════════════════════════════════
_workerSemaphore = 0;
_workerMaxConcurrent = 3;
_workerQueue = [];
_workerPool = null;
_acquireWorkerSlot() {
if (this._workerSemaphore < this._workerMaxConcurrent) {
this._workerSemaphore++;
return Promise.resolve();
}
return new Promise(resolve => this._workerQueue.push(resolve));
}
_releaseWorkerSlot() {
const next = this._workerQueue.shift();
if (next) {
next();
} else {
this._workerSemaphore--;
}
}
_workerPool = null;
_getWorkerPool() {
if (!this._workerPool) {
+64 -2
View File
@@ -87,6 +87,10 @@ export class PlayerManager {
/** @type {Set<string>} Channel IDs currently being joined (not yet in playerMap) */
_pendingJoins = new Set();
/** @type {Map<string, {timer, songUrl, startedAtMs}>} Pending scrobble timers keyed by channel ID.
* Prevents duplicate scrobbles when startplay fires multiple times. */
_pendingScrobbleTimers = new Map();
/** @type {Object} */
config;
@@ -387,6 +391,22 @@ export class PlayerManager {
if (seeded) return seeded;
} catch (_) {}
// ── Fallback: VoiceManager.voiceStates direct lookup ────────────────
// After a reboot, getVoiceChannelId() may return null if the
// VoiceManager hasn't synced yet, but voiceStates (populated from
// READY / GUILD_CREATE raw gateway events) may already have the data.
try {
const vm = getVoiceManager(this.commands.client);
if (vm?.voiceStates) {
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
if (guildVoiceMap && typeof guildVoiceMap.get === "function") {
const vmChannelId = guildVoiceMap.get(userId);
const seeded = seedObserved(vmChannelId);
if (seeded) return seeded;
}
}
} catch (_) {}
const memberVoiceChannelId =
message?.member?.voice?.channelId ??
message?.message?.member?.voice?.channelId ??
@@ -428,15 +448,37 @@ export class PlayerManager {
}
} catch (_) {}
// ── Fallback: match user to any active player in the guild ──────────
// After a reboot with 24/7, voice states may not be fully populated.
// If the guild has active players, check if any of them have the user
// as a remote participant in their LiveKit room.
const liveGuildPlayers = [...this.playerMap.entries()].filter(([channelId, player]) => {
const fallbackChannel =
this.commands.client?.channels?.get?.(channelId) ??
null;
return getPlayerGuildId(player, fallbackChannel) === cleanGuild;
return getPlayerGuildId(player, fallbackChannel) === cleanGuild && !player?._destroyed;
});
if (liveGuildPlayers.length === 1) {
return getPlayerChannelId(liveGuildPlayers[0][1], liveGuildPlayers[0][0]) || cleanId(liveGuildPlayers[0][0]);
}
// Multiple players — try LiveKit remote participants to find which
// channel the user is actually in.
if (liveGuildPlayers.length > 1) {
for (const [mapKey, player] of liveGuildPlayers) {
try {
const room = player?.connection?.room;
if (!room?.isConnected || !room.remoteParticipants) continue;
for (const [, participant] of room.remoteParticipants) {
const pId = participant?.identity ?? participant?.sid;
if (pId === userId) {
const found = getPlayerChannelId(player, mapKey) || cleanId(mapKey);
seedObserved(found);
return found;
}
}
} catch (_) {}
}
}
return null;
}
@@ -658,6 +700,9 @@ export class PlayerManager {
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
this.playerMap.delete(activeChannelId);
// Clean up pending scrobble timer
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
await player.leave();
@@ -750,6 +795,9 @@ export class PlayerManager {
// 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();
@@ -893,6 +941,16 @@ export class PlayerManager {
const startedAtMs = player.startedPlaying;
// ── Cancel any previous pending scrobble timer for this channel ───────
// Prevents duplicate scrobbles when startplay fires multiple times
// (e.g. recovery rejoining, track restart, queue loop).
const pendingKey = channelId;
const existing = this._pendingScrobbleTimers.get(pendingKey);
if (existing) {
clearTimeout(existing.timer);
this._pendingScrobbleTimers.delete(pendingKey);
}
// Send now-playing for each linked user
for (const userId of humanUserIds) {
lastfm.updateNowPlaying(userId, song).catch(() => {});
@@ -914,7 +972,8 @@ export class PlayerManager {
);
// Don't schedule if threshold is too far out (cap at 10 min)
if (thresholdMs <= 600_000) {
setTimeout(() => {
const timer = setTimeout(() => {
this._pendingScrobbleTimers.delete(pendingKey);
// Only scrobble if the same song is still playing
const current = player.queue?.getCurrent();
if (!current || player._destroyed || player.leaving) return;
@@ -928,6 +987,9 @@ export class PlayerManager {
}
}
}, thresholdMs);
// Store the timer so we can cancel it if startplay fires again
this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs });
}
}
}
+29
View File
@@ -256,9 +256,38 @@ export class RecoveryManager {
revoice: remix.revoice,
settingsMgr: remix.settingsMgr,
observedVoiceUsers: remix.observedVoiceUsers,
locale: remix.locale ?? null,
});
remix.players.setupEvents(p, { channelId: cleanChannelId, guildId });
// ── Set a default textChannel so song announcements have somewhere to go ──
// After a reboot, spawned players don't have a user message to set
// textChannel from. Find the guild's announcement channel or the first
// available text channel as a fallback.
try {
const guild = remix.client.guilds.get(cleanGuildId) ?? remix.client.guilds.get(guildId);
const serverSet = remix.settingsMgr.getServer(guildId);
const cachedChId = remix._announcementChannelCache?.get?.(guildId)
?? serverSet?.get("announcementChannelId")
?? null;
let textCh = cachedChId ? guild?.channels?.get(String(cachedChId)) : null;
if (!textCh && guild) {
textCh = [...(guild.channels?.values?.() ?? [])].find(c =>
(c.isTextBased?.() ?? c.channel_type === "TextChannel" ?? true) &&
(c.permissionsFor?.(remix.client.user)?.has?.("SendMessages") ?? true)
);
}
if (textCh) {
p.textChannel = textCh;
if (!cachedChId && serverSet) {
remix._announcementChannelCache?.set?.(guildId, textCh.id);
if (serverSet.get("announcementChannelId") !== textCh.id) {
serverSet.set("announcementChannelId", textCh.id);
}
}
}
} catch (_) {}
// ── Autoleave handler ───────────────────────────────────────────────────
p.on("autoleave", async () => {
const activeChannelId = String(p._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId;