mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
feat: FluxerList integration, log channel, and stability fixes
FluxerList:
- Auto server-count sync (posts on startup, then every 30 min, budget-aware)
- Vote check wired into the vote command (60s per-user cache)
- 429/Retry-After aware rate limiting with typed actionable errors
- Enable via config.fluxerlist.apiKey (fl_ key from FluxerList dashboard)
Log channel (ErrorChannel):
- Forwards all errors/warnings + crash reports to a Fluxer channel
- Startup confirmation message + owner-only logtest command
- Fix: @fluxerjs REST needs { body: { content } } shape (empty-message bug)
This commit is contained in:
1 parent
d9b529edd7
commit
2fbbdf0322
13 files changed
+534
-94
No files matched your search
@@ -285,6 +285,8 @@ class Remix {
|
||||
|
||||
this.gatewayHandler.onReady();
|
||||
|
||||
this.fluxerlist?.startAutoStats?.(client);
|
||||
|
||||
if (!presenceRotationStarted && presenceContents.length > 1) {
|
||||
presenceRotationStarted = true;
|
||||
setInterval(() => {
|
||||
|
||||
+68
-15
@@ -4,15 +4,21 @@
|
||||
* designated Fluxer channel, so the owner sees problems (player failures,
|
||||
* node disconnects, database errors, crashes) without reading container logs.
|
||||
*
|
||||
* Two forwarding layers:
|
||||
* 1. Logger tap: wraps logger.error and (optionally) logger.warn so every
|
||||
* existing error site in the codebase is covered without touching call
|
||||
* sites. The logger's built-in storm gate already collapses identical
|
||||
* repeated lines before they reach this tap.
|
||||
* Three forwarding layers:
|
||||
* 1. Logger tap: wraps logger.error, (optionally) logger.warn and
|
||||
* (opt-in via forwardInfo) logger.info so every existing error site in
|
||||
* the codebase is covered without touching call sites. The logger's
|
||||
* built-in storm gate already collapses identical repeated lines before
|
||||
* they reach this tap.
|
||||
* 2. Crash reports: explicit reportCrash() calls from the process-level
|
||||
* handlers in index.mjs. These bypass the queue and send immediately —
|
||||
* REST keeps working even when the gateway connection is down — with a
|
||||
* bounded timeout so the fatal-exit path is never stalled.
|
||||
* 3. Startup confirmation: when enabled (startupMessage, default true), a
|
||||
* one-time "Log channel connected" message is sent through the real
|
||||
* send path at boot, so the owner immediately sees that forwarding works
|
||||
* — and gets an explicit console hint when the channel ID or bot
|
||||
* permissions are wrong instead of silent silence.
|
||||
*
|
||||
* Messages are sent through client.rest.post when available, with a raw
|
||||
* fetch fallback (Authorization: Bot <token>) for very early crashes before
|
||||
@@ -44,12 +50,13 @@ let _maxQueue = 40;
|
||||
let _queue = [];
|
||||
let _dropped = 0;
|
||||
let _flushing = false;
|
||||
let _announced = false;
|
||||
|
||||
const _forwardDedup = new Map();
|
||||
const _crashDedup = new Map();
|
||||
let _lastFailLog = 0;
|
||||
|
||||
const _originals = { error: null, warn: null };
|
||||
const _originals = { error: null, warn: null, info: null };
|
||||
|
||||
/**
|
||||
* Initialize the channel reporter from config. Safe to call once at boot;
|
||||
@@ -71,8 +78,36 @@ export function initErrorChannel({ config, client } = {}) {
|
||||
console.info(`[ErrorChannel] Disabled (${!_channelId ? "no channelId configured" : "enabled=false"}).`);
|
||||
return;
|
||||
}
|
||||
if (!_originals.error) _tapLogger(cfg.forwardWarn !== false);
|
||||
console.info(`[ErrorChannel] Active — forwarding errors${cfg.forwardWarn !== false ? " + warnings" : ""} to channel ${_channelId}.`);
|
||||
const forwardWarn = cfg.forwardWarn !== false;
|
||||
const forwardInfo = cfg.forwardInfo === true;
|
||||
if (!_originals.error) _tapLogger(forwardWarn, forwardInfo);
|
||||
console.info(`[ErrorChannel] Active — forwarding errors${forwardWarn ? " + warnings" : ""}${forwardInfo ? " + info" : ""} to channel ${_channelId}.`);
|
||||
if (cfg.startupMessage !== false) _announceOnce();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the channel reporter is currently active (enabled=true and a
|
||||
* channelId is configured). Used by the logtest command for its status reply.
|
||||
* @returns {boolean} True when forwarding is active.
|
||||
*/
|
||||
export function isLogChannelEnabled() {
|
||||
return _enabled && Boolean(_channelId);
|
||||
}
|
||||
|
||||
/** @private Send the one-time startup confirmation through the real send path. */
|
||||
function _announceOnce() {
|
||||
if (_announced) return;
|
||||
_announced = true;
|
||||
const content =
|
||||
"✅ **Log channel connected** — from now on this channel receives:\n" +
|
||||
"🔴 every error · 🟡 every warning · 🚨 crash reports (with uptime + memory)\n" +
|
||||
"Verify delivery any time with the `logtest` command.";
|
||||
_sendWithFallback(content).catch((e) => {
|
||||
console.error(
|
||||
`[ErrorChannel] Startup notice FAILED for channel ${_channelId}: ${e?.message ?? e}` +
|
||||
" — check that the bot has View Channel + Send Messages permission there and that errorLogChannel.channelId is correct."
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -103,11 +138,10 @@ export async function reportCrash(title, err, { fatal = false } = {}) {
|
||||
.slice(0, CONTENT_MAX);
|
||||
|
||||
try {
|
||||
await Promise.race([_send(content), _sleep(CRASH_SEND_BUDGET_MS)]);
|
||||
await Promise.race([_sendWithFallback(content), _sleep(CRASH_SEND_BUDGET_MS)]);
|
||||
return true;
|
||||
} catch (_) {
|
||||
await Promise.race([_sendRaw(content), _sleep(CRASH_SEND_BUDGET_MS)]);
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
} catch (_) {
|
||||
return false;
|
||||
@@ -121,8 +155,11 @@ export async function reportCrash(title, err, { fatal = false } = {}) {
|
||||
export function _resetErrorChannelForTests() {
|
||||
if (_originals.error) logger.error = _originals.error;
|
||||
if (_originals.warn) logger.warn = _originals.warn;
|
||||
if (_originals.info) logger.info = _originals.info;
|
||||
_originals.error = null;
|
||||
_originals.warn = null;
|
||||
_originals.info = null;
|
||||
_announced = false;
|
||||
_enabled = false;
|
||||
_channelId = null;
|
||||
_token = null;
|
||||
@@ -135,7 +172,7 @@ export function _resetErrorChannelForTests() {
|
||||
}
|
||||
|
||||
/** @private Wrap the shared logger methods so all existing error sites forward automatically. */
|
||||
function _tapLogger(forwardWarn) {
|
||||
function _tapLogger(forwardWarn, forwardInfo = false) {
|
||||
_originals.error = logger.error;
|
||||
logger.error = function (tag, ...args) {
|
||||
_originals.error(tag, ...args);
|
||||
@@ -148,6 +185,13 @@ function _tapLogger(forwardWarn) {
|
||||
_forward("warn", tag, args);
|
||||
};
|
||||
}
|
||||
if (forwardInfo && typeof logger.info === "function") {
|
||||
_originals.info = logger.info;
|
||||
logger.info = function (tag, ...args) {
|
||||
_originals.info(tag, ...args);
|
||||
_forward("info", tag, args);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** @private Forward one emitted log line into the queue (with dedup + self-exclusion). */
|
||||
@@ -157,7 +201,7 @@ function _forward(level, tag, args) {
|
||||
if (tag.startsWith("[ErrorChannel]") || tag.startsWith("[Error_Handling]")) return;
|
||||
const body = _formatArgs(args);
|
||||
const now = Date.now();
|
||||
const emoji = level === "error" ? "🔴" : "🟡";
|
||||
const emoji = level === "error" ? "🔴" : level === "info" ? "ℹ️" : "🟡";
|
||||
const text = body ? `${emoji} **${tag}** ${body}` : `${emoji} **${tag}**`;
|
||||
const key = `${level}|${tag}|${(body || tag).slice(0, 200)}`;
|
||||
const last = _forwardDedup.get(key);
|
||||
@@ -209,7 +253,7 @@ async function _runFlush() {
|
||||
/** @private Send a queued message, swallowing and cooldown-logging failures. */
|
||||
async function _sendQuietly(content) {
|
||||
try {
|
||||
await _send(content);
|
||||
await _sendWithFallback(content);
|
||||
} catch (e) {
|
||||
const now = Date.now();
|
||||
if (now - _lastFailLog > FAIL_LOG_COOLDOWN_MS) {
|
||||
@@ -223,12 +267,21 @@ async function _sendQuietly(content) {
|
||||
async function _send(content) {
|
||||
const rest = _client?.rest;
|
||||
if (typeof rest?.post === "function") {
|
||||
await rest.post(`/channels/${_channelId}/messages`, { content });
|
||||
await rest.post(`/channels/${_channelId}/messages`, { body: { content } });
|
||||
return;
|
||||
}
|
||||
await _sendRaw(content);
|
||||
}
|
||||
|
||||
/** @private Send via client REST, retrying once via raw fetch when that throws. */
|
||||
async function _sendWithFallback(content) {
|
||||
try {
|
||||
await _send(content);
|
||||
} catch (_) {
|
||||
await _sendRaw(content);
|
||||
}
|
||||
}
|
||||
|
||||
/** @private Send via a direct Fluxer REST call (Authorization: Bot <token>). */
|
||||
async function _sendRaw(content) {
|
||||
const res = await fetch(`${API_BASE}/channels/${_channelId}/messages`, {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/** @module src/services/FluxerListManager @description FluxerList API integration for fetching server/bot voter lists with caching. */
|
||||
/** @module src/services/FluxerListManager @description FluxerList API integration: voter lists, server-count auto-sync for the bot listing, per-user vote checks and listing info — with per-endpoint caching, doc-accurate rate-limit handling (429 + Retry-After) and typed errors. Docs: https://docs.fluxerlist.com/api-quickstart */
|
||||
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import {
|
||||
@@ -8,23 +8,143 @@ import {
|
||||
buildFluxerListUrl,
|
||||
} from "../utils/API.mjs";
|
||||
|
||||
/** @class FluxerListManager @description Fetches and caches voter lists from the FluxerList API for servers and bots. */
|
||||
const REQUEST_TIMEOUT_MS = 15_000;
|
||||
const RATE_LIMIT_WARN_COOLDOWN_MS = 60_000;
|
||||
|
||||
/**
|
||||
* Typed FluxerList API error. Diagnostics live in `message`; `status` carries
|
||||
* the HTTP status code (0 for client-side blocks like an active rate-limit gate).
|
||||
*/
|
||||
export class FluxerListApiError extends Error {
|
||||
/**
|
||||
* @param {string} message - Human-readable diagnostic message.
|
||||
* @param {number} [status=0] - HTTP status code, or 0 when blocked locally.
|
||||
*/
|
||||
constructor(message, status = 0) {
|
||||
super(message);
|
||||
this.name = "FluxerListApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/** @class FluxerListManager @description FluxerList API client shared by the whole bot (voter lists, stats sync, vote checks). */
|
||||
export class FluxerListManager {
|
||||
/** @param {object} [config={}] @param {string} [config.apiKey] @param {string} [config.serverId] @param {string} [config.botId] @param {string} [config.serverSlug] @param {string} [config.botSlug] */
|
||||
/** @param {object} [config={}] @param {string} [config.apiKey] @param {string} [config.botId] @param {string} [config.serverId] @param {string} [config.serverSlug] @param {string} [config.botSlug] @param {boolean} [config.autoStats] @param {number} [config.statsIntervalMinutes] */
|
||||
constructor(config = {}) {
|
||||
this.apiKey = config?.apiKey ?? "";
|
||||
this.apiKey = typeof config?.apiKey === "string" ? config.apiKey.trim() : "";
|
||||
this.serverId = config?.serverId ?? "";
|
||||
this.botId = config?.botId ?? "";
|
||||
this.serverSlug = config?.serverSlug ?? config?.serverId ?? "";
|
||||
this.botSlug = config?.botSlug ?? config?.botId ?? "";
|
||||
this.enabled = !!this.apiKey;
|
||||
this.autoStats = config?.autoStats !== false;
|
||||
this.statsIntervalMinutes = Number(config?.statsIntervalMinutes) > 0
|
||||
? Number(config.statsIntervalMinutes)
|
||||
: 30;
|
||||
|
||||
this._cache = new Map();
|
||||
this._blockedUntil = 0;
|
||||
this._lastRateLimitWarn = 0;
|
||||
this._lastStatsPost = 0;
|
||||
this._lastPostedCount = null;
|
||||
this._statsIntervalMs = FLUXERLIST_LIMITS.STATS_DEFAULT_INTERVAL_MS;
|
||||
this._statsTimer = null;
|
||||
this._statsClient = null;
|
||||
|
||||
if (!this.enabled) {
|
||||
logger.settings("[FluxerList] Disabled — apiKey missing in config.");
|
||||
} else {
|
||||
logger.settings("[FluxerList] Enabled — API key configured.");
|
||||
logger.settings(
|
||||
`[FluxerList] Enabled${this.autoStats ? " — auto server-count sync every " + this.statsIntervalMinutes + " min" : ""}.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
* Perform one authenticated API request with rate-limit gating and typed errors.
|
||||
* @param {string} endpoint - Endpoint template with `:id`.
|
||||
* @param {string} resourceId - Bot/server ID or slug.
|
||||
* @param {{ method?: string, body?: object, query?: Record<string, string|number> }} [opts]
|
||||
* @returns {Promise<object|null>} Parsed JSON response, or null for 204s.
|
||||
* @throws {FluxerListApiError} On rate-limit gate or HTTP error responses.
|
||||
*/
|
||||
async _request(endpoint, resourceId, opts = {}) {
|
||||
this._assertEnabled();
|
||||
|
||||
const now = Date.now();
|
||||
if (now < this._blockedUntil) {
|
||||
const waitS = Math.ceil((this._blockedUntil - now) / 1000);
|
||||
throw new FluxerListApiError(`FluxerList rate limit is active — retrying in ${waitS}s.`, 429);
|
||||
}
|
||||
|
||||
const method = opts.method ?? "GET";
|
||||
const url = buildFluxerListUrl(endpoint, resourceId, opts.query ?? {});
|
||||
|
||||
const headers = {
|
||||
[FLUXERLIST_AUTH.HEADER]: FLUXERLIST_AUTH.bearer(this.apiKey),
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "RemixBot/1.0 (FluxerList Integration)",
|
||||
};
|
||||
if (opts.body !== undefined) headers["Content-Type"] = "application/json";
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method,
|
||||
headers,
|
||||
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new FluxerListApiError(`FluxerList request failed: ${e?.message ?? e}`, 0);
|
||||
}
|
||||
|
||||
if (res.status === 429) {
|
||||
const retryAfterS = Number(res.headers.get("retry-after")) || 0;
|
||||
let resetMs = 0;
|
||||
try {
|
||||
const payload = await res.json();
|
||||
resetMs = Number(payload?.reset) || 0;
|
||||
} catch (_) { /* body not JSON — header already parsed above */ }
|
||||
const waitMs = retryAfterS > 0
|
||||
? retryAfterS * 1000
|
||||
: Math.max(0, resetMs - Date.now()) || 60_000;
|
||||
this._blockedUntil = Date.now() + waitMs;
|
||||
if (Date.now() - this._lastRateLimitWarn > RATE_LIMIT_WARN_COOLDOWN_MS) {
|
||||
this._lastRateLimitWarn = Date.now();
|
||||
const long = waitMs > 30 * 60_000 ? " (long window — the shared 3,000/month key budget may be exhausted)" : "";
|
||||
logger.warn(`[FluxerList] Rate limited — pausing all FluxerList requests for ${Math.round(waitMs / 1000)}s${long}.`);
|
||||
}
|
||||
throw new FluxerListApiError(
|
||||
`FluxerList rate limited — retry after ${Math.round(waitMs / 1000)}s.`,
|
||||
429
|
||||
);
|
||||
}
|
||||
|
||||
if (res.status === 400) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new FluxerListApiError(`FluxerList rejected the request as invalid (HTTP 400): ${text.slice(0, 200)}`, 400);
|
||||
}
|
||||
if (res.status === 401) {
|
||||
throw new FluxerListApiError("Invalid FluxerList API key. Generate one in the FluxerList Dashboard → Developer tab (keys start with fl_) and set fluxerlist.apiKey in config.json.", 401);
|
||||
}
|
||||
if (res.status === 403) {
|
||||
throw new FluxerListApiError("FluxerList API key does not belong to this listing's owner. Use a key from the account that owns the bot/server.", 403);
|
||||
}
|
||||
if (res.status === 404) {
|
||||
throw new FluxerListApiError(`No FluxerList listing matches "${resourceId}". Check the ID or slug in your config (e.g. "remix" from fluxerlist.com/bots/remix).`, 404);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new FluxerListApiError(`FluxerList API error (HTTP ${res.status}): ${text.slice(0, 200)}`, res.status);
|
||||
}
|
||||
|
||||
if (res.status === 204) return null;
|
||||
try {
|
||||
return await res.json();
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,13 +179,13 @@ export class FluxerListManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** @async Fetch voters from FluxerList API. @param {"server"|"bot"} type @param {string} [id] @param {object} [options={}] @param {number} [options.page] @param {number} [options.limit] @param {boolean} [options.skipCache] @returns {Promise<object>} @throws {Error} On auth, not-found, or HTTP errors. */
|
||||
/** @async Fetch voters from FluxerList API. @param {"server"|"bot"} type @param {string} [id] @param {object} [options={}] @param {number} [options.page] @param {number} [options.limit] @param {boolean} [options.skipCache] @returns {Promise<object>} @throws {FluxerListApiError} On auth, not-found, or HTTP errors. */
|
||||
async getVoters(type, id, options = {}) {
|
||||
this._assertEnabled();
|
||||
|
||||
const resourceId = id || (type === "server" ? this.serverId : this.botId);
|
||||
if (!resourceId) {
|
||||
throw new Error(`No ${type} ID configured. Set it in config.json or provide it as an argument.`);
|
||||
throw new FluxerListApiError(`No ${type} ID configured. Set it in config.json or provide it as an argument.`, 0);
|
||||
}
|
||||
|
||||
const page = options.page ?? FLUXERLIST_LIMITS.DEFAULT_PAGE;
|
||||
@@ -84,37 +204,10 @@ export class FluxerListManager {
|
||||
? FLUXERLIST.ENDPOINTS.SERVER_VOTERS
|
||||
: FLUXERLIST.ENDPOINTS.BOT_VOTERS;
|
||||
|
||||
const url = buildFluxerListUrl(endpoint, resourceId, { page, limit });
|
||||
const data = await this._request(endpoint, resourceId, { query: { page, limit } });
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
[FLUXERLIST_AUTH.HEADER]: FLUXERLIST_AUTH.bearer(this.apiKey),
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "RemixBot/1.0 (FluxerList Integration)",
|
||||
},
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
|
||||
if (res.status === 401) {
|
||||
throw new Error("Invalid FluxerList API key. Check your config.json fluxerlist.apiKey.");
|
||||
}
|
||||
if (res.status === 403) {
|
||||
throw new Error("FluxerList API key does not belong to this resource owner.");
|
||||
}
|
||||
if (res.status === 404) {
|
||||
const label = type === "server" ? "Server" : "Bot";
|
||||
throw new Error(`${label} "${resourceId}" was not found on FluxerList. Make sure the ID or slug in your config is correct (e.g. "remix" from fluxerlist.com/bots/remix).`);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(`FluxerList API error (HTTP ${res.status}): ${text.slice(0, 200)}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (typeof data.total !== "number" || !Array.isArray(data.voters)) {
|
||||
throw new Error("Unexpected FluxerList API response format.");
|
||||
if (typeof data?.total !== "number" || !Array.isArray(data?.voters)) {
|
||||
throw new FluxerListApiError("Unexpected FluxerList API response format.", 0);
|
||||
}
|
||||
|
||||
this._setCached(cacheKey, data);
|
||||
@@ -154,10 +247,174 @@ export class FluxerListManager {
|
||||
return allVoters;
|
||||
}
|
||||
|
||||
/** @private @throws {Error} If not configured. */
|
||||
/**
|
||||
* Post the bot's server count to its FluxerList listing.
|
||||
* Docs: POST /bots/{id}/stats, limit 12 requests/hour — post on a schedule,
|
||||
* not on every guild join/leave. Identical counts are skipped (unless forced)
|
||||
* to conserve the shared 3,000 requests/month key budget.
|
||||
* @async
|
||||
* @param {number} count - Current server count (non-negative integer).
|
||||
* @param {{ force?: boolean, id?: string }} [opts] - `force` bypasses the unchanged-count and min-interval guards.
|
||||
* @returns {Promise<{ok: boolean, skipped?: boolean, reason?: string, serverCount?: number, retryInMs?: number}>}
|
||||
* @throws {FluxerListApiError} On HTTP errors (auth, not found, rate limit).
|
||||
*/
|
||||
async postServerCount(count, opts = {}) {
|
||||
this._assertEnabled();
|
||||
|
||||
const resourceId = opts.id || this.botId;
|
||||
if (!resourceId) {
|
||||
throw new FluxerListApiError("No bot ID available for stats sync. Set fluxerlist.botId in config.json (or let the bot auto-detect it at startup).", 0);
|
||||
}
|
||||
|
||||
const serverCount = Number(count);
|
||||
if (!Number.isInteger(serverCount) || serverCount < 0) {
|
||||
throw new FluxerListApiError(`Invalid server count: ${count} (must be a non-negative integer).`, 0);
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
if (!opts.force) {
|
||||
if (serverCount === this._lastPostedCount) {
|
||||
return { ok: false, skipped: true, reason: "unchanged", serverCount };
|
||||
}
|
||||
const sinceLast = now - this._lastStatsPost;
|
||||
if (this._lastStatsPost > 0 && sinceLast < FLUXERLIST_LIMITS.STATS_MIN_INTERVAL_MS) {
|
||||
return {
|
||||
ok: false,
|
||||
skipped: true,
|
||||
reason: "too-soon",
|
||||
serverCount,
|
||||
retryInMs: FLUXERLIST_LIMITS.STATS_MIN_INTERVAL_MS - sinceLast,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const data = await this._request(FLUXERLIST.ENDPOINTS.BOT_STATS, resourceId, {
|
||||
method: "POST",
|
||||
body: { serverCount },
|
||||
});
|
||||
|
||||
this._lastStatsPost = now;
|
||||
this._lastPostedCount = serverCount;
|
||||
|
||||
logger.settings(`[FluxerList] Server count posted: ${serverCount}${typeof data?.serverCount === "number" && data.serverCount !== serverCount ? ` (listing now shows ${data.serverCount})` : ""}`);
|
||||
return { ok: true, serverCount };
|
||||
}
|
||||
|
||||
/**
|
||||
* Start automatic server-count syncing: one post shortly after the bot is
|
||||
* ready, then every `statsIntervalMinutes` (default 30, minimum 5 per the
|
||||
* docs' 12/hour endpoint limit). The scheduled post skips identical counts
|
||||
* to conserve the monthly key budget. Safe to call multiple times.
|
||||
* @param {object} client - The Fluxer client (uses client.guilds.cache.size and client.user.id).
|
||||
* @param {{ intervalMs?: number }} [opts] - Override the cadence (production default 30 min).
|
||||
* @returns {(() => void)|null} A stop function, or null when disabled/no key.
|
||||
*/
|
||||
startAutoStats(client, opts = {}) {
|
||||
if (!this.enabled || this.autoStats === false) return null;
|
||||
if (this._statsTimer) return () => this.stopAutoStats();
|
||||
|
||||
const resolvedId = this.botId || client?.user?.id || "";
|
||||
if (!resolvedId) {
|
||||
logger.warn("[FluxerList] Auto stats sync skipped — no botId in config and client.user.id unavailable yet.");
|
||||
return null;
|
||||
}
|
||||
if (this.botId !== resolvedId) this.botId = resolvedId;
|
||||
|
||||
this._statsClient = client;
|
||||
const requested = opts.intervalMs ?? this.statsIntervalMinutes * 60_000;
|
||||
const clamped = Math.min(
|
||||
Math.max(Number(requested) || FLUXERLIST_LIMITS.STATS_DEFAULT_INTERVAL_MS, FLUXERLIST_LIMITS.STATS_MIN_INTERVAL_MS),
|
||||
FLUXERLIST_LIMITS.STATS_MAX_INTERVAL_MS
|
||||
);
|
||||
this._statsIntervalMs = clamped;
|
||||
|
||||
const tick = async () => {
|
||||
try {
|
||||
const count = this._statsClient?.guilds?.cache?.size;
|
||||
if (!Number.isFinite(count)) return;
|
||||
await this.postServerCount(count, { force: !this._lastPostedCount });
|
||||
} catch (e) {
|
||||
logger.warn(`[FluxerList] Stats sync failed: ${e?.message ?? e}`);
|
||||
}
|
||||
};
|
||||
|
||||
logger.settings(`[FluxerList] Auto stats sync started — posting server count every ${Math.round(clamped / 60_000)} min.`);
|
||||
const bootTimer = setTimeout(tick, 15_000);
|
||||
bootTimer.unref?.();
|
||||
this._statsTimer = setInterval(tick, clamped);
|
||||
this._statsTimer.unref?.();
|
||||
|
||||
return () => this.stopAutoStats();
|
||||
}
|
||||
|
||||
/** Stop the automatic server-count sync (also clears pending boot post). @returns {void} */
|
||||
stopAutoStats() {
|
||||
if (this._statsTimer) {
|
||||
clearInterval(this._statsTimer);
|
||||
this._statsTimer = null;
|
||||
}
|
||||
this._statsClient = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a user currently has an active vote for the bot.
|
||||
* Docs: GET /bots/{id}/check?fluxerId= — 60 requests/min, so results are
|
||||
* cached for 60 seconds per user.
|
||||
* @async
|
||||
* @param {string} userId - The Fluxer user ID to check.
|
||||
* @returns {Promise<boolean|null>} `true`/`false` for the vote status, or `null` when the API failed (caller decides fail-open/fail-closed).
|
||||
*/
|
||||
async hasVoted(userId) {
|
||||
try {
|
||||
this._assertEnabled();
|
||||
const resourceId = this.botId;
|
||||
if (!resourceId) {
|
||||
logger.warn("[FluxerList] hasVoted called without a botId (set fluxerlist.botId or wait for auto-detect).");
|
||||
return null;
|
||||
}
|
||||
const cacheKey = `check:${resourceId}:${userId}`;
|
||||
const cached = this._getCached(cacheKey);
|
||||
if (cached !== null) return cached.voted;
|
||||
|
||||
const data = await this._request(FLUXERLIST.ENDPOINTS.BOT_CHECK, resourceId, {
|
||||
query: { fluxerId: String(userId) },
|
||||
});
|
||||
const result = { voted: data?.voted === true, votes: Number(data?.votes) || 0 };
|
||||
this._setCached(cacheKey, result, FLUXERLIST_LIMITS.VOTE_CHECK_TTL_MS);
|
||||
return result.voted;
|
||||
} catch (e) {
|
||||
logger.warn(`[FluxerList] Vote check failed: ${e?.message ?? e}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the bot's own public listing data (cached for 5 minutes).
|
||||
* @async
|
||||
* @param {{ force?: boolean, id?: string }} [opts]
|
||||
* @returns {Promise<object>} The bot listing object.
|
||||
* @throws {FluxerListApiError} On HTTP errors.
|
||||
*/
|
||||
async getBotInfo(opts = {}) {
|
||||
this._assertEnabled();
|
||||
const resourceId = opts.id || this.botId;
|
||||
if (!resourceId) {
|
||||
throw new FluxerListApiError("No bot ID available. Set fluxerlist.botId in config.json.", 0);
|
||||
}
|
||||
const cacheKey = `info:${resourceId}`;
|
||||
if (!opts.force) {
|
||||
const cached = this._getCached(cacheKey);
|
||||
if (cached) return cached;
|
||||
}
|
||||
const data = await this._request(FLUXERLIST.ENDPOINTS.BOT_INFO, resourceId);
|
||||
this._setCached(cacheKey, data, FLUXERLIST_LIMITS.BOT_INFO_TTL_MS);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** @private @throws {FluxerListApiError} If not configured. */
|
||||
_assertEnabled() {
|
||||
if (!this.enabled) {
|
||||
throw new Error("FluxerList integration is not configured (missing apiKey in config.json).");
|
||||
throw new FluxerListApiError("FluxerList integration is not configured (missing apiKey in config.json). Generate one in the FluxerList Dashboard → Developer tab (keys start with fl_).", 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
-9
@@ -11,11 +11,20 @@ export const FLUXERLIST = {
|
||||
/** Public FluxerList website URL. @type {string} */
|
||||
SITE_URL: "https://fluxerlist.com",
|
||||
|
||||
/** API endpoint path templates. @type {{ SERVER_VOTERS: string, BOT_VOTERS: string }} */
|
||||
/** API endpoint path templates. @type {{ SERVER_VOTERS: string, BOT_VOTERS: string, BOT_STATS: string, BOT_CHECK: string, BOT_INFO: string }} */
|
||||
ENDPOINTS: {
|
||||
SERVER_VOTERS: "/servers/:id/voters",
|
||||
|
||||
BOT_VOTERS: "/bots/:id/voters",
|
||||
|
||||
/** POST server count for a bot listing (body: { serverCount }). */
|
||||
BOT_STATS: "/bots/:id/stats",
|
||||
|
||||
/** GET a user's vote status for a bot (query: fluxerId). */
|
||||
BOT_CHECK: "/bots/:id/check",
|
||||
|
||||
/** GET a bot's public listing data. */
|
||||
BOT_INFO: "/bots/:id",
|
||||
},
|
||||
|
||||
/** Accepted resource type identifiers. @type {string[]} */
|
||||
@@ -50,7 +59,7 @@ export const FLUXERLIST_AUTH = {
|
||||
};
|
||||
|
||||
/**
|
||||
* FluxerList pagination and cache limits.
|
||||
* FluxerList pagination, cache and rate-limit limits (per docs.fluxerlist.com).
|
||||
* @namespace FLUXERLIST_LIMITS
|
||||
*/
|
||||
export const FLUXERLIST_LIMITS = {
|
||||
@@ -63,25 +72,47 @@ export const FLUXERLIST_LIMITS = {
|
||||
/** Maximum allowed items-per-page. @type {number} */
|
||||
MAX_LIMIT: 100,
|
||||
|
||||
/** Cache time-to-live in milliseconds. @type {number} */
|
||||
/** Cache time-to-live in milliseconds for voter lists. @type {number} */
|
||||
CACHE_TTL_MS: 5 * 60 * 1000,
|
||||
|
||||
/** Minimum spacing between stats posts (docs: limit is 12/hour). @type {number} */
|
||||
STATS_MIN_INTERVAL_MS: 5 * 60 * 1000,
|
||||
|
||||
/** Recommended stats cadence (docs: "post on startup, then roughly every 30 minutes"). @type {number} */
|
||||
STATS_DEFAULT_INTERVAL_MS: 30 * 60 * 1000,
|
||||
|
||||
/** Cache TTL for per-user vote checks (docs limit 60/min; cache on our side). @type {number} */
|
||||
VOTE_CHECK_TTL_MS: 60 * 1000,
|
||||
|
||||
/** Cache TTL for the bot's own listing info (default 20/min bucket). @type {number} */
|
||||
BOT_INFO_TTL_MS: 5 * 60 * 1000,
|
||||
|
||||
/** Hard cap on scheduled stats intervals accepted from config, in ms. @type {number} */
|
||||
STATS_MAX_INTERVAL_MS: 6 * 60 * 60 * 1000,
|
||||
};
|
||||
|
||||
/**
|
||||
* Build a full FluxerList API URL by substituting `:id` in the endpoint and appending query params.
|
||||
* @param {string} endpoint - Endpoint template (e.g. `"/servers/:id/voters"`).
|
||||
* `page`/`limit` keep their clamping behavior; any other params are passed through verbatim.
|
||||
* @param {string} endpoint - Endpoint template (e.g. `"/bots/:id/check"`).
|
||||
* @param {string} resourceId - Value to substitute for `:id`.
|
||||
* @param {{ page?: number, limit?: number }} [queryParams={}]
|
||||
* @param {Record<string, string|number>} [queryParams={}]
|
||||
* @returns {string} Fully qualified URL.
|
||||
*/
|
||||
export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) {
|
||||
const path = endpoint.replace(":id", encodeURIComponent(resourceId));
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (queryParams.page) params.set("page", String(queryParams.page));
|
||||
if (queryParams.limit) {
|
||||
const clamped = Math.min(Math.max(1, queryParams.limit), FLUXERLIST_LIMITS.MAX_LIMIT);
|
||||
params.set("limit", String(clamped));
|
||||
for (const [key, value] of Object.entries(queryParams)) {
|
||||
if (value === undefined || value === null) continue;
|
||||
if (key === "limit") {
|
||||
const clamped = Math.min(Math.max(1, Number(value) || 1), FLUXERLIST_LIMITS.MAX_LIMIT);
|
||||
params.set("limit", String(clamped));
|
||||
} else if (key === "page") {
|
||||
params.set("page", String(Math.max(1, Number(value) || 1)));
|
||||
} else {
|
||||
params.set(key, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
const qs = params.toString();
|
||||
|
||||
Reference in new issue
Block a user