diff --git a/commands/debug.mjs b/commands/debug.mjs index 64bc206..415ec40 100644 --- a/commands/debug.mjs +++ b/commands/debug.mjs @@ -18,18 +18,39 @@ export function run(msg, data) { case "voice": { const servers = [...this.players.playerMap.entries()].map(([cid, s]) => { const channel = this.client.channels.get(cid); + const conn = s.connection; + const room = conn?.room; + const roomState = room?.state ?? "no-room"; + const hasMediaPlayer = !!s._mediaPlayer && !s._mediaPlayer?.destroyed; return { name: channel?.name ?? "unknown", id: channel?.id ?? cid, - status: s.connection?.state?.status ?? "unknown", + channelId: s._channelId ?? cid, + guildId: s._guildId ?? "unknown", guildname: channel?.guild?.name ?? "unknown", - guildid: channel?.guildId ?? "unknown" + conn: conn ? "yes" : "null", + roomState, + mediaPlayer: hasMediaPlayer ? "alive" : (s._mediaPlayer?.destroyed ? "destroyed" : "none"), + destroyed: s._destroyed ?? false, + leaving: s.leaving ?? false, + joining: s._isJoining ?? false, + recovering: s._isRecovering ?? false, + paused: s._paused ?? false, + hasQueue: !!(s.queue?.getCurrent() || !s.queue?.isEmpty()), + home247: s._home247Channel ?? null, }; }); + const pending = [...(this.players._pendingJoins ?? [])]; + const summary = { + playerMapSize: this.players.playerMap.size, + livePlayers: servers.filter(s => s.conn === "yes" && !s.destroyed && !s.leaving).length, + pendingJoins: pending.length, + pendingChannels: pending, + }; const embed = new EmbedBuilder() .setColor(getGlobalColor()) .setTitle(this.t(msg, "responses.debug.voiceTitle")) - .setDescription("```json\n" + JSON.stringify(servers, null, 2) + "\n```") + .setDescription("```json\n" + JSON.stringify({ summary, servers }, null, 2) + "\n```") ; msg.reply({ embeds: [embed] }); break; diff --git a/commands/join.mjs b/commands/join.mjs index 11cbf35..198bc53 100644 --- a/commands/join.mjs +++ b/commands/join.mjs @@ -89,16 +89,23 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { message.channel.send({ embeds: [embed] }); }); - this.players.playerMap.set(cleanChannelId, p); + // Mark as pending so concurrent commands see the channel is taken, + // but don't add to playerMap until join() succeeds to avoid phantom + // entries inflating the player count. + this.players._pendingJoins.add(cleanChannelId); const joiningEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joining")); const statusMsg = await message.reply({ embeds: [joiningEmbed] }); try { await p.join(cleanChannelId); + // Only add to playerMap after join succeeds + this.players.playerMap.set(cleanChannelId, p); + this.players._pendingJoins.delete(cleanChannelId); const okEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joined", { channel: cid })); await statusMsg.edit({ embeds: [okEmbed] }); cb(p); } catch (e) { + this.players._pendingJoins.delete(cleanChannelId); this.players.playerMap.delete(cleanChannelId); p.destroy(); const errEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joinFailed", { error: e.message })); diff --git a/commands/stats.mjs b/commands/stats.mjs index 30078ba..86b012f 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -73,18 +73,44 @@ function getUserCount(client) { } function getLivePlayerCount(playerMap) { - const liveChannels = new Set(); + let live = 0; + const seenGuilds = new Set(); for (const [mapKey, player] of playerMap ?? []) { + // Skip null / destroyed / leaving entries if (!player || player._destroyed || player.leaving) continue; - const channelId = String(player._channelId ?? mapKey ?? "").replace(/\D/g, ""); - if (!channelId) continue; + // Skip players still in the join() phase — they don't have a voice + // connection yet and may fail to connect. + if (player._isJoining) continue; - liveChannels.add(channelId); + // A player is only "live" if it has an actual voice connection. + // Stale entries (gateway disconnect, LiveKit drop) that haven't been + // cleaned up yet will have connection = null or a dead room state. + const conn = player.connection; + if (conn) { + const room = conn.room; + if (room) { + const state = room.state; + // Explicitly dead states → skip + if (state === "disconnected" || state === "failed" || state === 0) continue; + // undefined = connected on some LiveKit builds (no persistent state prop) + // "connected" = explicitly connected + } + // conn exists but no room → still a valid LiveKit connection reference + } else { + // No connection at all → not live + continue; + } + + live++; + + // Also track unique guilds so we can report server count + const guildId = String(player._guildId ?? "").replace(/\D/g, ""); + if (guildId) seenGuilds.add(guildId); } - return liveChannels.size; + return live; } // ── Embed builder ───────────────────────────────────────────────────────────── diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 194ea03..8436516 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -84,6 +84,9 @@ export class PlayerManager { /** @type {Map} */ playerMap = new Map(); + /** @type {Set} Channel IDs currently being joined (not yet in playerMap) */ + _pendingJoins = new Set(); + /** @type {Object} */ config; @@ -459,6 +462,10 @@ export class PlayerManager { player.textChannel = message.channel; return player; } + // Also check if a join is in-progress for this channel + if (this._pendingJoins.has(cleanUserChannelId)) { + return null; // A player is being created — caller should retry + } } const serverPlayers = cleanGuildId @@ -684,6 +691,10 @@ export class PlayerManager { cb(existing); return message.reply(mkEmbed(this._t(message, "responses.join.alreadyJoined", { channel: cid }))); } + // Also block if a join is already in-progress for this channel + if (this._pendingJoins.has(cleanChannelId)) { + return message.reply(mkEmbed(this._t(message, "responses.join.joining"))); + } const player = new Player(this.config.token, { ...this.playerConfig, @@ -770,12 +781,21 @@ export class PlayerManager { if (typeof ch?.send === "function") ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)); }); - this.playerMap.set(cleanChannelId, player); + // Mark as "pending join" so concurrent getPlayer() / checkVoiceChannels() + // calls can see a player is being created for this channel, but stats + // won't count it until the join actually succeeds. + this._pendingJoins.add(cleanChannelId); (async () => { const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining"))); try { await player.join(cid); + + // Only add to playerMap after join succeeds — this prevents phantom + // entries from inflating the player count. + this.playerMap.set(cleanChannelId, player); + this._pendingJoins.delete(cleanChannelId); + await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid }))); const guildId = cleanId(channel.guildId ?? getMessageGuildId(message)); @@ -789,6 +809,8 @@ export class PlayerManager { cb(player); } catch (err) { + this._pendingJoins.delete(cleanChannelId); + const errCode = sanitizeJoinError(err); let errorMsg; if (errCode === "PERMISSION") {