idk is that work

This commit is contained in:
NoLogicAlan committed 2026-05-14 16:15:29 +03:00
1 parent 48bebc950d
commit fdd3789898
2 files changed
+146 -24

No files matched your search

+132 -22
View File
@@ -12,7 +12,7 @@ export const command = new CommandBuilder()
// ── Stats cache ────────────────────────────────────────────────────────────── // ── Stats cache ──────────────────────────────────────────────────────────────
const CACHE_TTL_MS = 5 * 60 * 1000; const CACHE_TTL_MS = 5 * 60 * 1000;
const FAST_WAIT_MS = 1_500; const FAST_WAIT_MS = 8_000;
let cachedStats = null; // { guildCount, userCount } let cachedStats = null; // { guildCount, userCount }
let cacheExpiresAt = 0; let cacheExpiresAt = 0;
@@ -25,25 +25,65 @@ function withTimeout(promise, ms, fallback) {
]); ]);
} }
function computeUserCount(client) { async function pool(limit, tasks) {
let total = 0; const results = [];
for (const [, guild] of client.guilds ?? []) { const executing = new Set();
total += guild.memberCount ?? guild.members?.size ?? 0; for (const task of tasks) {
const p = Promise.resolve()
.then(task)
.then((value) => {
results.push(value);
executing.delete(p);
})
.catch(() => {
results.push(0);
executing.delete(p);
});
executing.add(p);
if (executing.size >= limit) await Promise.race(executing);
} }
return total; await Promise.all(executing);
return results;
}
function computeUserCount(client) {
const uniqueUsers = new Set();
for (const [, guild] of client.guilds ?? []) {
const members = guild?.members;
const iterable = typeof members?.values === "function"
? members.values()
: Array.isArray(members)
? members
: Object.values(members ?? {});
for (const member of iterable) {
const id = member?.id ?? member?.user?.id ?? null;
if (id) uniqueUsers.add(String(id));
}
}
return uniqueUsers.size;
} }
async function fetchAccurateGuildCount(client) { async function fetchAccurateGuildCount(client) {
if (typeof client?.user?.fetchGuilds === "function") {
try {
const guilds = await withTimeout(client.user.fetchGuilds(), 4_000, null);
if (Array.isArray(guilds)) return guilds.length;
if (typeof guilds?.size === "number") return guilds.size;
if (typeof guilds?.values === "function") return [...guilds.values()].length;
} catch (_) {}
}
if (typeof client.fetchTotalGuildCount === "function") { if (typeof client.fetchTotalGuildCount === "function") {
try { try {
const count = await withTimeout(client.fetchTotalGuildCount(), 1_200, null); const count = await withTimeout(client.fetchTotalGuildCount(), 4_000, null);
if (typeof count === "number" && count >= 0) return count; if (typeof count === "number" && count >= 0) return count;
} catch (_) {} } catch (_) {}
} }
if (typeof client.fetchAllStats === "function") { if (typeof client.fetchAllStats === "function") {
try { try {
const stats = await withTimeout(client.fetchAllStats(), 1_500, null); const stats = await withTimeout(client.fetchAllStats(), 4_000, null);
if (typeof stats?.guilds === "number" && stats.guilds >= 0) return stats.guilds; if (typeof stats?.guilds === "number" && stats.guilds >= 0) return stats.guilds;
} catch (_) {} } catch (_) {}
} }
@@ -69,16 +109,55 @@ async function fetchAccurateGuildCount(client) {
return client.guilds?.size ?? 0; return client.guilds?.size ?? 0;
} }
async function fetchAccurateUserCount(client) { async function fetchGuildMemberIds(guild) {
if (typeof client.fetchAllStats === "function") {
try { try {
const stats = await withTimeout(client.fetchAllStats(), 1_500, null); let after = undefined;
if (typeof stats?.users === "number" && stats.users >= 0) return stats.users; const ids = new Set();
if (typeof stats?.members === "number" && stats.members >= 0) return stats.members; for (let page = 0; page < 1000; page++) {
} catch (_) {} const raw = await guild.members.fetch({ limit: 1000, after });
const batch = Array.isArray(raw)
? raw
: typeof raw?.values === "function"
? [...raw.values()]
: Object.values(raw ?? {});
for (const member of batch) {
const id = member?.id ?? member?.user?.id ?? null;
if (id) ids.add(String(id));
} }
if (batch.length < 1000) break;
after = batch.reduce((max, member) => {
const id = member.id ?? member.user?.id ?? "";
return id > max ? id : max;
}, "0");
if (!after) break;
}
return ids;
} catch {
const ids = new Set();
const members = guild?.members;
const iterable = typeof members?.values === "function"
? members.values()
: Array.isArray(members)
? members
: Object.values(members ?? {});
for (const member of iterable) {
const id = member?.id ?? member?.user?.id ?? null;
if (id) ids.add(String(id));
}
return ids;
}
}
return computeUserCount(client); async function fetchAccurateUserCount(client) {
const guilds = [...(client.guilds?.values?.() ?? [])];
if (guilds.length === 0) return 0;
const idSets = await pool(8, guilds.map((guild) => () => fetchGuildMemberIds(guild)));
const uniqueUsers = new Set();
for (const idSet of idSets) {
if (!idSet || typeof idSet[Symbol.iterator] !== "function") continue;
for (const id of idSet) uniqueUsers.add(String(id));
}
return uniqueUsers.size;
} }
async function refreshStats(client) { async function refreshStats(client) {
@@ -188,9 +267,33 @@ function buildEmbed(t, msg, {
return builder; return builder;
} }
async function safeEditStatsMessage(messageRef, payload, fallbackMessage) {
try {
if (messageRef && typeof messageRef.edit === "function") {
await messageRef.edit(payload);
return true;
}
if (messageRef?.message && typeof messageRef.message.edit === "function") {
await messageRef.message.edit(payload);
return true;
}
} catch (err) {
console.error("[stats] edit failed:", err);
}
try {
await fallbackMessage.reply(payload);
return false;
} catch (err) {
console.error("[stats] fallback reply failed:", err);
return false;
}
}
// ── Runner ──────────────────────────────────────────────────────────────────── // ── Runner ────────────────────────────────────────────────────────────────────
export async function run(message) { export async function run(message) {
try {
const lastfm = this.lastfm; const lastfm = this.lastfm;
const lastfmEnabled = lastfm?.enabled ?? false; const lastfmEnabled = lastfm?.enabled ?? false;
const lastfmSnapshot = getLastfmSnapshot(lastfm); const lastfmSnapshot = getLastfmSnapshot(lastfm);
@@ -218,11 +321,11 @@ export async function run(message) {
lastfm.getStoredTotalScrobbles?.() ?? Promise.resolve(lastfmSnapshot.scrobbleCount), lastfm.getStoredTotalScrobbles?.() ?? Promise.resolve(lastfmSnapshot.scrobbleCount),
3_000, 3_000,
lastfmSnapshot.scrobbleCount lastfmSnapshot.scrobbleCount
) ).catch(() => lastfmSnapshot.scrobbleCount)
: Promise.resolve(0); : Promise.resolve(0);
const linkedPromise = lastfmEnabled const linkedPromise = lastfmEnabled
? withTimeout(lastfm.getLinkedUsersCount(), FAST_WAIT_MS, lastfmSnapshot.linkedUsers) ? withTimeout(lastfm.getLinkedUsersCount(), FAST_WAIT_MS, lastfmSnapshot.linkedUsers).catch(() => lastfmSnapshot.linkedUsers)
: Promise.resolve(0); : Promise.resolve(0);
const start = Date.now(); const start = Date.now();
@@ -238,20 +341,27 @@ export async function run(message) {
const ping = Date.now() - start; const ping = Date.now() - start;
const [stats, scrobbleCount, linkedUsers] = await Promise.all([ const [stats, scrobbleCount, linkedUsers] = await Promise.all([
withTimeout(getStats(this.client), FAST_WAIT_MS, statsFallback), getStats(this.client).catch(() => statsFallback),
scrobblePromise, scrobblePromise,
linkedPromise, linkedPromise,
]); ]);
await msg.edit({ await safeEditStatsMessage(msg, {
embeds: [buildEmbed((...args) => this.t(...args), message, { embeds: [buildEmbed((...args) => this.t(...args), message, {
...shared, ...shared,
guildCount: stats.guildCount, guildCount: stats?.guildCount ?? statsFallback.guildCount,
userCount: stats.userCount, userCount: stats?.userCount ?? statsFallback.userCount,
scrobbleCount, scrobbleCount,
linkedUsers, linkedUsers,
ping, ping,
loading: false, loading: false,
})], })],
}).catch((err) => console.error("[stats] editEmbed failed:", err)); }, message);
} catch (err) {
console.error("[stats] run failed:", err);
const fallback = new EmbedBuilder()
.setColor(getGlobalColor())
.setDescription("Failed to load full stats. Please try again in a moment.");
await message.reply({ embeds: [fallback] }).catch(() => {});
}
} }
+14 -2
View File
@@ -1332,10 +1332,22 @@ export default 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); const joinMsg = String(e?.message ?? e ?? "");
const isPermissionJoinFailure =
joinMsg.includes("401") ||
joinMsg.includes("Unauthorized") ||
joinMsg.includes("no permissions to access the room") ||
joinMsg.includes("signal failure: client error") ||
joinMsg.includes("active 401 cooldown");
if (isPermissionJoinFailure) {
logger.warn(`[Player] Join blocked for ${channelId}: ${joinMsg}`);
} else {
logger.error("[Player] Join failed:", joinMsg, causeStr);
}
// Track the disconnect reason for smarter recovery decisions // Track the disconnect reason for smarter recovery decisions
if (e.message?.includes("401") || e.message?.includes("Unauthorized")) { if (joinMsg.includes("401") || joinMsg.includes("Unauthorized")) {
this._lastDisconnectReason = "401"; this._lastDisconnectReason = "401";
this._lastDisconnectTime = Date.now(); this._lastDisconnectTime = Date.now();
} }