mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
...little changes
This commit is contained in:
1 parent
bdf7221366
commit
0f085a6ae4
1 file changed
+268
-158
+268
-158
@@ -3,6 +3,8 @@
|
|||||||
* @description Display bot statistics including guild count, user count, uptime, and ping.
|
* @description Display bot statistics including guild count, user count, uptime, and ping.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import * as fs from "node:fs";
|
||||||
|
import * as path from "node:path";
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/Utils.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
@@ -19,89 +21,188 @@ export const command = new CommandBuilder()
|
|||||||
.addAliases("info")
|
.addAliases("info")
|
||||||
.setCategory("util");
|
.setCategory("util");
|
||||||
|
|
||||||
|
/** Cache is considered fresh for this long; older values trigger a background refresh. */
|
||||||
const CACHE_TTL_MS = 5 * 60 * 1000;
|
const CACHE_TTL_MS = 5 * 60 * 1000;
|
||||||
|
/** Max time the fill-in edit waits for Last.fm values before giving up (next run shows them). */
|
||||||
|
const LASTFM_FILL_BUDGET_MS = 2500;
|
||||||
|
/** Max time the fill-in edit waits for the background refresh to produce a user count. */
|
||||||
|
const REFRESH_FILL_BUDGET_MS = 10_000;
|
||||||
|
/** How many times a rate-limited message send is retried before giving up. */
|
||||||
|
const RATE_LIMIT_MAX_RETRIES = 2;
|
||||||
|
/** Upper bound for a single rate-limit backoff wait. */
|
||||||
|
const RATE_LIMIT_MAX_WAIT_MS = 15_000;
|
||||||
|
/** Where the warm cache is persisted (cwd-relative, same convention as ./storage/defaults.json). */
|
||||||
|
const CACHE_FILE = path.join(process.cwd(), "storage", "stats-cache.json");
|
||||||
|
|
||||||
let cachedUserCount = null;
|
let cache = { guilds: null, users: null, scrobbles: null, linkedUsers: null, updatedAt: 0 };
|
||||||
let cacheExpiresAt = 0;
|
let lastPing = null;
|
||||||
let inflightPromise = null;
|
let refreshInflight = null;
|
||||||
|
|
||||||
/**
|
try {
|
||||||
* Run tasks with a concurrency limit.
|
const raw = JSON.parse(fs.readFileSync(CACHE_FILE, "utf8"));
|
||||||
* @private
|
cache = {
|
||||||
* @param {number} limit - Maximum number of concurrent tasks.
|
guilds: typeof raw?.guilds === "number" ? raw.guilds : null,
|
||||||
* @param {Function[]} tasks - Array of task functions to execute.
|
users: typeof raw?.users === "number" ? raw.users : null,
|
||||||
* @returns {Promise<unknown[]>} Array of task results.
|
scrobbles: typeof raw?.scrobbles === "number" ? raw.scrobbles : null,
|
||||||
*/
|
linkedUsers: typeof raw?.linkedUsers === "number" ? raw.linkedUsers : null,
|
||||||
async function pool(limit, tasks) {
|
updatedAt: typeof raw?.updatedAt === "number" ? raw.updatedAt : 0,
|
||||||
const results = [];
|
};
|
||||||
const executing = new Set();
|
} catch {
|
||||||
for (const task of tasks) {
|
/* first run or unreadable cache — start cold, warm up in background */
|
||||||
const p = Promise.resolve().then(task).then(r => { results.push(r); executing.delete(p); });
|
|
||||||
executing.add(p);
|
|
||||||
if (executing.size >= limit) await Promise.race(executing);
|
|
||||||
}
|
|
||||||
await Promise.all(executing);
|
|
||||||
return results;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Persist the current cache to disk so the next restart serves warm data. @private */
|
||||||
* Fetch the total member count for a guild by paginating through members.
|
function persistCache() {
|
||||||
* @private
|
|
||||||
* @async
|
|
||||||
* @param {object} guild - The Discord guild object.
|
|
||||||
* @returns {Promise<number>} Total member count.
|
|
||||||
*/
|
|
||||||
async function fetchGuildMemberCount(guild) {
|
|
||||||
try {
|
try {
|
||||||
let after = undefined;
|
fs.mkdirSync(path.dirname(CACHE_FILE), { recursive: true });
|
||||||
let total = 0;
|
fs.writeFileSync(CACHE_FILE, JSON.stringify(cache));
|
||||||
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 ?? {});
|
|
||||||
total += batch.length;
|
|
||||||
if (batch.length < 1000) break;
|
|
||||||
after = batch.reduce((max, m) => {
|
|
||||||
const id = m.id ?? m.user?.id ?? "";
|
|
||||||
return id > max ? id : max;
|
|
||||||
}, "0");
|
|
||||||
}
|
|
||||||
return total;
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[Stats] Error:", e?.message);
|
logger.warn("[Stats] Failed to persist stats cache:", e?.message);
|
||||||
return guild.memberCount ?? guild.members?.size ?? 0;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Refresh the cached total user count across all guilds.
|
* Sum guild and member totals directly from the gateway cache.
|
||||||
|
* memberCount comes with every guild payload, so no member listing is needed.
|
||||||
* @private
|
* @private
|
||||||
* @async
|
* @param {object} client - The client instance.
|
||||||
* @param {object} client - The Discord client instance.
|
* @returns {{guilds: number, users: number}} Instant totals.
|
||||||
* @returns {Promise<number>} Total user count.
|
|
||||||
*/
|
*/
|
||||||
async function refreshUserCount(client) {
|
function computeInstantTotals(client) {
|
||||||
const guilds = [...client.guilds.values()];
|
let guilds = 0;
|
||||||
const counts = await pool(10, guilds.map(g => () => fetchGuildMemberCount(g)));
|
let users = 0;
|
||||||
cachedUserCount = counts.reduce((a, b) => a + b, 0);
|
for (const guild of client.guilds.values()) {
|
||||||
cacheExpiresAt = Date.now() + CACHE_TTL_MS;
|
guilds++;
|
||||||
inflightPromise = null;
|
users += guild.memberCount ?? guild.members?.size ?? 0;
|
||||||
return cachedUserCount;
|
}
|
||||||
|
return { guilds, users };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the total user count, using cache if still valid or refreshing if expired.
|
* Resolve the totals to display right now, merging the gateway cache with the
|
||||||
|
* last known values. While the cache is fresh, the higher of the two smooths
|
||||||
|
* over guilds still streaming in; the background refresh rewrites cache.users
|
||||||
|
* with the pure gateway sum so counts still drop when members leave.
|
||||||
* @private
|
* @private
|
||||||
* @param {object} client - The Discord client instance.
|
* @param {object} client - The client instance.
|
||||||
* @returns {Promise<number>} Total user count.
|
* @returns {{guildCount: number, userCount: number, needsLoading: boolean}}
|
||||||
*/
|
*/
|
||||||
function getUserCount(client) {
|
function getTotals(client) {
|
||||||
if (cachedUserCount !== null && Date.now() < cacheExpiresAt) return Promise.resolve(cachedUserCount);
|
const instant = computeInstantTotals(client);
|
||||||
if (!inflightPromise) inflightPromise = refreshUserCount(client);
|
const cacheFresh = cache.updatedAt > 0 && Date.now() - cache.updatedAt < CACHE_TTL_MS;
|
||||||
return inflightPromise;
|
|
||||||
|
const guildCount = instant.guilds || cache.guilds || 0;
|
||||||
|
const userCount = cacheFresh
|
||||||
|
? Math.max(instant.users || 0, cache.users || 0)
|
||||||
|
: instant.users;
|
||||||
|
|
||||||
|
const needsLoading = userCount === 0 && !cache.users;
|
||||||
|
return { guildCount, userCount, needsLoading };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Refresh the cache in the background if it is older than the TTL.
|
||||||
|
* Verifies the guild count via REST (covers guilds missing from the gateway
|
||||||
|
* cache) and warms the Last.fm totals. Results are persisted for restarts.
|
||||||
|
* @private
|
||||||
|
* @param {object} client - The client instance.
|
||||||
|
* @param {object|null} lastfm - The Last.fm manager, if enabled.
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
function scheduleBackgroundRefresh(client, lastfm) {
|
||||||
|
if (cache.updatedAt > 0 && Date.now() - cache.updatedAt < CACHE_TTL_MS) return;
|
||||||
|
if (refreshInflight) return;
|
||||||
|
|
||||||
|
refreshInflight = (async () => {
|
||||||
|
const instant = computeInstantTotals(client);
|
||||||
|
|
||||||
|
let guilds = instant.guilds;
|
||||||
|
try {
|
||||||
|
let total = 0;
|
||||||
|
let after = null;
|
||||||
|
while (true) {
|
||||||
|
const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : "");
|
||||||
|
const chunk = await client.rest.get(url);
|
||||||
|
if (!Array.isArray(chunk) || chunk.length === 0) break;
|
||||||
|
total += chunk.length;
|
||||||
|
if (chunk.length < 200) break;
|
||||||
|
after = chunk[chunk.length - 1].id;
|
||||||
|
}
|
||||||
|
if (total > 0) guilds = Math.max(guilds, total);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Stats] Background guild count refresh failed:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
cache.guilds = guilds || cache.guilds;
|
||||||
|
cache.users = instant.users || cache.users;
|
||||||
|
cache.updatedAt = Date.now();
|
||||||
|
persistCache();
|
||||||
|
|
||||||
|
if (lastfm?.enabled) {
|
||||||
|
const [sc, lu] = await Promise.allSettled([
|
||||||
|
lastfm.getTotalScrobbles(),
|
||||||
|
lastfm.getLinkedUsersCount(),
|
||||||
|
]);
|
||||||
|
if (sc.status === "fulfilled" && typeof sc.value === "number") cache.scrobbles = sc.value;
|
||||||
|
if (lu.status === "fulfilled" && typeof lu.value === "number") cache.linkedUsers = lu.value;
|
||||||
|
persistCache();
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
.catch((e) => logger.warn("[Stats] Background refresh failed:", e?.message))
|
||||||
|
.finally(() => { refreshInflight = null; });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Race a promise against a timeout. Resolves `{ timedOut: true, value: fallback }`
|
||||||
|
* when the budget is spent; the underlying promise keeps running either way.
|
||||||
|
* @private
|
||||||
|
* @template T
|
||||||
|
* @param {Promise<T>} promise - The promise to race.
|
||||||
|
* @param {number} ms - Timeout budget in milliseconds.
|
||||||
|
* @param {T} fallback - Value returned when the budget is spent or rejected.
|
||||||
|
* @returns {Promise<{timedOut: boolean, value: T}>}
|
||||||
|
*/
|
||||||
|
function withBudget(promise, ms, fallback) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
let done = false;
|
||||||
|
const finish = (timedOut, value) => {
|
||||||
|
if (done) return;
|
||||||
|
done = true;
|
||||||
|
clearTimeout(timer);
|
||||||
|
resolve({ timedOut, value });
|
||||||
|
};
|
||||||
|
const timer = setTimeout(() => finish(true, fallback), ms);
|
||||||
|
timer.unref?.();
|
||||||
|
promise.then(
|
||||||
|
(v) => finish(false, v),
|
||||||
|
() => finish(true, fallback),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a message send/edit action, transparently retrying when the REST
|
||||||
|
* library throws a 429 RateLimitError. Waits exactly as long as the API
|
||||||
|
* asks for (capped), so bursts in a busy channel degrade to a short delay
|
||||||
|
* instead of an error.
|
||||||
|
* @private
|
||||||
|
* @template T
|
||||||
|
* @param {Function} fn - Async action returning the message.
|
||||||
|
* @param {string} [label] - Label used in warning logs.
|
||||||
|
* @returns {Promise<T>} The action result.
|
||||||
|
*/
|
||||||
|
async function withRateLimitRetry(fn, label = "send") {
|
||||||
|
for (let attempt = 0; ; attempt++) {
|
||||||
|
try {
|
||||||
|
return await fn();
|
||||||
|
} catch (e) {
|
||||||
|
const isRateLimit = e?.code === "RATE_LIMITED" || e?.statusCode === 429;
|
||||||
|
if (!isRateLimit || attempt >= RATE_LIMIT_MAX_RETRIES) throw e;
|
||||||
|
const waitMs = Math.min(Math.ceil((e.retryAfter ?? 1) * 1000), RATE_LIMIT_MAX_WAIT_MS);
|
||||||
|
logger.warn(`[Stats] Rate limited on ${label}, retrying in ${waitMs}ms (attempt ${attempt + 1}/${RATE_LIMIT_MAX_RETRIES})`);
|
||||||
|
await new Promise((r) => setTimeout(r, waitMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -135,89 +236,49 @@ function getLivePlayerCount(playerMap) {
|
|||||||
return live;
|
return live;
|
||||||
}
|
}
|
||||||
|
|
||||||
let cachedGuildCount = null;
|
|
||||||
let guildCacheExpiresAt = 0;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the total guild count via REST API with caching.
|
|
||||||
* @private
|
|
||||||
* @async
|
|
||||||
* @param {object} client - The Discord client instance.
|
|
||||||
* @returns {Promise<number>} Total guild count.
|
|
||||||
*/
|
|
||||||
async function getGuildCount(client) {
|
|
||||||
if (cachedGuildCount !== null && Date.now() < guildCacheExpiresAt) {
|
|
||||||
return cachedGuildCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
let total = 0;
|
|
||||||
let after = null;
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : "");
|
|
||||||
const chunk = await client.rest.get(url);
|
|
||||||
|
|
||||||
if (!Array.isArray(chunk) || chunk.length === 0) break;
|
|
||||||
|
|
||||||
total += chunk.length;
|
|
||||||
|
|
||||||
if (chunk.length < 200) break;
|
|
||||||
|
|
||||||
after = chunk[chunk.length - 1].id;
|
|
||||||
}
|
|
||||||
|
|
||||||
cachedGuildCount = total;
|
|
||||||
guildCacheExpiresAt = Date.now() + CACHE_TTL_MS;
|
|
||||||
return total;
|
|
||||||
} catch (e) {
|
|
||||||
logger.warn("[Stats] REST guild count fetch failed:", e?.message);
|
|
||||||
if (typeof client.guilds?.size === "number") return client.guilds.size;
|
|
||||||
return Object.keys(client.guilds ?? {}).length;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build the stats embed with all bot information.
|
* Build the stats embed with all bot information.
|
||||||
* @private
|
* @private
|
||||||
* @param {Function} t - Translation function.
|
* @param {Function} t - Translation function.
|
||||||
* @param {object} msg - The command message wrapper.
|
* @param {object} msg - The command message wrapper.
|
||||||
* @param {object} stats - Statistics data object.
|
* @param {object} s - Statistics data object.
|
||||||
* @param {number} stats.guildCount - Number of guilds.
|
* @param {number} s.guildCount - Number of guilds.
|
||||||
* @param {number} stats.userCount - Number of users.
|
* @param {number} s.userCount - Number of users.
|
||||||
* @param {number} stats.playerCount - Number of active players.
|
* @param {number} s.playerCount - Number of active players.
|
||||||
* @param {number} stats.scrobbleCount - Total Last.fm scrobbles.
|
* @param {number} s.scrobbleCount - Total Last.fm scrobbles.
|
||||||
* @param {number} stats.linkedUsers - Number of Last.fm linked users.
|
* @param {number} s.linkedUsers - Number of Last.fm linked users.
|
||||||
* @param {number} stats.ping - Bot response ping in ms.
|
* @param {number} s.ping - Bot response ping in ms.
|
||||||
* @param {string} stats.uptime - Formatted uptime string.
|
* @param {string} s.uptime - Formatted uptime string.
|
||||||
* @param {string} stats.comHash - Git commit hash.
|
* @param {string} s.comHash - Git commit hash.
|
||||||
* @param {string} stats.comLink - Git commit link URL.
|
* @param {string} s.comLink - Git commit link URL.
|
||||||
* @param {string} [stats.reason] - Last restart reason.
|
* @param {string} [s.reason] - Last restart reason.
|
||||||
* @param {string} [stats.footer] - Custom footer text.
|
* @param {string} [s.footer] - Custom footer text.
|
||||||
* @param {boolean} stats.loading - Whether data is still loading.
|
* @param {boolean} s.lastfmEnabled - Whether Last.fm integration is enabled.
|
||||||
* @param {boolean} stats.lastfmEnabled - Whether Last.fm integration is enabled.
|
* @param {string[]} [pending] - Keys to render as "..." while still unknown.
|
||||||
* @returns {EmbedBuilder} The constructed embed.
|
* @returns {EmbedBuilder} The constructed embed.
|
||||||
*/
|
*/
|
||||||
function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) {
|
function buildEmbed(t, msg, s, pending = []) {
|
||||||
const num = (v) => Utils.formatNumber(v);
|
const num = (v) => Utils.formatNumber(v);
|
||||||
const ld = (v) => loading ? "..." : v;
|
const field = (key, value) => `\`${pending.includes(key) ? "..." : value}\``;
|
||||||
|
|
||||||
const description = [
|
const description = [
|
||||||
`${t(msg, "responses.stats.servers")} — \`${num(guildCount)}\``,
|
`${t(msg, "responses.stats.servers")} — ${field("guilds", num(s.guildCount))}`,
|
||||||
`${t(msg, "responses.stats.users")} — \`${ld(num(userCount))}\``,
|
`${t(msg, "responses.stats.users")} — ${field("users", num(s.userCount))}`,
|
||||||
`${t(msg, "responses.stats.players")} — \`${num(playerCount)}\``,
|
`${t(msg, "responses.stats.players")} — ${field("players", num(s.playerCount))}`,
|
||||||
];
|
];
|
||||||
|
|
||||||
if (lastfmEnabled) {
|
if (s.lastfmEnabled) {
|
||||||
description.push(`${t(msg, "responses.stats.scrobbles")} — \`${ld(num(scrobbleCount))}\``);
|
description.push(
|
||||||
description.push(`${t(msg, "responses.stats.linkedUsers")} — \`${ld(num(linkedUsers))}\``);
|
`${t(msg, "responses.stats.scrobbles")} — ${field("scrobbles", num(s.scrobbleCount))}`,
|
||||||
|
`${t(msg, "responses.stats.linkedUsers")} — ${field("linkedUsers", num(s.linkedUsers))}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
description.push(
|
description.push(
|
||||||
`${t(msg, "responses.stats.ping")} — \`${ld(`${num(ping)}ms`)}\``,
|
`${t(msg, "responses.stats.ping")} — ${field("ping", `${num(s.ping)}ms`)}`,
|
||||||
`${t(msg, "responses.stats.uptime")} — \`${uptime}\``,
|
`${t(msg, "responses.stats.uptime")} — \`${s.uptime}\``,
|
||||||
`${t(msg, "responses.stats.build")} — [\`${comHash}\`](${comLink})`,
|
`${t(msg, "responses.stats.build")} — [\`${s.comHash}\`](${s.comLink})`,
|
||||||
reason ? `${t(msg, "responses.stats.lastRestart")} — \`${reason}\`` : null,
|
s.reason ? `${t(msg, "responses.stats.lastRestart")} — \`${s.reason}\`` : null,
|
||||||
``,
|
``,
|
||||||
t(msg, "responses.stats.supportKofi"),
|
t(msg, "responses.stats.supportKofi"),
|
||||||
t(msg, "responses.stats.community"),
|
t(msg, "responses.stats.community"),
|
||||||
@@ -229,7 +290,7 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
|
|||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setAuthor({ name: t(msg, "responses.stats.title") })
|
.setAuthor({ name: t(msg, "responses.stats.title") })
|
||||||
.setDescription(desc)
|
.setDescription(desc)
|
||||||
.setFooter({ text: footer || t(msg, "responses.stats.title") });
|
.setFooter({ text: s.footer || t(msg, "responses.stats.title") });
|
||||||
|
|
||||||
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
||||||
return builder;
|
return builder;
|
||||||
@@ -237,8 +298,9 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Run handler for the stats command.
|
* Run handler for the stats command.
|
||||||
* Collects bot statistics and displays them in an embed, initially with loading
|
* Replies instantly with everything known from the gateway cache and the warm
|
||||||
* state then edited with the real data.
|
* cache; slow sources are refreshed in the background and filled in with a
|
||||||
|
* single bounded, fire-and-forget edit when needed.
|
||||||
*
|
*
|
||||||
* @param {object} message - The command message wrapper.
|
* @param {object} message - The command message wrapper.
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
@@ -246,13 +308,28 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
|
|||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const lastfm = this.lastfm;
|
const lastfm = this.lastfm;
|
||||||
const lastfmEnabled = lastfm?.enabled ?? false;
|
const lastfmEnabled = lastfm?.enabled ?? false;
|
||||||
|
const t = (...a) => this.t(...a);
|
||||||
|
|
||||||
const shared = {
|
const totals = getTotals(this.client);
|
||||||
guildCount: cachedGuildCount ?? this.client.guilds?.size ?? 0,
|
|
||||||
|
scheduleBackgroundRefresh(this.client, lastfmEnabled ? lastfm : null);
|
||||||
|
|
||||||
|
const pending = [];
|
||||||
|
if (totals.needsLoading) pending.push("users");
|
||||||
|
if (lastfmEnabled) {
|
||||||
|
if (cache.scrobbles === null) pending.push("scrobbles");
|
||||||
|
if (cache.linkedUsers === null) pending.push("linkedUsers");
|
||||||
|
}
|
||||||
|
if (lastPing === null) pending.push("ping");
|
||||||
|
|
||||||
|
const embedData = {
|
||||||
|
guildCount: totals.guildCount,
|
||||||
|
userCount: totals.userCount,
|
||||||
playerCount: getLivePlayerCount(this.players.playerMap),
|
playerCount: getLivePlayerCount(this.players.playerMap),
|
||||||
scrobbleCount: 0,
|
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
|
||||||
linkedUsers: 0,
|
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
||||||
lastfmEnabled,
|
lastfmEnabled,
|
||||||
|
ping: lastPing ?? 0,
|
||||||
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
|
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
|
||||||
comHash: this.comHash,
|
comHash: this.comHash,
|
||||||
comLink: this.comLink,
|
comLink: this.comLink,
|
||||||
@@ -260,25 +337,58 @@ export async function run(message) {
|
|||||||
footer: this.config.customStatsFooter || null,
|
footer: this.config.customStatsFooter || null,
|
||||||
};
|
};
|
||||||
|
|
||||||
const scrobblePromise = lastfmEnabled ? lastfm.getTotalScrobbles() : Promise.resolve(0);
|
let msg = null;
|
||||||
const linkedPromise = lastfmEnabled ? lastfm.getLinkedUsersCount() : Promise.resolve(0);
|
try {
|
||||||
|
msg = await withRateLimitRetry(async () => {
|
||||||
|
const t0 = Date.now();
|
||||||
|
const m = await message.reply({ embeds: [buildEmbed(t, message, embedData, pending)] });
|
||||||
|
lastPing = Date.now() - t0;
|
||||||
|
return m;
|
||||||
|
}, "stats reply");
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Stats] Could not send stats reply:", e?.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const hasCached = cachedUserCount !== null;
|
if (pending.length > 0) {
|
||||||
|
(async () => {
|
||||||
|
if (totals.needsLoading && refreshInflight) {
|
||||||
|
await withBudget(refreshInflight, REFRESH_FILL_BUDGET_MS, null);
|
||||||
|
}
|
||||||
|
|
||||||
const start = Date.now();
|
if (lastfmEnabled && (cache.scrobbles === null || cache.linkedUsers === null)) {
|
||||||
const msg = await message.reply({
|
const [sc, lu] = await Promise.all([
|
||||||
embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, userCount: hasCached ? cachedUserCount : 0, ping: 0, loading: true })]
|
withBudget(lastfm.getTotalScrobbles(), LASTFM_FILL_BUDGET_MS, null),
|
||||||
});
|
withBudget(lastfm.getLinkedUsersCount(), LASTFM_FILL_BUDGET_MS, null),
|
||||||
const ping = Date.now() - start;
|
]);
|
||||||
|
if (!sc.timedOut && typeof sc.value === "number") cache.scrobbles = sc.value;
|
||||||
|
if (!lu.timedOut && typeof lu.value === "number") cache.linkedUsers = lu.value;
|
||||||
|
persistCache();
|
||||||
|
}
|
||||||
|
|
||||||
const [users, scrobbleCount, linkedUsers, guildCount] = await Promise.all([
|
const fresh = getTotals(this.client);
|
||||||
getUserCount(this.client),
|
const fill = {
|
||||||
scrobblePromise,
|
...embedData,
|
||||||
linkedPromise,
|
guildCount: fresh.guildCount,
|
||||||
getGuildCount(this.client),
|
userCount: fresh.userCount,
|
||||||
]);
|
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
|
||||||
|
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
||||||
|
ping: lastPing ?? 0,
|
||||||
|
};
|
||||||
|
|
||||||
await msg.edit({
|
const stillPending = [];
|
||||||
embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, guildCount, userCount: users, scrobbleCount, linkedUsers, ping, loading: false })]
|
if (fresh.userCount === 0 && !cache.users) stillPending.push("users");
|
||||||
}).catch((err) => logger.error("[stats] editEmbed failed:", err));
|
if (lastPing === null) stillPending.push("ping");
|
||||||
|
if (lastfmEnabled) {
|
||||||
|
if (cache.scrobbles === null) stillPending.push("scrobbles");
|
||||||
|
if (cache.linkedUsers === null) stillPending.push("linkedUsers");
|
||||||
|
}
|
||||||
|
if (stillPending.length >= pending.length && stillPending.length > 0) return;
|
||||||
|
|
||||||
|
await withRateLimitRetry(
|
||||||
|
() => msg.edit({ embeds: [buildEmbed(t, message, fill, stillPending)] }),
|
||||||
|
"stats fill-in edit",
|
||||||
|
);
|
||||||
|
})().catch((e) => logger.warn("[Stats] Fill-in edit failed:", e?.message));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user