Files
fluxer/commands/stats.mjs
T
2026-10-22 03:29:00 +03:00

577 lines
21 KiB
JavaScript

/**
* @module commands/stats
* @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/commands/index.mjs";
import { Utils } from "../src/utils/Utils.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/ui/index.mjs";
import { logger } from "../src/core/Logger.mjs";
import * as ShardingUtils from "../src/utils/ShardingUtils.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the stats command.
*/
export const command = new CommandBuilder()
.setName("stats")
.setDescription("Display stats about the bot like the uptime.", "commands.stats")
.addAliases("info", "botinfo", "about")
.setCategory("util");
/** Cache is considered fresh for this long; older values trigger a background refresh. */
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");
/** Last-resort label for the gateway line when locale files lack the key
* (customized deployments keep their own locale files across updates). */
const GATEWAY_FALLBACK_LABEL = "\u{1F310} **Gateway**";
let cache = { guilds: null, users: null, scrobbles: null, linkedUsers: null, updatedAt: 0 };
let lastPing = null;
let refreshInflight = null;
try {
const raw = JSON.parse(fs.readFileSync(CACHE_FILE, "utf8"));
cache = {
guilds: typeof raw?.guilds === "number" ? raw.guilds : null,
users: typeof raw?.users === "number" ? raw.users : null,
scrobbles: typeof raw?.scrobbles === "number" ? raw.scrobbles : null,
linkedUsers: typeof raw?.linkedUsers === "number" ? raw.linkedUsers : null,
updatedAt: typeof raw?.updatedAt === "number" ? raw.updatedAt : 0,
};
} catch {
/* first run or unreadable cache — start cold, warm up in background */
}
/** Persist the current cache to disk so the next restart serves warm data. @private */
function persistCache() {
try {
fs.mkdirSync(path.dirname(CACHE_FILE), { recursive: true });
fs.writeFileSync(CACHE_FILE, JSON.stringify(cache));
} catch (e) {
logger.warn("[Stats] Failed to persist stats cache:", e?.message);
}
}
/**
* Sum guild and member totals directly from the gateway cache.
* memberCount comes with every guild payload, so no member listing is needed.
* @private
* @param {object} client - The client instance.
* @returns {{guilds: number, users: number}} Instant totals.
*/
function computeInstantTotals(client) {
let guilds = 0;
let users = 0;
for (const guild of client.guilds.values()) {
guilds++;
users += guild.memberCount ?? guild.members?.size ?? 0;
}
return { guilds, users };
}
/**
* 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
* @param {object} client - The client instance.
* @returns {{guildCount: number, userCount: number, needsLoading: boolean}}
*/
function getTotals(client) {
const instant = computeInstantTotals(client);
const cacheFresh = cache.updatedAt > 0 && Date.now() - cache.updatedAt < CACHE_TTL_MS;
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),
);
});
}
/**
* Read the gateway heartbeat ACK latency from the WebSocket manager
* (`client.ws.ping`). Returns -1 when unavailable (not logged in yet, or
* no heartbeat ACK received yet).
* @private
* @param {object} client - The client instance.
* @returns {number} Gateway latency in ms, or -1.
*/
function readGatewayPing(client) {
try {
const ping = client?.ws?.ping;
return typeof ping === "number" && Number.isFinite(ping) ? ping : -1;
} catch (_) {
return -1;
}
}
/**
* 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));
}
}
}
/**
* Gather real-time music playback and player statistics.
* Deduplicates active players by instance and computes connected, playing,
* total queued tracks, and 24/7 radio sessions.
* @private
* @param {Map} playerMap - The player map from PlayerManager.
* @returns {{totalPlayers: number, playingCount: number, queuedTracks: number, radios247: number}}
*/
function getMusicStats(playerMap) {
const uniquePlayers = new Set();
if (playerMap) {
for (const player of playerMap.values()) {
if (!player || player._destroyed || player.leaving || player._isJoining) continue;
const conn = player.connection;
if (conn) {
const room = conn.room;
if (room) {
const isConnected = room.isConnected;
const connectionState = room.connectionState;
if (!isConnected && (connectionState === 0 || connectionState === "disconnected")) continue;
}
} else {
continue;
}
uniquePlayers.add(player);
}
}
let totalPlayers = uniquePlayers.size;
let playingCount = 0;
let queuedTracks = 0;
let radios247 = 0;
for (const player of uniquePlayers) {
const cur = player.queue?.getCurrent?.();
const isPlaying = !!cur && !player.paused;
if (isPlaying) playingCount++;
const qSize = (player.queue?.size?.() ?? 0) + (cur ? 1 : 0);
queuedTracks += qSize;
if (player._is247Enabled?.()) {
radios247++;
}
}
return {
totalPlayers,
playingCount,
queuedTracks,
radios247,
};
}
/**
* Resolve the current shard assignment string (e.g. "0/2" when sharded, or "0" in single-process mode).
* @private
* @param {object} client - The bot client instance.
* @param {string|null} guildId - The guild ID where the command was invoked.
* @returns {string} Formatted shard info.
*/
function getShardInfo(client, guildId) {
try {
const isSharded = ShardingUtils.isShardedProcess();
const currentShard = ShardingUtils.shardIdForGuild(client, guildId);
if (isSharded) {
const totalShards = Number(process.env.FLUXER_SHARD_COUNT) || 1;
return totalShards > 1 ? `${currentShard}/${totalShards}` : `${currentShard}`;
}
return `${currentShard}`;
} catch (_) {
return "0";
}
}
/**
* Translate with a hardcoded fallback and optional placeholders. Locale lookups
* that miss (custom or outdated locale files make translate() return the raw dot-notation key)
* render the readable fallback instead of an ugly key path in the embed.
* @private
* @param {Function} t - Translation function.
* @param {object} msg - The command message wrapper.
* @param {string} key - Locale key.
* @param {string} fallback - Label used when the key is missing.
* @param {object} [vars={}] - Optional interpolation variables.
* @returns {string}
*/
function tOr(t, msg, key, fallback, vars = {}) {
const value = t(msg, key, vars);
return value === key ? fallback : value;
}
/**
* Build the stats embed with all bot information.
* Uses a clean multi-column grid layout (addFields) with category sections
* and a top-right bot avatar thumbnail.
* @private
* @param {Function} t - Translation function.
* @param {object} msg - The command message wrapper.
* @param {object} s - Statistics data object.
* @param {number} s.guildCount - Number of guilds.
* @param {number} s.userCount - Number of users.
* @param {number} s.playerCount - Number of active connected players.
* @param {number} s.playingCount - Number of players actively streaming.
* @param {number} s.queuedTracks - Total tracks across all player queues.
* @param {number} s.radios247 - Number of active 24/7 radio sessions.
* @param {string} s.shard - Shard assignment string.
* @param {string|null} [s.botIcon] - Bot avatar URL.
* @param {number} s.scrobbleCount - Total Last.fm scrobbles.
* @param {number} s.linkedUsers - Number of Last.fm linked users.
* @param {number} s.ping - Bot response ping in ms (REST reply round trip).
* @param {number} s.gatewayPing - Gateway heartbeat ACK latency in ms (-1 if unknown).
* @param {string} s.uptime - Formatted uptime string.
* @param {string} s.comHash - Git commit hash.
* @param {string} s.comLink - Git commit link URL.
* @param {string} [s.reason] - Last restart reason.
* @param {string} [s.footer] - Custom footer text.
* @param {boolean} s.lastfmEnabled - Whether Last.fm integration is enabled.
* @param {string[]} [pending] - Keys to render as "..." while still unknown.
* @returns {EmbedBuilder} The constructed embed.
*/
function buildEmbed(t, msg, s, pending = []) {
const num = (v) => Utils.formatNumber(v);
const field = (key, value) => `\`${pending.includes(key) ? "..." : value}\``;
const playerVal = s.playingCount > 0
? tOr(t, msg, "responses.stats.playersWithPlaying", `${num(s.playerCount)} (${num(s.playingCount)} playing)`, {
total: num(s.playerCount),
playing: num(s.playingCount),
})
: num(s.playerCount);
const fields = [];
const overviewParts = [
`${t(msg, "responses.stats.servers")} — ${field("guilds", num(s.guildCount))}`,
`${t(msg, "responses.stats.users")} — ${field("users", num(s.userCount))}`,
`${tOr(t, msg, "responses.stats.shard", "🧩 **Shard**")} — \`${s.shard}\``,
];
fields.push({
name: tOr(t, msg, "responses.stats.categoryOverview", "📊 Overview"),
value: overviewParts.join(" • "),
inline: false,
});
const musicLines = [
`${t(msg, "responses.stats.players")} — ${field("players", playerVal)}`,
];
const musicExtra = [];
if (s.queuedTracks > 0) {
musicExtra.push(`${tOr(t, msg, "responses.stats.queuedTracks", "🎶 **Queued Tracks**")} — ${field("queuedTracks", num(s.queuedTracks))}`);
}
if (s.radios247 > 0) {
musicExtra.push(`${tOr(t, msg, "responses.stats.radios", "📻 **24/7 Radios**")} — ${field("radios", num(s.radios247))}`);
}
if (musicExtra.length > 0) {
musicLines.push(musicExtra.join(" • "));
}
fields.push({
name: tOr(t, msg, "responses.stats.categoryMusic", "🎧 Music Activity"),
value: musicLines.join("\n"),
inline: false,
});
if (s.lastfmEnabled) {
const lastfmParts = [
`${t(msg, "responses.stats.scrobbles")} — ${field("scrobbles", num(s.scrobbleCount))}`,
`${t(msg, "responses.stats.linkedUsers")} — ${field("linkedUsers", num(s.linkedUsers))}`,
];
fields.push({
name: tOr(t, msg, "responses.stats.categoryLastfm", "🎵 Last.fm"),
value: lastfmParts.join(" • "),
inline: false,
});
}
const latencyParts = [
`${t(msg, "responses.stats.ping")} — ${field("ping", `${num(s.ping)}ms`)}`,
];
if (s.gatewayPing >= 0) {
latencyParts.push(`${tOr(t, msg, "responses.stats.gateway", GATEWAY_FALLBACK_LABEL)} — \`${num(s.gatewayPing)}ms\``);
}
const perfLines = [
latencyParts.join(" • "),
`${t(msg, "responses.stats.uptime")} — \`${s.uptime}\``,
];
fields.push({
name: tOr(t, msg, "responses.stats.categoryPerformance", "⚡ System & Network"),
value: perfLines.join("\n"),
inline: false,
});
const bottomLines = [
`${t(msg, "responses.stats.build")} — [\`${s.comHash}\`](${s.comLink})` +
(s.reason ? ` • ${t(msg, "responses.stats.lastRestart")} — \`${s.reason}\`` : ""),
`${t(msg, "responses.stats.supportKofi")} • ${t(msg, "responses.stats.community")}`,
];
fields.push({
name: "\u200B",
value: bottomLines.join("\n"),
inline: false,
});
const authorOptions = { name: t(msg, "responses.stats.title") };
if (typeof s.botIcon === "string" && s.botIcon.startsWith("http")) {
authorOptions.iconURL = s.botIcon;
}
const builder = new EmbedBuilder()
.setColor(getGlobalColor())
.setAuthor(authorOptions)
.setFooter({ text: s.footer || t(msg, "responses.stats.title") });
if (fields.length > 0) {
try {
builder.addFields(...fields);
} catch (_) {
if (typeof builder.setFields === "function") {
try { builder.setFields(fields); } catch (__) { builder.data.fields = fields; }
} else {
builder.data.fields = fields;
}
}
}
if (typeof s.botIcon === "string" && s.botIcon.startsWith("http")) {
try { builder.setThumbnail(s.botIcon); } catch (_) {}
}
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
return builder;
}
/**
* Run handler for the stats command.
* Replies instantly with everything known from the gateway cache and the warm
* 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.
* @returns {Promise<void>}
*/
export async function run(message) {
const lastfm = this.lastfm;
const lastfmEnabled = lastfm?.enabled ?? false;
const t = (...a) => this.t(...a);
const totals = getTotals(this.client);
const music = getMusicStats(this.players?.playerMap);
const shard = getShardInfo(this.client, message.guildId ?? message.guild?.id);
let botIcon = null;
try {
const raw = this.client?.user?.displayAvatarURL?.() || this.client?.user?.avatarURL?.();
if (typeof raw === "string" && raw.startsWith("http")) botIcon = raw;
} catch (_) {}
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: music.totalPlayers,
playingCount: music.playingCount,
queuedTracks: music.queuedTracks,
radios247: music.radios247,
shard,
botIcon,
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
lastfmEnabled,
ping: lastPing ?? 0,
gatewayPing: readGatewayPing(this.client),
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
comHash: this.comHash,
comLink: this.comLink,
reason: this.config.restart ?? null,
footer: this.config.customStatsFooter || null,
};
let msg = null;
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;
}
if (pending.length > 0) {
(async () => {
if (totals.needsLoading && refreshInflight) {
await withBudget(refreshInflight, REFRESH_FILL_BUDGET_MS, null);
}
if (lastfmEnabled && (cache.scrobbles === null || cache.linkedUsers === null)) {
const [sc, lu] = await Promise.all([
withBudget(lastfm.getTotalScrobbles(), LASTFM_FILL_BUDGET_MS, null),
withBudget(lastfm.getLinkedUsersCount(), LASTFM_FILL_BUDGET_MS, null),
]);
if (!sc.timedOut && typeof sc.value === "number") cache.scrobbles = sc.value;
if (!lu.timedOut && typeof lu.value === "number") cache.linkedUsers = lu.value;
persistCache();
}
const fresh = getTotals(this.client);
const freshMusic = getMusicStats(this.players?.playerMap);
const fill = {
...embedData,
guildCount: fresh.guildCount,
userCount: fresh.userCount,
playerCount: freshMusic.totalPlayers,
playingCount: freshMusic.playingCount,
queuedTracks: freshMusic.queuedTracks,
radios247: freshMusic.radios247,
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
ping: lastPing ?? 0,
gatewayPing: readGatewayPing(this.client),
};
const stillPending = [];
if (fresh.userCount === 0 && !cache.users) stillPending.push("users");
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));
}
}