mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
great and not great
This commit is contained in:
1 parent
ed622ee453
commit
a78edeaa9a
4 files changed
+313
-238
No files matched your search
+273
-219
@@ -9,166 +9,186 @@ export const command = new CommandBuilder()
|
|||||||
.addAliases("info")
|
.addAliases("info")
|
||||||
.setCategory("util");
|
.setCategory("util");
|
||||||
|
|
||||||
// ── Constants ─────────────────────────────────────────────────────────────────
|
// ── Stats cache ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 min cache lifetime
|
const CACHE_TTL_MS = 5 * 60 * 1000;
|
||||||
const MEMBER_FETCH_LIMIT = 1_000; // Discord max per page
|
const FAST_WAIT_MS = 8_000;
|
||||||
const POOL_CONCURRENCY = 6; // guilds fetched in parallel
|
|
||||||
const GUILD_FETCH_MS = 4_000; // timeout per guild member fetch
|
|
||||||
const TOTAL_STATS_MS = 15_000; // hard cap for the whole refresh
|
|
||||||
const SCROBBLE_MS = 3_000;
|
|
||||||
const LINKED_MS = 5_000;
|
|
||||||
|
|
||||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
let cachedStats = null; // { guildCount, userCount }
|
||||||
|
let cacheExpiresAt = 0;
|
||||||
|
let inflightPromise = null;
|
||||||
|
|
||||||
/** Resolve `promise` within `ms`, otherwise return `fallback`. */
|
function getMessageGuildId(message) {
|
||||||
|
return message?.channel?.channel?.guildId ??
|
||||||
|
message?.message?.guildId ??
|
||||||
|
message?.guildId ??
|
||||||
|
null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTranslator(remix) {
|
||||||
|
return (message, key, data = {}) => {
|
||||||
|
const guildId = getMessageGuildId(message);
|
||||||
|
return remix?.locale?.translate?.(guildId, key, data) ?? key;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function withTimeout(promise, ms, fallback) {
|
function withTimeout(promise, ms, fallback) {
|
||||||
let timer;
|
|
||||||
return Promise.race([
|
return Promise.race([
|
||||||
promise,
|
promise,
|
||||||
new Promise((resolve) => { timer = setTimeout(() => resolve(fallback), ms); }),
|
new Promise((resolve) => setTimeout(() => resolve(fallback), ms)),
|
||||||
]).finally(() => clearTimeout(timer));
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Run `tasks` (thunks) with at most `limit` in flight at once. */
|
|
||||||
async function pool(limit, tasks) {
|
async function pool(limit, tasks) {
|
||||||
const results = [];
|
const results = [];
|
||||||
const executing = new Set();
|
const executing = new Set();
|
||||||
|
|
||||||
for (const task of tasks) {
|
for (const task of tasks) {
|
||||||
const p = Promise.resolve()
|
const p = Promise.resolve()
|
||||||
.then(task)
|
.then(task)
|
||||||
.then((v) => { results.push(v); })
|
.then((value) => {
|
||||||
.catch(() => { results.push(new Set()); }) // never let one guild crash all
|
results.push(value);
|
||||||
.finally(() => executing.delete(p));
|
executing.delete(p);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
results.push(0);
|
||||||
|
executing.delete(p);
|
||||||
|
});
|
||||||
executing.add(p);
|
executing.add(p);
|
||||||
if (executing.size >= limit) await Promise.race(executing);
|
if (executing.size >= limit) await Promise.race(executing);
|
||||||
}
|
}
|
||||||
|
|
||||||
await Promise.all(executing);
|
await Promise.all(executing);
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Member counting ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
/** Fast path: count from whatever is already cached in memory. */
|
|
||||||
function computeUserCount(client) {
|
function computeUserCount(client) {
|
||||||
const uniqueUsers = new Set();
|
const uniqueUsers = new Set();
|
||||||
const guilds = client?.guilds?.cache ?? client?.guilds ?? [];
|
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 guild of (guilds.values ? guilds.values() : guilds)) {
|
for (const member of iterable) {
|
||||||
const members = guild?.members?.cache ?? guild?.members ?? [];
|
const id = member?.id ?? member?.user?.id ?? null;
|
||||||
const iter = members.values ? members.values() : Object.values(members);
|
|
||||||
for (const m of iter) {
|
|
||||||
const id = m?.id ?? m?.user?.id;
|
|
||||||
if (id) uniqueUsers.add(String(id));
|
if (id) uniqueUsers.add(String(id));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return uniqueUsers.size;
|
return uniqueUsers.size;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
async function fetchAccurateGuildCount(client) {
|
||||||
* Fetch all member IDs for one guild, paginating if needed.
|
if (typeof client?.user?.fetchGuilds === "function") {
|
||||||
* Wrapped with a per-guild timeout so a slow shard can't block everything.
|
try {
|
||||||
*/
|
const guilds = await withTimeout(client.user.fetchGuilds(), 4_000, null);
|
||||||
async function fetchGuildMemberIds(guild) {
|
if (Array.isArray(guilds)) return guilds.length;
|
||||||
const ids = new Set();
|
if (typeof guilds?.size === "number") return guilds.size;
|
||||||
|
if (typeof guilds?.values === "function") return [...guilds.values()].length;
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
const doFetch = async () => {
|
if (typeof client.fetchTotalGuildCount === "function") {
|
||||||
if (!guild?.members?.fetch) throw new Error("no fetch");
|
try {
|
||||||
|
const count = await withTimeout(client.fetchTotalGuildCount(), 4_000, null);
|
||||||
|
if (typeof count === "number" && count >= 0) return count;
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
let after = "0";
|
if (typeof client.fetchAllStats === "function") {
|
||||||
while (true) {
|
try {
|
||||||
const batch = await guild.members.fetch({ limit: MEMBER_FETCH_LIMIT, after });
|
const stats = await withTimeout(client.fetchAllStats(), 4_000, null);
|
||||||
const items = batch?.values ? [...batch.values()] : (Array.isArray(batch) ? batch : []);
|
if (typeof stats?.guilds === "number" && stats.guilds >= 0) return stats.guilds;
|
||||||
if (!items.length) break;
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
let lastId = "0";
|
if (client.rest && typeof client.rest.get === "function") {
|
||||||
for (const m of items) {
|
try {
|
||||||
const id = String(m.id ?? m.user?.id ?? "");
|
let total = 0;
|
||||||
if (id) { ids.add(id); if (id > lastId) lastId = id; }
|
let after = undefined;
|
||||||
|
for (let page = 0; page < 25; page++) {
|
||||||
|
const route = `/users/@me/guilds?limit=200${after ? `&after=${after}` : ""}`;
|
||||||
|
const response = await withTimeout(client.rest.get(route), 800, null);
|
||||||
|
if (!response) break;
|
||||||
|
const batch = Array.isArray(response) ? response : (response?.guilds ?? []);
|
||||||
|
total += batch.length;
|
||||||
|
if (batch.length < 200) break;
|
||||||
|
after = batch[batch.length - 1]?.id;
|
||||||
|
if (!after) break;
|
||||||
}
|
}
|
||||||
if (items.length < MEMBER_FETCH_LIMIT) break;
|
if (total > 0) return total;
|
||||||
after = lastId;
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
return client.guilds?.size ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchGuildMemberIds(guild) {
|
||||||
|
try {
|
||||||
|
let after = undefined;
|
||||||
|
const ids = new Set();
|
||||||
|
for (let page = 0; page < 1000; page++) {
|
||||||
|
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;
|
return ids;
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
return await withTimeout(doFetch(), GUILD_FETCH_MS, ids);
|
|
||||||
} catch {
|
} catch {
|
||||||
// Fall back to cached members for this guild
|
const ids = new Set();
|
||||||
const members = guild?.members?.cache ?? guild?.members ?? [];
|
const members = guild?.members;
|
||||||
const iter = members.values ? members.values() : Object.values(members);
|
const iterable = typeof members?.values === "function"
|
||||||
for (const m of iter) {
|
? members.values()
|
||||||
const id = m?.id ?? m?.user?.id;
|
: 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));
|
if (id) ids.add(String(id));
|
||||||
}
|
}
|
||||||
return ids;
|
return ids;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fetch accurate guild count, with a fallback to cache size. */
|
|
||||||
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 (guilds?.size != null) return guilds.size;
|
|
||||||
} catch { /* fall through */ }
|
|
||||||
}
|
|
||||||
return client?.guilds?.cache?.size ?? client?.guilds?.size ?? 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Fetch accurate unique user count across all guilds.
|
|
||||||
* Hard-capped at TOTAL_STATS_MS so it can never hang the command.
|
|
||||||
*/
|
|
||||||
async function fetchAccurateUserCount(client) {
|
async function fetchAccurateUserCount(client) {
|
||||||
const guildsMap = client?.guilds?.cache ?? client?.guilds;
|
const guilds = [...(client.guilds?.values?.() ?? [])];
|
||||||
const guilds = guildsMap?.values ? [...guildsMap.values()] : [...(guildsMap ?? [])];
|
if (guilds.length === 0) return 0;
|
||||||
if (!guilds.length) return 0;
|
const idSets = await pool(8, guilds.map((guild) => () => fetchGuildMemberIds(guild)));
|
||||||
|
const uniqueUsers = new Set();
|
||||||
const idSets = await pool(
|
for (const idSet of idSets) {
|
||||||
POOL_CONCURRENCY,
|
if (!idSet || typeof idSet[Symbol.iterator] !== "function") continue;
|
||||||
guilds.map((g) => () => fetchGuildMemberIds(g))
|
for (const id of idSet) uniqueUsers.add(String(id));
|
||||||
);
|
}
|
||||||
|
return uniqueUsers.size;
|
||||||
const unique = new Set();
|
|
||||||
for (const set of idSets) for (const id of set) unique.add(id);
|
|
||||||
return unique.size;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Stats cache ───────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
let cachedStats = null;
|
|
||||||
let cacheExpiresAt = 0;
|
|
||||||
let inflightPromise = null;
|
|
||||||
|
|
||||||
async function refreshStats(client) {
|
async function refreshStats(client) {
|
||||||
try {
|
try {
|
||||||
const [guildCount, userCount] = await withTimeout(
|
cachedStats = {
|
||||||
Promise.all([
|
guildCount: await fetchAccurateGuildCount(client),
|
||||||
fetchAccurateGuildCount(client),
|
userCount: await fetchAccurateUserCount(client),
|
||||||
fetchAccurateUserCount(client),
|
};
|
||||||
]),
|
|
||||||
TOTAL_STATS_MS,
|
|
||||||
[
|
|
||||||
client?.guilds?.cache?.size ?? client?.guilds?.size ?? 0,
|
|
||||||
computeUserCount(client),
|
|
||||||
]
|
|
||||||
);
|
|
||||||
cachedStats = { guildCount, userCount };
|
|
||||||
} catch {
|
} catch {
|
||||||
cachedStats = {
|
cachedStats = {
|
||||||
guildCount: client?.guilds?.cache?.size ?? client?.guilds?.size ?? 0,
|
guildCount: client.guilds?.size ?? 0,
|
||||||
userCount: computeUserCount(client),
|
userCount: computeUserCount(client),
|
||||||
};
|
};
|
||||||
} finally {
|
|
||||||
cacheExpiresAt = Date.now() + CACHE_TTL_MS;
|
|
||||||
inflightPromise = null; // always clear so future calls can retry
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
cacheExpiresAt = Date.now() + CACHE_TTL_MS;
|
||||||
|
inflightPromise = null;
|
||||||
return cachedStats;
|
return cachedStats;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,151 +198,185 @@ function getStats(client) {
|
|||||||
return inflightPromise;
|
return inflightPromise;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Live player count ─────────────────────────────────────────────────────────
|
function getLastfmSnapshot(lastfm) {
|
||||||
|
return {
|
||||||
|
scrobbleCount: Number(lastfm?._totalScrobblesCache ?? 0),
|
||||||
|
linkedUsers: Number(lastfm?._linkedUsersCache ?? 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function getLivePlayerCount(playerMap) {
|
function getLivePlayerCount(playerMap) {
|
||||||
if (!playerMap) return 0;
|
|
||||||
let live = 0;
|
let live = 0;
|
||||||
const iter = playerMap.values ? playerMap.values() : Object.values(playerMap);
|
|
||||||
for (const player of iter) {
|
for (const [, player] of playerMap ?? []) {
|
||||||
if (!player || player._destroyed || player.leaving || player._isJoining) continue;
|
if (!player || player._destroyed || player.leaving) continue;
|
||||||
|
if (player._isJoining) continue;
|
||||||
|
|
||||||
const conn = player.connection;
|
const conn = player.connection;
|
||||||
if (!conn) continue;
|
if (!conn) continue;
|
||||||
|
|
||||||
const room = conn.room;
|
const room = conn.room;
|
||||||
if (room && !room.isConnected &&
|
if (room) {
|
||||||
(room.connectionState === 0 || room.connectionState === "disconnected")) continue;
|
const isConnected = room.isConnected;
|
||||||
|
const connectionState = room.connectionState;
|
||||||
|
if (!isConnected && (connectionState === 0 || connectionState === "disconnected")) continue;
|
||||||
|
}
|
||||||
|
|
||||||
live++;
|
live++;
|
||||||
}
|
}
|
||||||
|
|
||||||
return live;
|
return live;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Embed builder ─────────────────────────────────────────────────────────────
|
// ── Embed builder ─────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
function buildEmbed(translator, msg, data) {
|
function buildEmbed(t, msg, {
|
||||||
const {
|
guildCount,
|
||||||
guildCount, userCount, playerCount, scrobbleCount,
|
userCount,
|
||||||
linkedUsers, ping, uptime, comHash, comLink,
|
playerCount,
|
||||||
reason, footer, loading, lastfmEnabled,
|
scrobbleCount,
|
||||||
} = data;
|
linkedUsers,
|
||||||
|
ping,
|
||||||
|
uptime,
|
||||||
|
comHash,
|
||||||
|
comLink,
|
||||||
|
reason,
|
||||||
|
footer,
|
||||||
|
loading,
|
||||||
|
lastfmEnabled,
|
||||||
|
}) {
|
||||||
|
const num = (v) => Utils.formatNumber(v);
|
||||||
|
const ld = (v) => loading ? "..." : v;
|
||||||
|
|
||||||
const t = (key) => { try { return translator(msg, key); } catch { return key.split(".").pop(); } };
|
const description = [
|
||||||
const num = (v) => Utils.formatNumber(v ?? 0);
|
`${t(msg, "responses.stats.servers")} — \`${num(guildCount)}\``,
|
||||||
const ld = (v) => (loading ? "…" : v);
|
`${t(msg, "responses.stats.users")} — \`${ld(num(userCount))}\``,
|
||||||
|
`${t(msg, "responses.stats.players")} — \`${num(playerCount)}\``,
|
||||||
const lines = [
|
|
||||||
`${t("responses.stats.servers")} — \`${num(guildCount)}\``,
|
|
||||||
`${t("responses.stats.users")} — \`${ld(num(userCount))}\``,
|
|
||||||
`${t("responses.stats.players")} — \`${num(playerCount)}\``,
|
|
||||||
];
|
];
|
||||||
|
|
||||||
if (lastfmEnabled) {
|
if (lastfmEnabled) {
|
||||||
lines.push(
|
description.push(`${t(msg, "responses.stats.scrobbles")} — \`${ld(num(scrobbleCount))}\``);
|
||||||
`${t("responses.stats.scrobbles")} — \`${ld(num(scrobbleCount))}\``,
|
description.push(`${t(msg, "responses.stats.linkedUsers")} — \`${ld(num(linkedUsers))}\``);
|
||||||
`${t("responses.stats.linkedUsers")} — \`${ld(num(linkedUsers))}\``
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
lines.push(
|
description.push(
|
||||||
`${t("responses.stats.ping")} — \`${ld(`${num(ping)}ms`)}\``,
|
`${t(msg, "responses.stats.ping")} — \`${ld(`${num(ping)}ms`)}\``,
|
||||||
`${t("responses.stats.uptime")} — \`${uptime}\``,
|
`${t(msg, "responses.stats.uptime")} — \`${uptime}\``,
|
||||||
`${t("responses.stats.build")} — [\`${comHash || "N/A"}\`](${comLink || "#"})`
|
`${t(msg, "responses.stats.build")} — [\`${comHash}\`](${comLink})`,
|
||||||
|
reason ? `${t(msg, "responses.stats.lastRestart")} — \`${reason}\`` : null,
|
||||||
|
"",
|
||||||
|
t(msg, "responses.stats.supportKofi"),
|
||||||
|
t(msg, "responses.stats.community"),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (reason) lines.push(`${t("responses.stats.lastRestart")} — \`${reason}\``);
|
const desc = description.filter((line) => line !== null).join("\n");
|
||||||
|
|
||||||
lines.push("", t("responses.stats.supportKofi"), t("responses.stats.community"));
|
const builder = new EmbedBuilder()
|
||||||
|
|
||||||
return new EmbedBuilder()
|
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setAuthor({ name: t("responses.stats.title") })
|
.setAuthor({ name: t(msg, "responses.stats.title") })
|
||||||
.setDescription(lines.filter(Boolean).join("\n"))
|
.setDescription(desc)
|
||||||
.setFooter({ text: footer || t("responses.stats.title") })
|
.setFooter({ text: footer || t(msg, "responses.stats.title") });
|
||||||
.setTimestamp();
|
|
||||||
|
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
||||||
|
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) {
|
||||||
const lastfm = this.lastfm;
|
|
||||||
const lastfmEnabled = !!lastfm?.enabled;
|
|
||||||
const translator = typeof this.t === "function" ? this.t.bind(this) : (_m, k) => k;
|
|
||||||
|
|
||||||
const shared = {
|
|
||||||
playerCount: getLivePlayerCount(this.players?.playerMap),
|
|
||||||
scrobbleCount: Number(lastfm?._totalScrobblesCache ?? 0),
|
|
||||||
linkedUsers: Number(lastfm?._linkedUsersCache ?? 0),
|
|
||||||
lastfmEnabled,
|
|
||||||
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
|
|
||||||
comHash: this.comHash,
|
|
||||||
comLink: this.comLink,
|
|
||||||
reason: this.config?.restart ?? null,
|
|
||||||
footer: this.config?.customStatsFooter ?? null,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Use whatever we already have so the first reply is instant
|
|
||||||
const statsFallback = cachedStats ?? {
|
|
||||||
guildCount: this.client?.guilds?.cache?.size ?? this.client?.guilds?.size ?? 0,
|
|
||||||
userCount: computeUserCount(this.client),
|
|
||||||
};
|
|
||||||
|
|
||||||
// ── 1. Reply immediately with a loading embed ─────────────────────────────
|
|
||||||
let sentMsg;
|
|
||||||
const sendStart = Date.now();
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const loadingEmbed = buildEmbed(translator, message, {
|
const t = createTranslator(this);
|
||||||
...shared,
|
const lastfm = this.lastfm;
|
||||||
...statsFallback,
|
const lastfmEnabled = lastfm?.enabled ?? false;
|
||||||
ping: 0,
|
const lastfmSnapshot = getLastfmSnapshot(lastfm);
|
||||||
loading: !cachedStats,
|
|
||||||
|
const shared = {
|
||||||
|
guildCount: this.client.guilds?.size ?? 0,
|
||||||
|
playerCount: getLivePlayerCount(this.players.playerMap),
|
||||||
|
scrobbleCount: lastfmSnapshot.scrobbleCount,
|
||||||
|
linkedUsers: lastfmSnapshot.linkedUsers,
|
||||||
|
lastfmEnabled,
|
||||||
|
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
|
||||||
|
comHash: this.comHash,
|
||||||
|
comLink: this.comLink,
|
||||||
|
reason: this.config.restart ?? null,
|
||||||
|
footer: this.config.customStatsFooter || null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const statsFallback = cachedStats ?? {
|
||||||
|
guildCount: shared.guildCount,
|
||||||
|
userCount: computeUserCount(this.client),
|
||||||
|
};
|
||||||
|
|
||||||
|
const scrobblePromise = lastfmEnabled
|
||||||
|
? withTimeout(
|
||||||
|
lastfm.getStoredTotalScrobbles?.() ?? Promise.resolve(lastfmSnapshot.scrobbleCount),
|
||||||
|
3_000,
|
||||||
|
lastfmSnapshot.scrobbleCount
|
||||||
|
).catch(() => lastfmSnapshot.scrobbleCount)
|
||||||
|
: Promise.resolve(0);
|
||||||
|
|
||||||
|
const linkedPromise = lastfmEnabled
|
||||||
|
? withTimeout(lastfm.getLinkedUsersCount(), FAST_WAIT_MS, lastfmSnapshot.linkedUsers).catch(() => lastfmSnapshot.linkedUsers)
|
||||||
|
: Promise.resolve(0);
|
||||||
|
|
||||||
|
const start = Date.now();
|
||||||
|
const msg = await message.reply({
|
||||||
|
embeds: [buildEmbed(t, message, {
|
||||||
|
...shared,
|
||||||
|
guildCount: statsFallback.guildCount,
|
||||||
|
userCount: statsFallback.userCount,
|
||||||
|
ping: 0,
|
||||||
|
loading: !cachedStats,
|
||||||
|
})],
|
||||||
});
|
});
|
||||||
sentMsg = await message.reply({ embeds: [loadingEmbed] });
|
const ping = Date.now() - start;
|
||||||
} catch (err) {
|
|
||||||
console.error("[stats] initial reply failed:", err);
|
|
||||||
return; // nothing we can do without a message handle
|
|
||||||
}
|
|
||||||
|
|
||||||
const ping = Date.now() - sendStart;
|
const [stats, scrobbleCount, linkedUsers] = await Promise.all([
|
||||||
|
|
||||||
// ── 2. Fetch everything in parallel, all with timeouts ────────────────────
|
|
||||||
const scrobblePromise = lastfmEnabled && typeof lastfm.getStoredTotalScrobbles === "function"
|
|
||||||
? withTimeout(lastfm.getStoredTotalScrobbles(), SCROBBLE_MS, shared.scrobbleCount)
|
|
||||||
: Promise.resolve(shared.scrobbleCount);
|
|
||||||
|
|
||||||
const linkedPromise = lastfmEnabled && typeof lastfm.getLinkedUsersCount === "function"
|
|
||||||
? withTimeout(lastfm.getLinkedUsersCount(), LINKED_MS, shared.linkedUsers)
|
|
||||||
: Promise.resolve(shared.linkedUsers);
|
|
||||||
|
|
||||||
let stats, scrobbleCount, linkedUsers;
|
|
||||||
try {
|
|
||||||
[stats, scrobbleCount, linkedUsers] = await Promise.all([
|
|
||||||
getStats(this.client).catch(() => statsFallback),
|
getStats(this.client).catch(() => statsFallback),
|
||||||
scrobblePromise.catch(() => shared.scrobbleCount),
|
scrobblePromise,
|
||||||
linkedPromise.catch(() => shared.linkedUsers),
|
linkedPromise,
|
||||||
]);
|
]);
|
||||||
} catch (err) {
|
|
||||||
console.error("[stats] background fetch failed:", err);
|
|
||||||
stats = statsFallback;
|
|
||||||
scrobbleCount = shared.scrobbleCount;
|
|
||||||
linkedUsers = shared.linkedUsers;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── 3. Edit with the final data ───────────────────────────────────────────
|
await safeEditStatsMessage(msg, {
|
||||||
try {
|
embeds: [buildEmbed(t, message, {
|
||||||
const finalEmbed = buildEmbed(translator, message, {
|
...shared,
|
||||||
...shared,
|
guildCount: stats?.guildCount ?? statsFallback.guildCount,
|
||||||
guildCount: stats?.guildCount ?? statsFallback.guildCount,
|
userCount: stats?.userCount ?? statsFallback.userCount,
|
||||||
userCount: stats?.userCount ?? statsFallback.userCount,
|
scrobbleCount,
|
||||||
scrobbleCount,
|
linkedUsers,
|
||||||
linkedUsers,
|
ping,
|
||||||
ping,
|
loading: false,
|
||||||
loading: false,
|
})],
|
||||||
});
|
}, message);
|
||||||
|
|
||||||
if (typeof sentMsg?.edit === "function") {
|
|
||||||
await sentMsg.edit({ embeds: [finalEmbed] });
|
|
||||||
}
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error("[stats] edit failed:", 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(() => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -913,8 +913,21 @@ const isIgnorableWsCrash = (err) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const isAbortError = (err) => {
|
||||||
|
const name = String(err?.name ?? "");
|
||||||
|
const code = String(err?.code ?? "");
|
||||||
|
const message = String(err?.message ?? err ?? "");
|
||||||
|
return name === "AbortError" ||
|
||||||
|
code === "ABORT_ERR" ||
|
||||||
|
message.includes("This operation was aborted");
|
||||||
|
};
|
||||||
|
|
||||||
process.on("unhandledRejection", (reason, p) => {
|
process.on("unhandledRejection", (reason, p) => {
|
||||||
if (reason?.message?.includes("AudioSource is closed")) return;
|
if (reason?.message?.includes("AudioSource is closed")) return;
|
||||||
|
if (isAbortError(reason)) {
|
||||||
|
logger.warn("[Error_Handling] Suppressed AbortError from a timed-out request.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
logger.error("[Error_Handling] Unhandled Rejection/Catch");
|
logger.error("[Error_Handling] Unhandled Rejection/Catch");
|
||||||
logger.error("Reason:", reason, p);
|
logger.error("Reason:", reason, p);
|
||||||
});
|
});
|
||||||
@@ -924,11 +937,16 @@ process.on("uncaughtException", (err, origin) => {
|
|||||||
logger.warn("Error:", err?.stack ?? err, origin);
|
logger.warn("Error:", err?.stack ?? err, origin);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (isAbortError(err)) {
|
||||||
|
logger.warn("[Error_Handling] Suppressed AbortError from a timed-out request.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
logger.error("[Error_Handling] Uncaught Exception/Catch");
|
logger.error("[Error_Handling] Uncaught Exception/Catch");
|
||||||
logger.error("Error:", err, origin);
|
logger.error("Error:", err, origin);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
});
|
});
|
||||||
process.on("uncaughtExceptionMonitor", (err, origin) => {
|
process.on("uncaughtExceptionMonitor", (err, origin) => {
|
||||||
|
if (isAbortError(err)) return;
|
||||||
logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)");
|
logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)");
|
||||||
logger.error("Error:", err, origin);
|
logger.error("Error:", err, origin);
|
||||||
});
|
});
|
||||||
|
|||||||
+9
-11
@@ -1255,15 +1255,18 @@ export class GatewayHandler {
|
|||||||
`guild is 401-banned (${Math.round((banExpiry - Date.now()) / 1000)}s remaining).`
|
`guild is 401-banned (${Math.round((banExpiry - Date.now()) / 1000)}s remaining).`
|
||||||
);
|
);
|
||||||
// Remove the old player entry and destroy it
|
// Remove the old player entry and destroy it
|
||||||
|
const bannedPlayer = remix.players.playerMap.get(cleanOld);
|
||||||
remix.players.playerMap.delete(cleanOld);
|
remix.players.playerMap.delete(cleanOld);
|
||||||
try { remix.players.playerMap.get(cleanOld)?.destroy(); } catch (_) {}
|
try { bannedPlayer?.destroy(); } catch (_) {}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Match the specific player by channel ID
|
// Match the specific player by channel ID
|
||||||
const player = remix.players.playerMap.get(cleanOld);
|
const player = remix.players.playerMap.get(cleanOld);
|
||||||
if (player && !player.leaving) {
|
if (player && !player.leaving) {
|
||||||
logger.voice247("[247] Fluxer gateway disconnected us. Forcing player recovery...");
|
logger.voice247(
|
||||||
|
`[247] Fluxer gateway disconnected ${cleanOld} in guild ${guildId} — scheduling 24/7 respawn.`
|
||||||
|
);
|
||||||
|
|
||||||
// Set a gateway disconnect cooldown for this guild to
|
// Set a gateway disconnect cooldown for this guild to
|
||||||
// prevent recovery cascades. If recovery rejoins and the
|
// prevent recovery cascades. If recovery rejoins and the
|
||||||
@@ -1273,17 +1276,12 @@ export class GatewayHandler {
|
|||||||
// Auto-clear the cooldown after 30 seconds
|
// Auto-clear the cooldown after 30 seconds
|
||||||
setTimeout(() => this._gatewayDisconnectCooldown.delete(cleanGuild), 30_000);
|
setTimeout(() => this._gatewayDisconnectCooldown.delete(cleanGuild), 30_000);
|
||||||
|
|
||||||
// Mark the disconnect reason on the player for smarter recovery
|
// Mark the disconnect reason before shutting the player down.
|
||||||
player._lastDisconnectReason = "gateway";
|
player._lastDisconnectReason = "gateway";
|
||||||
player._lastDisconnectTime = Date.now();
|
player._lastDisconnectTime = Date.now();
|
||||||
|
remix.players.playerMap.delete(cleanOld);
|
||||||
if (typeof player._recoverConnection === "function") {
|
try { player.destroy(); } catch (_) {}
|
||||||
player._recoverConnection();
|
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect");
|
||||||
} else {
|
|
||||||
remix.players.playerMap.delete(cleanOld);
|
|
||||||
try { player.destroy(); } catch (_) {}
|
|
||||||
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect");
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect");
|
this.recoveryManager.scheduleSpawn(guildId, cleanOld, this.T.rejoin247Delay, "gateway-disconnect");
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-8
@@ -372,18 +372,16 @@ export class PlayerManager {
|
|||||||
const seedObserved = (channelId) => {
|
const seedObserved = (channelId) => {
|
||||||
const cleanChannelId = cleanId(channelId);
|
const cleanChannelId = cleanId(channelId);
|
||||||
if (!cleanChannelId) return null;
|
if (!cleanChannelId) return null;
|
||||||
if (!this.observedVoiceUsers?.has(userId)) {
|
const current = this.observedVoiceUsers?.get?.(userId) ?? null;
|
||||||
|
if (
|
||||||
|
cleanId(current?.guildId) !== cleanGuild ||
|
||||||
|
cleanId(current?.channelId) !== cleanChannelId
|
||||||
|
) {
|
||||||
this.observedVoiceUsers?.set(userId, { channelId: cleanChannelId, guildId: cleanGuild });
|
this.observedVoiceUsers?.set(userId, { channelId: cleanChannelId, guildId: cleanGuild });
|
||||||
}
|
}
|
||||||
return cleanId(this.observedVoiceUsers?.get(userId)?.channelId) || cleanChannelId;
|
return cleanChannelId;
|
||||||
};
|
};
|
||||||
|
|
||||||
const observed = this.observedVoiceUsers?.get?.(userId);
|
|
||||||
if (cleanId(observed?.guildId) === cleanGuild) {
|
|
||||||
const observedChannelId = cleanId(observed?.channelId);
|
|
||||||
if (observedChannelId) return observedChannelId;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const vm = getVoiceManager(this.commands.client);
|
const vm = getVoiceManager(this.commands.client);
|
||||||
const voiceChannelId = vm?.getVoiceChannelId?.(guildId, userId);
|
const voiceChannelId = vm?.getVoiceChannelId?.(guildId, userId);
|
||||||
@@ -479,6 +477,13 @@ export class PlayerManager {
|
|||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const observed = this.observedVoiceUsers?.get?.(userId);
|
||||||
|
if (cleanId(observed?.guildId) === cleanGuild) {
|
||||||
|
const observedChannelId = cleanId(observed?.channelId);
|
||||||
|
if (observedChannelId) return observedChannelId;
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user