mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
fluxerlist vote api
This commit is contained in:
1 parent
726277324e
commit
d24ae4070f
5 files changed
+636
No files matched your search
@@ -0,0 +1,276 @@
|
||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
import { FLUXERLIST, buildVoteLink, buildProfileLink } from "../src/constants/API.mjs";
|
||||
|
||||
// Auto-remove timer for reaction navigation: 60 seconds
|
||||
const EMOJI_REMOVE_TIMEOUT = 60_000;
|
||||
|
||||
export const command = new CommandBuilder()
|
||||
.setName("vote")
|
||||
.setDescription("View voting info or check voters for your server/bot on FluxerList", "commands.vote")
|
||||
.setCategory("util")
|
||||
.addAliases("voters")
|
||||
.addChoiceOption(o =>
|
||||
o.setName("action")
|
||||
.setDescription("The action to perform: info, check, voters", "options.vote.action")
|
||||
.addChoices("info", "check", "voters")
|
||||
.setRequired(false)
|
||||
)
|
||||
.addChoiceOption(o =>
|
||||
o.setName("type")
|
||||
.setDescription("Resource type: server or bot", "options.vote.type")
|
||||
.addChoices("server", "bot")
|
||||
.setRequired(false)
|
||||
)
|
||||
.addStringOption(o =>
|
||||
o.setName("id")
|
||||
.setDescription("The server or bot UUID (uses config default if not provided)")
|
||||
.setRequired(false)
|
||||
)
|
||||
.addNumberOption(o =>
|
||||
o.setName("page")
|
||||
.setDescription("Page number for voter list pagination")
|
||||
.setRequired(false)
|
||||
);
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
function notConfigured(prefix) {
|
||||
return {
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor("#ff0000")
|
||||
.setDescription(`FluxerList integration is not configured on this bot. Ask the bot owner to add a FluxerList API key to the config.`)]
|
||||
};
|
||||
}
|
||||
|
||||
function noResourceId(type, prefix) {
|
||||
return {
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor("#ff0000")
|
||||
.setDescription(`No ${type} ID configured. Provide it with \`${prefix}vote check ${type} <uuid>\` or set it in config.json.`)]
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a paginated voter list embed.
|
||||
* @param {Array<{ username: string, fluxerId: number, votedAt: string }>} voters
|
||||
* @param {number} total
|
||||
* @param {number} page
|
||||
* @param {number} limit
|
||||
* @param {"server"|"bot"} type
|
||||
* @param {string} resourceId
|
||||
* @param {boolean} expired - Whether the navigation controls have expired
|
||||
* @returns {object} Embed payload
|
||||
*/
|
||||
function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired = false) {
|
||||
const totalPages = Math.max(1, Math.ceil(total / limit));
|
||||
|
||||
const lines = voters.map((v, i) => {
|
||||
const rank = (page - 1) * limit + i + 1;
|
||||
const num = String(rank).padStart(2, " ");
|
||||
const username = v.username || `User#${v.fluxerId}`;
|
||||
const dateStr = v.votedAt
|
||||
? new Date(v.votedAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
|
||||
: "Unknown";
|
||||
return `\`${num}.\` **${username}** — voted ${dateStr}`;
|
||||
});
|
||||
|
||||
const desc = lines.length > 0
|
||||
? lines.join("\n").slice(0, 4096)
|
||||
: "No voters found on this page.";
|
||||
|
||||
const title = type === "server" ? "Server Voters" : "Bot Voters";
|
||||
const footerText = expired
|
||||
? "Controls expired"
|
||||
: totalPages > 1
|
||||
? `Page ${page}/${totalPages} of ${Utils.formatNumber(total)} voters \u2022 Use \u25C0\u25B6 to navigate`
|
||||
: `${Utils.formatNumber(total)} voter${total !== 1 ? "s" : ""} total`;
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`${title}`)
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: footerText });
|
||||
|
||||
return { embeds: [embed] };
|
||||
}
|
||||
|
||||
// ── Run ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function run(msg, data) {
|
||||
const fluxerlist = this.fluxerlist;
|
||||
const prefix = this.handler?.getPrefix?.(msg.message?.guildId) ?? "%";
|
||||
const action = data.get("action")?.value ?? "info";
|
||||
const type = data.get("type")?.value ?? "bot";
|
||||
const resourceId = data.get("id")?.value || null;
|
||||
const page = data.get("page")?.value ?? 1;
|
||||
|
||||
switch (action) {
|
||||
// ── Info — Show vote link & FluxerList info ────────────────────────────────
|
||||
case "info": {
|
||||
const resolvedType = type || "bot";
|
||||
const id = resourceId || (resolvedType === "server" ? fluxerlist?.serverId : fluxerlist?.botId);
|
||||
|
||||
if (!id) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle("FluxerList Vote")
|
||||
.setDescription([
|
||||
`Vote for this bot/server on [FluxerList](${FLUXERLIST.SITE_URL})!`,
|
||||
``,
|
||||
`FluxerList is a server and bot listing platform where users can vote to help grow the community.`,
|
||||
``,
|
||||
`**Commands:**`,
|
||||
`\`${prefix}vote info\` \u2014 Show this info & vote link`,
|
||||
`\`${prefix}vote info server\` \u2014 Show vote link for a server`,
|
||||
`\`${prefix}vote check\` \u2014 Check who voted (owner-only)`,
|
||||
`\`${prefix}vote voters\` \u2014 View the voter list (owner-only)`,
|
||||
].join("\n"))]
|
||||
});
|
||||
}
|
||||
|
||||
const voteUrl = buildVoteLink(resolvedType, id);
|
||||
const profileUrl = buildProfileLink(resolvedType, id);
|
||||
const label = resolvedType === "server" ? "Server" : "Bot";
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setTitle(`Vote on FluxerList`)
|
||||
.setDescription([
|
||||
`Support this ${label.toLowerCase()} by voting on FluxerList!`,
|
||||
``,
|
||||
`**[Vote Now](${voteUrl})**`,
|
||||
`**[View Profile](${profileUrl})**`,
|
||||
``,
|
||||
`Your votes help this ${label.toLowerCase()} grow and reach more users.`,
|
||||
].join("\n"));
|
||||
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
// ── Check / Voters — Show voter list ───────────────────────────────────────
|
||||
case "check":
|
||||
case "voters": {
|
||||
if (!fluxerlist || !fluxerlist.enabled) return msg.reply(notConfigured(prefix));
|
||||
|
||||
const resolvedType = type || "bot";
|
||||
const id = resourceId || (resolvedType === "server" ? fluxerlist.serverId : fluxerlist.botId);
|
||||
|
||||
if (!id) return msg.reply(noResourceId(resolvedType, prefix));
|
||||
|
||||
// Fetch the first page
|
||||
let voterData;
|
||||
try {
|
||||
voterData = await fluxerlist.getVoters(resolvedType, id, { page, limit: 20 });
|
||||
} catch (err) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor("#ff0000")
|
||||
.setDescription(`Failed to fetch voters: ${err.message}`)]
|
||||
});
|
||||
}
|
||||
|
||||
// No voters at all
|
||||
if (voterData.total === 0) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription(`No one has voted for this ${resolvedType} yet. Share the vote link to get started!`)]
|
||||
});
|
||||
}
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil(voterData.total / 20));
|
||||
|
||||
// Single page — no navigation needed
|
||||
if (totalPages <= 1) {
|
||||
const embed = buildVotersEmbed(voterData.voters, voterData.total, voterData.page, 20, resolvedType, id);
|
||||
return msg.reply(embed);
|
||||
}
|
||||
|
||||
// Multi-page — add emoji navigation
|
||||
let currentPage = voterData.page;
|
||||
|
||||
const buildPage = (pageIdx, expired = false) => {
|
||||
return buildVotersEmbed(voterData.voters, voterData.total, pageIdx, 20, resolvedType, id, expired);
|
||||
};
|
||||
|
||||
const replyMsg = await msg.reply(buildPage(currentPage));
|
||||
if (!replyMsg?.message) return;
|
||||
|
||||
const navEmojis = ["\u25C0\uFE0F", "\u25B6\uFE0F", "\u274C"];
|
||||
for (const emoji of navEmojis) {
|
||||
await replyMsg.message.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await replyMsg.message.removeAllReactions();
|
||||
} catch {
|
||||
for (const emoji of navEmojis) {
|
||||
try { await replyMsg.message.removeReaction(emoji); } catch {}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let emojiTimeout;
|
||||
const resetTimer = () => {
|
||||
clearTimeout(emojiTimeout);
|
||||
emojiTimeout = setTimeout(async () => {
|
||||
unobserve?.();
|
||||
await clearReactions();
|
||||
await replyMsg.edit(buildPage(currentPage, true)).catch(() => {});
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||
if (e.emoji_id === "\u274C") {
|
||||
clearTimeout(emojiTimeout);
|
||||
unobserve?.();
|
||||
await replyMsg.message.delete().catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
resetTimer();
|
||||
|
||||
if (e.emoji_id === "\u25C0\uFE0F") {
|
||||
currentPage = currentPage > 1 ? currentPage - 1 : totalPages;
|
||||
} else if (e.emoji_id === "\u25B6\uFE0F") {
|
||||
currentPage = currentPage < totalPages ? currentPage + 1 : 1;
|
||||
}
|
||||
|
||||
// Fetch the new page data
|
||||
try {
|
||||
voterData = await fluxerlist.getVoters(resolvedType, id, { page: currentPage, limit: 20 });
|
||||
} catch {
|
||||
/* keep previous data */
|
||||
}
|
||||
|
||||
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
||||
});
|
||||
|
||||
resetTimer();
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
.setDescription([
|
||||
`**FluxerList Vote Commands:**`,
|
||||
``,
|
||||
`\`${prefix}vote\` \u2014 Show vote info & link`,
|
||||
`\`${prefix}vote info\` \u2014 Show voting info & vote link`,
|
||||
`\`${prefix}vote check\` \u2014 Check who voted (owner-only)`,
|
||||
`\`${prefix}vote voters\` \u2014 View the voter list (owner-only)`,
|
||||
``,
|
||||
`**Options:**`,
|
||||
`\`${prefix}vote check server\` \u2014 Check voters for a server`,
|
||||
`\`${prefix}vote check bot\` \u2014 Check voters for a bot`,
|
||||
].join("\n"))]
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,12 @@
|
||||
"scrobbleMinMs": 240000,
|
||||
"Comment2": "scrobbleThreshold: fraction of track duration before scrobbling (0.5 = 50%). scrobbleMinMs: minimum ms played before scrobble (default 4 min). Both must be met."
|
||||
},
|
||||
"fluxerlist": {
|
||||
"Comment": "FluxerList integration: check voters for your server/bot. API keys are allocated by site admins, prefixed with fl_, and visible in your Dashboard. To request access, open a ticket in the Fluxer server.",
|
||||
"apiKey": "fl_your_api_key_here",
|
||||
"serverId": "your server UUID (optional, used as default for %vote check server)",
|
||||
"botId": "your bot UUID (optional, used as default for %vote check bot)"
|
||||
},
|
||||
"owners": ["user id for owner-only commands", "another user id"],
|
||||
"playerAFKTimeout": 60000,
|
||||
"Comment": "The above specifies the time in ms after which a player goes inactive; Optional.",
|
||||
|
||||
@@ -16,6 +16,7 @@ import { Locale } from "./src/constants/Locale.mjs";
|
||||
import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs";
|
||||
import { GatewayHandler } from "./src/GatewayHandler.mjs";
|
||||
import { LastFmManager } from "./src/LastFmManager.mjs";
|
||||
import { FluxerListManager } from "./src/FluxerListManager.mjs";
|
||||
|
||||
/**
|
||||
* Create a backward-compatible "bot view" wrapper around VoiceStateCache.
|
||||
@@ -234,6 +235,10 @@ export class Remix {
|
||||
// Handles Last.fm API auth, scrobbling, and user data.
|
||||
this.lastfm = new LastFmManager(config.lastfm, config.mysql);
|
||||
|
||||
// ── FluxerList Manager ──────────────────────────────────────────────────
|
||||
// Handles FluxerList API voter data queries.
|
||||
this.fluxerlist = new FluxerListManager(config.fluxerlist);
|
||||
|
||||
// ── Settings ready callback ──────────────────────────────────────────────
|
||||
settings.on("ready", () => {
|
||||
initLogger(config);
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
/**
|
||||
* FluxerListManager.mjs — FluxerList API client for voter data queries.
|
||||
*
|
||||
* Features:
|
||||
* - Fetch paginated voter lists for servers and bots
|
||||
* - Bearer token authentication (fl_ prefixed API keys)
|
||||
* - In-memory response caching with configurable TTL
|
||||
* - Graceful error handling (401/403 auth errors, network failures)
|
||||
*
|
||||
* FluxerList API docs: https://fluxerlist.com/api/v1
|
||||
*/
|
||||
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import {
|
||||
FLUXERLIST,
|
||||
FLUXERLIST_AUTH,
|
||||
FLUXERLIST_LIMITS,
|
||||
buildFluxerListUrl,
|
||||
} from "./constants/API.mjs";
|
||||
|
||||
// ── FluxerListManager ───────────────────────────────────────────────────────────
|
||||
|
||||
export class FluxerListManager {
|
||||
/**
|
||||
* @param {object} config - The `fluxerlist` section from config.json
|
||||
* @param {string} [config.apiKey] - FluxerList API key (prefixed with fl_)
|
||||
* @param {string} [config.serverId] - Default server UUID for voter queries
|
||||
* @param {string} [config.botId] - Default bot UUID for voter queries
|
||||
*/
|
||||
constructor(config = {}) {
|
||||
this.apiKey = config?.apiKey ?? "";
|
||||
this.serverId = config?.serverId ?? "";
|
||||
this.botId = config?.botId ?? "";
|
||||
this.enabled = !!this.apiKey;
|
||||
|
||||
// In-memory cache: Map<cacheKey, { data, expiresAt }>
|
||||
this._cache = new Map();
|
||||
|
||||
if (!this.enabled) {
|
||||
logger.settings("[FluxerList] Disabled — apiKey missing in config.");
|
||||
} else {
|
||||
logger.settings("[FluxerList] Enabled — API key configured.");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cache helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate a cache key from the request parameters.
|
||||
* @param {"server"|"bot"} type
|
||||
* @param {string} id
|
||||
* @param {number} page
|
||||
* @param {number} limit
|
||||
* @returns {string}
|
||||
*/
|
||||
_cacheKey(type, id, page, limit) {
|
||||
return `${type}:${id}:p${page}:l${limit}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a cached response if still fresh.
|
||||
* @param {string} key
|
||||
* @returns {object|null}
|
||||
*/
|
||||
_getCached(key) {
|
||||
const entry = this._cache.get(key);
|
||||
if (!entry) return null;
|
||||
if (Date.now() >= entry.expiresAt) {
|
||||
this._cache.delete(key);
|
||||
return null;
|
||||
}
|
||||
return entry.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a response in the cache with the configured TTL.
|
||||
* @param {string} key
|
||||
* @param {object} data
|
||||
* @param {number} [ttlMs] - Override TTL in milliseconds
|
||||
*/
|
||||
_setCached(key, data, ttlMs) {
|
||||
this._cache.set(key, {
|
||||
data,
|
||||
expiresAt: Date.now() + (ttlMs ?? FLUXERLIST_LIMITS.CACHE_TTL_MS),
|
||||
});
|
||||
|
||||
// Evict stale entries periodically to prevent unbounded growth
|
||||
if (this._cache.size > 200) {
|
||||
const now = Date.now();
|
||||
for (const [k, v] of this._cache) {
|
||||
if (now >= v.expiresAt) this._cache.delete(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── API calls ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Fetch the list of voters for a server or bot.
|
||||
*
|
||||
* @param {"server"|"bot"} type - Resource type
|
||||
* @param {string} [id] - Server or bot UUID (falls back to config default)
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.page=1] - Page number (1-based)
|
||||
* @param {number} [options.limit=50] - Results per page (max 100)
|
||||
* @param {boolean} [options.skipCache=false] - Bypass cache and fetch fresh data
|
||||
* @returns {Promise<{ total: number, page: number, limit: number, voters: Array<{ username: string, fluxerId: number, votedAt: string }> }>}
|
||||
* @throws {Error} If the API key is missing or the request fails
|
||||
*/
|
||||
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.`);
|
||||
}
|
||||
|
||||
const page = options.page ?? FLUXERLIST_LIMITS.DEFAULT_PAGE;
|
||||
const limit = options.limit ?? FLUXERLIST_LIMITS.DEFAULT_LIMIT;
|
||||
|
||||
// Check cache first
|
||||
const cacheKey = this._cacheKey(type, resourceId, page, limit);
|
||||
if (!options.skipCache) {
|
||||
const cached = this._getCached(cacheKey);
|
||||
if (cached) {
|
||||
logger.settings(`[FluxerList] Cache hit for ${cacheKey}`);
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
// Build request URL
|
||||
const endpoint = type === "server"
|
||||
? FLUXERLIST.ENDPOINTS.SERVER_VOTERS
|
||||
: FLUXERLIST.ENDPOINTS.BOT_VOTERS;
|
||||
|
||||
const url = buildFluxerListUrl(endpoint, resourceId, { page, limit });
|
||||
|
||||
// Make the API call
|
||||
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)",
|
||||
},
|
||||
});
|
||||
|
||||
// Handle HTTP errors
|
||||
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.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();
|
||||
|
||||
// Validate response shape
|
||||
if (typeof data.total !== "number" || !Array.isArray(data.voters)) {
|
||||
throw new Error("Unexpected FluxerList API response format.");
|
||||
}
|
||||
|
||||
// Cache the result
|
||||
this._setCached(cacheKey, data);
|
||||
|
||||
logger.settings(`[FluxerList] Fetched ${data.voters.length} voters for ${type} ${resourceId} (page ${page}, total ${data.total})`);
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: fetch voters for a server.
|
||||
* @param {string} [id] - Server UUID (falls back to config default)
|
||||
* @param {object} [options] - Same as getVoters options
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
async getServerVoters(id, options = {}) {
|
||||
return this.getVoters("server", id, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: fetch voters for a bot.
|
||||
* @param {string} [id] - Bot UUID (falls back to config default)
|
||||
* @param {object} [options] - Same as getVoters options
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
async getBotVoters(id, options = {}) {
|
||||
return this.getVoters("bot", id, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch ALL voters across all pages for a resource.
|
||||
* Use with caution on resources with many voters — this makes multiple API calls.
|
||||
*
|
||||
* @param {"server"|"bot"} type
|
||||
* @param {string} [id] - Resource UUID
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.limit=100] - Results per page (uses max to minimize calls)
|
||||
* @returns {Promise<Array<{ username: string, fluxerId: number, votedAt: string }>>}
|
||||
*/
|
||||
async getAllVoters(type, id, options = {}) {
|
||||
this._assertEnabled();
|
||||
|
||||
const limit = options.limit ?? FLUXERLIST_LIMITS.MAX_LIMIT;
|
||||
let page = 1;
|
||||
let allVoters = [];
|
||||
let total = Infinity;
|
||||
|
||||
// Safety: max 50 pages to prevent runaway loops
|
||||
while (allVoters.length < total && page <= 50) {
|
||||
const data = await this.getVoters(type, id, { page, limit, skipCache: options.skipCache });
|
||||
allVoters = allVoters.concat(data.voters);
|
||||
total = data.total;
|
||||
page++;
|
||||
|
||||
// If we got fewer results than the limit, we've reached the last page
|
||||
if (data.voters.length < limit) break;
|
||||
}
|
||||
|
||||
return allVoters;
|
||||
}
|
||||
|
||||
// ── Internal ────────────────────────────────────────────────────────────────
|
||||
|
||||
_assertEnabled() {
|
||||
if (!this.enabled) {
|
||||
throw new Error("FluxerList integration is not configured (missing apiKey in config.json).");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* API.mjs — Single source of truth for all external API constants.
|
||||
*
|
||||
* FLUXERLIST — FluxerList vote-tracking API configuration & endpoints
|
||||
* FLUXERLIST_AUTH — Authentication header format & key prefix
|
||||
* FLUXERLIST_LIMITS — Pagination & rate limit defaults
|
||||
*
|
||||
* Edit only here; FluxerListManager.mjs and commands/vote.mjs import from this file.
|
||||
*/
|
||||
|
||||
// ── FluxerList API ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const FLUXERLIST = {
|
||||
/** Base URL for all FluxerList API v1 endpoints */
|
||||
BASE_URL: "https://fluxerlist.com/api/v1",
|
||||
|
||||
/** FluxerList website base URL (for vote links, profiles, etc.) */
|
||||
SITE_URL: "https://fluxerlist.com",
|
||||
|
||||
/** Available endpoint paths — append :id and query params at call time */
|
||||
ENDPOINTS: {
|
||||
/** GET /api/v1/servers/:id/voters — voters for a server */
|
||||
SERVER_VOTERS: "/servers/:id/voters",
|
||||
|
||||
/** GET /api/v1/bots/:id/voters — voters for a bot */
|
||||
BOT_VOTERS: "/bots/:id/voters",
|
||||
},
|
||||
|
||||
/** Resource types supported by the API (used in command choices) */
|
||||
RESOURCE_TYPES: ["server", "bot"],
|
||||
|
||||
/** Thumbnail image for vote embeds (FluxerList branding) */
|
||||
THUMBNAIL: "https://fluxerlist.com/api/v1",
|
||||
};
|
||||
|
||||
export const FLUXERLIST_AUTH = {
|
||||
/** Header name for API key authentication */
|
||||
HEADER: "Authorization",
|
||||
|
||||
/** Prefix prepended to all FluxerList API keys */
|
||||
KEY_PREFIX: "fl_",
|
||||
|
||||
/**
|
||||
* Build the Authorization header value.
|
||||
* @param {string} apiKey - The raw API key (with or without the fl_ prefix)
|
||||
* @returns {string} Header value in "Bearer fl_xxx" format
|
||||
*/
|
||||
bearer(apiKey) {
|
||||
const key = apiKey.startsWith(FLUXERLIST_AUTH.KEY_PREFIX)
|
||||
? apiKey
|
||||
: FLUXERLIST_AUTH.KEY_PREFIX + apiKey;
|
||||
return `Bearer ${key}`;
|
||||
},
|
||||
};
|
||||
|
||||
export const FLUXERLIST_LIMITS = {
|
||||
/** Default page number when none is specified */
|
||||
DEFAULT_PAGE: 1,
|
||||
|
||||
/** Default number of results per page */
|
||||
DEFAULT_LIMIT: 50,
|
||||
|
||||
/** Maximum number of results per page (API enforced) */
|
||||
MAX_LIMIT: 100,
|
||||
|
||||
/** Cache TTL in milliseconds for voter list responses (5 min) */
|
||||
CACHE_TTL_MS: 5 * 60 * 1000,
|
||||
};
|
||||
|
||||
/**
|
||||
* Build a full FluxerList API URL by replacing :id in the endpoint path.
|
||||
*
|
||||
* @param {string} endpoint - One of FLUXERLIST.ENDPOINTS values (e.g. "/servers/:id/voters")
|
||||
* @param {string} resourceId - The server or bot UUID to substitute for :id
|
||||
* @param {object} [queryParams] - Optional query parameters
|
||||
* @param {number} [queryParams.page] - Page number (default: 1)
|
||||
* @param {number} [queryParams.limit] - Results per page, max 100 (default: 50)
|
||||
* @returns {string} Full URL ready for fetch()
|
||||
*/
|
||||
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));
|
||||
}
|
||||
|
||||
const qs = params.toString();
|
||||
return `${FLUXERLIST.BASE_URL}${path}${qs ? "?" + qs : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the vote link for a resource on FluxerList.
|
||||
*
|
||||
* @param {"server"|"bot"} type - Resource type
|
||||
* @param {string} resourceId - The server or bot UUID
|
||||
* @returns {string} URL to the vote page on FluxerList
|
||||
*/
|
||||
export function buildVoteLink(type, resourceId) {
|
||||
const path = type === "server" ? "servers" : "bots";
|
||||
return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}/vote`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the profile link for a resource on FluxerList.
|
||||
*
|
||||
* @param {"server"|"bot"} type - Resource type
|
||||
* @param {string} resourceId - The server or bot UUID
|
||||
* @returns {string} URL to the profile page on FluxerList
|
||||
*/
|
||||
export function buildProfileLink(type, resourceId) {
|
||||
const path = type === "server" ? "servers" : "bots";
|
||||
return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`;
|
||||
}
|
||||
Reference in new issue
Block a user