mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
cleannnn
This commit is contained in:
1 parent
05fb38aabd
commit
bc1fe82919
43 files changed
+122
-1784
No files matched your search
+3
-13
@@ -53,14 +53,10 @@ export async function run(msg, data) {
|
||||
};
|
||||
|
||||
const MAX_DESC = 4096;
|
||||
const CODE_WRAP = 12; // "```json\n" (8) + "\n```" (4)
|
||||
const CODE_WRAP = 12;
|
||||
|
||||
// ── Build pages ────────────────────────────────────────────────────────
|
||||
// Page 0: summary + compact server list
|
||||
// Page 1..N: detailed JSON for each server (one per page, or grouped if small)
|
||||
const pages = [];
|
||||
|
||||
// Page 0 — Summary
|
||||
const summaryLines = [
|
||||
`📊 **Summary**`,
|
||||
`Players in map: **${summary.playerMapSize}**`,
|
||||
@@ -73,7 +69,6 @@ export async function run(msg, data) {
|
||||
const s = servers[i];
|
||||
const status = s.conn === "yes" && !s.destroyed && !s.leaving ? "🟢" : "🔴";
|
||||
const line = `${status} \`${s.guildname}\` / \`#${s.name}\` — conn:${s.conn} room:${s.roomState} media:${s.mediaPlayer}`;
|
||||
// Guard against overflow even for the summary
|
||||
if (summaryLines.join("\n").length + line.length + 1 > MAX_DESC - 30) {
|
||||
summaryLines.push(`… and ${servers.length - i} more (see next pages)`);
|
||||
break;
|
||||
@@ -82,7 +77,6 @@ export async function run(msg, data) {
|
||||
}
|
||||
pages.push(summaryLines.join("\n"));
|
||||
|
||||
// Pages 1..N — Detailed JSON per-server (group small ones together)
|
||||
{
|
||||
let groupJson = "";
|
||||
let groupStart = 0;
|
||||
@@ -92,22 +86,20 @@ export async function run(msg, data) {
|
||||
const codeBlock = "```json\n" + groupJson + "\n```";
|
||||
pages.push(codeBlock.slice(0, MAX_DESC));
|
||||
groupJson = "";
|
||||
groupStart = i; // will be set by outer loop
|
||||
groupStart = i;
|
||||
};
|
||||
|
||||
let i = 0;
|
||||
for (i = 0; i < servers.length; i++) {
|
||||
const singleJson = JSON.stringify(servers[i], null, 2);
|
||||
const candidate = groupJson
|
||||
? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1) // merge objects into array-like
|
||||
? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1)
|
||||
: singleJson;
|
||||
|
||||
if (("```json\n" + candidate + "\n```").length > MAX_DESC && groupJson) {
|
||||
// Current group is full — flush it, start new group with this server
|
||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||
groupJson = singleJson;
|
||||
} else if (("```json\n" + candidate + "\n```").length > MAX_DESC) {
|
||||
// Even a single server is too big — truncate it
|
||||
const budget = MAX_DESC - CODE_WRAP;
|
||||
groupJson = singleJson.slice(0, budget);
|
||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||
@@ -121,7 +113,6 @@ export async function run(msg, data) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Single page — no pagination needed ────────────────────────────────
|
||||
if (pages.length === 1) {
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
@@ -131,7 +122,6 @@ export async function run(msg, data) {
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
// ── Multi-page with reactions ─────────────────────────────────────────
|
||||
const totalPages = pages.length;
|
||||
let currentPage = 0;
|
||||
|
||||
|
||||
+6
-48
@@ -3,11 +3,9 @@ import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { inspect } from "node:util";
|
||||
|
||||
// Auto-remove timer: 1 minute
|
||||
const EMOJI_REMOVE_TIMEOUT = 60000;
|
||||
|
||||
/**
|
||||
* List of keys that should be redacted from objects before displaying in Discord.
|
||||
* Matches any key that *contains* one of these strings (case-insensitive).
|
||||
*/
|
||||
const RESTRICTED = [
|
||||
@@ -27,12 +25,8 @@ const RESTRICTED = [
|
||||
"webhook",
|
||||
];
|
||||
|
||||
// Maximum depth for sensitive-key scanning and redaction.
|
||||
// 6 covers deeply nested config objects (e.g. config.nodelink.password nested
|
||||
// inside player config) without risking stack overflow on circular references.
|
||||
const SCAN_DEPTH = 6;
|
||||
|
||||
// Track visited objects to handle circular references
|
||||
function hasSensitive(obj, level = 0, visited = new WeakSet()) {
|
||||
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return false;
|
||||
if (visited.has(obj)) return false;
|
||||
@@ -88,31 +82,24 @@ async function clean(value) {
|
||||
|
||||
return output
|
||||
.replace(/`/g, "`\u200b")
|
||||
.replace(/@/g, "@\u200b") || "undefined"; // Fallback if output is empty
|
||||
.replace(/@/g, "@\u200b") || "undefined";
|
||||
}
|
||||
|
||||
function isSingleExpression(code) {
|
||||
const trimmed = code.trim();
|
||||
|
||||
// Empty code
|
||||
if (!trimmed) return false;
|
||||
|
||||
// Block statements — user is writing a full function body
|
||||
if (/^(if|for|while|do|switch|try|catch|finally|with)\s*[\({]/.test(trimmed)) return false;
|
||||
|
||||
// Declarations — always multi-statement style
|
||||
if (/^\s*(const|let|var|function\s|class\s)/.test(trimmed)) return false;
|
||||
|
||||
// Contains semicolons that look like statement separators (but not inside strings)
|
||||
// Strip string literals to avoid false positives from semicolons inside strings
|
||||
const stripped = trimmed
|
||||
.replace(/'(?:[^'\\]|\\.)*'/g, '""') // single-quoted strings
|
||||
.replace(/"(?:[^"\\]|\\.)*"/g, '""') // double-quoted strings
|
||||
.replace(/`(?:[^`\\]|\\.)*`/g, '""'); // template literals (simplified)
|
||||
.replace(/'(?:[^'\\]|\\.)*'/g, '""')
|
||||
.replace(/"(?:[^"\\]|\\.)*"/g, '""')
|
||||
.replace(/`(?:[^`\\]|\\.)*`/g, '""');
|
||||
if (stripped.includes(";")) return false;
|
||||
|
||||
// Contains newlines that suggest multiple statements
|
||||
// (but allow multi-line method chains like `.foo()\n.bar()`)
|
||||
const withoutChains = trimmed.replace(/\.\s*\n/g, ".");
|
||||
if (withoutChains.includes("\n")) return false;
|
||||
|
||||
@@ -128,12 +115,10 @@ async function runEval(expression, context) {
|
||||
let result, isError = false, type = "undefined";
|
||||
|
||||
try {
|
||||
// Auto-return single expressions so users don't need to write `return`
|
||||
const code = isSingleExpression(expression)
|
||||
? `return (${expression});`
|
||||
: expression;
|
||||
|
||||
// Use eval() — runs in module scope so `this` is the context passed via .call()
|
||||
result = await eval(`(async function() { ${code} })`).call(context);
|
||||
type = result === null ? "null" : typeof result;
|
||||
} catch (e) {
|
||||
@@ -162,21 +147,9 @@ export const command = new CommandBuilder()
|
||||
export async function run(msg, data) {
|
||||
const expression = data.get("expression").value;
|
||||
|
||||
// Build a rich context with shorthand variables so eval can access
|
||||
// everything easily via `this`. `this` = Remix instance merged with
|
||||
// the extra shortcuts below.
|
||||
// this.client → Fluxer Client
|
||||
// this.guilds → this.client.guilds
|
||||
// this.channels → this.client.channels
|
||||
// this.users → this.client.users
|
||||
// this.players → PlayerManager
|
||||
// this.settings → SettingsManager
|
||||
// this.msg → the Message wrapper
|
||||
// this.message → the raw fluxer message object
|
||||
const context = Object.assign({
|
||||
message: msg?.message,
|
||||
msg,
|
||||
// Shorthand aliases for convenience
|
||||
guilds: this.client?.guilds,
|
||||
channels: this.client?.channels,
|
||||
users: this.client?.users,
|
||||
@@ -184,11 +157,8 @@ export async function run(msg, data) {
|
||||
settings: this.settingsMgr,
|
||||
}, this);
|
||||
|
||||
// 1. Run the evaluation
|
||||
const { output, isError, type, elapsed } = await runEval(expression, context);
|
||||
|
||||
// 2. Chunk the output to bypass Discord limits (Max embed description is 4096 chars)
|
||||
// We use 3800 to leave room for the header and markdown formatting
|
||||
const chunkSize = 3800;
|
||||
const chunks = [];
|
||||
for (let i = 0; i < output.length; i += chunkSize) {
|
||||
@@ -198,25 +168,22 @@ export async function run(msg, data) {
|
||||
const totalPages = chunks.length;
|
||||
let currentPage = 0;
|
||||
|
||||
// Helper to build the specific embed page
|
||||
const buildPageContent = (pageIdx, expired = false) => {
|
||||
const title = isError
|
||||
? this.t(msg, "responses.eval.resultTitleError")
|
||||
: this.t(msg, "responses.eval.resultTitleSuccess");
|
||||
|
||||
// Embed description includes the metadata and the codeblock
|
||||
const typeLabel = this.t(msg, "responses.eval.typeLabel");
|
||||
const timeLabel = this.t(msg, "responses.eval.timeLabel");
|
||||
const desc = `**${typeLabel}** \`${type}\` • **${timeLabel}** \`${elapsed}ms\`\n\`\`\`js\n${chunks[pageIdx]}\n\`\`\``.slice(0, 4096);
|
||||
|
||||
// Customize footer based on state
|
||||
let footerText = this.t(msg, "responses.eval.pageLabel", { page: pageIdx + 1, total: totalPages });
|
||||
if (expired) footerText = this.t(msg, "responses.eval.controlsExpired");
|
||||
else if (totalPages > 1) footerText += " " + this.t(msg, "responses.eval.navigateHint");
|
||||
else footerText += " " + this.t(msg, "responses.eval.deleteHint");
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(isError ? "#ff0000" : getGlobalColor()) // Red if error, default otherwise
|
||||
.setColor(isError ? "#ff0000" : getGlobalColor())
|
||||
.setTitle(title)
|
||||
.setDescription(desc)
|
||||
.setFooter({ text: footerText })
|
||||
@@ -225,12 +192,9 @@ export async function run(msg, data) {
|
||||
return { embeds: [embed] };
|
||||
};
|
||||
|
||||
// 3. Send the initial message using the wrapper
|
||||
const replyMsg = await msg.reply(buildPageContent(0));
|
||||
if (!replyMsg?.message) return;
|
||||
|
||||
// 4. Setup React UI
|
||||
// If it's only 1 page, we just show the Delete button. Otherwise, add arrows.
|
||||
const navEmojis = totalPages > 1 ? ["⬅️", "➡️", "❌"] : ["❌"];
|
||||
let unobserve = null;
|
||||
let emojiTimeout = null;
|
||||
@@ -239,7 +203,6 @@ export async function run(msg, data) {
|
||||
await replyMsg.message.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
// Helper: Clear reactions when time runs out
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await replyMsg.message.removeAllReactions();
|
||||
@@ -252,7 +215,6 @@ export async function run(msg, data) {
|
||||
}
|
||||
};
|
||||
|
||||
// Helper: Reset inactivity timer
|
||||
const resetTimer = () => {
|
||||
clearTimeout(emojiTimeout);
|
||||
emojiTimeout = setTimeout(async () => {
|
||||
@@ -262,15 +224,12 @@ export async function run(msg, data) {
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
// 5. Start listening for reactions
|
||||
unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||
// Handle specific actions
|
||||
if (e.emoji_id === "❌") {
|
||||
// Clean up and delete the message
|
||||
clearTimeout(emojiTimeout);
|
||||
if (unobserve) unobserve();
|
||||
await replyMsg.message.delete().catch(() => {});
|
||||
return; // Exit completely
|
||||
return;
|
||||
}
|
||||
|
||||
resetTimer();
|
||||
@@ -281,7 +240,6 @@ export async function run(msg, data) {
|
||||
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
// Update Embed
|
||||
await replyMsg.edit(buildPageContent(currentPage)).catch(() => {});
|
||||
});
|
||||
|
||||
|
||||
+4
-19
@@ -3,7 +3,6 @@ import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
|
||||
// ── Filter catalogue ──────────────────────────────────────────────────────────
|
||||
const FILTERS = [
|
||||
{
|
||||
emoji: "🔇",
|
||||
@@ -177,7 +176,7 @@ const SESSION_MS = 60_000;
|
||||
function mergeFilterPayloads(keys) {
|
||||
const merged = {};
|
||||
for (const key of keys) {
|
||||
if (key === "off") continue; // "off" clears everything — handled upstream
|
||||
if (key === "off") continue;
|
||||
const f = FILTERS.find(f => f.key === key);
|
||||
if (!f || !f.payload || Object.keys(f.payload).length === 0) continue;
|
||||
for (const [category, settings] of Object.entries(f.payload)) {
|
||||
@@ -187,7 +186,6 @@ function mergeFilterPayloads(keys) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// ── Command definition ────────────────────────────────────────────────────────
|
||||
export const command = new CommandBuilder()
|
||||
.setName("filter")
|
||||
.setDescription(
|
||||
@@ -197,7 +195,6 @@ export const command = new CommandBuilder()
|
||||
.setCategory("music")
|
||||
.addAliases("filters", "fx", "effect");
|
||||
|
||||
// ── Build page embed ──────────────────────────────────────────────────────────
|
||||
function buildPageEmbed(t, msg, page, activeKeys, current) {
|
||||
const totalPages = Math.ceil(FILTERS.length / PAGE_SIZE);
|
||||
const start = page * PAGE_SIZE;
|
||||
@@ -207,7 +204,6 @@ function buildPageEmbed(t, msg, page, activeKeys, current) {
|
||||
? `🎵 **${Utils.truncate(current.title, 45)}**`
|
||||
: t(msg, "responses.filter.nothingPlayingInline");
|
||||
|
||||
// Show active filter indicators
|
||||
const activeSet = new Set(activeKeys);
|
||||
const lines = pageItems.map(f => {
|
||||
const isActive = activeSet.has(f.key);
|
||||
@@ -219,7 +215,6 @@ function buildPageEmbed(t, msg, page, activeKeys, current) {
|
||||
? `\n\n${PREV_EMOJI} Prev ${NEXT_EMOJI} Next ${CANCEL_EMOJI} ${t(msg, "responses.filter.closeHint")}`
|
||||
: `\n\n${CANCEL_EMOJI} ${t(msg, "responses.filter.closeHint")}`;
|
||||
|
||||
// Build active summary line
|
||||
let activeSummary = "";
|
||||
if (activeKeys.length > 0) {
|
||||
const activeLabels = activeKeys.map(k => {
|
||||
@@ -243,12 +238,10 @@ function buildPageEmbed(t, msg, page, activeKeys, current) {
|
||||
;
|
||||
}
|
||||
|
||||
// ── Command handler ───────────────────────────────────────────────────────────
|
||||
export async function run(msg) {
|
||||
const player = await this.getPlayer(msg, false, false, false);
|
||||
if (!player) return;
|
||||
|
||||
// Track multiple active filters (stackable)
|
||||
let activeKeys = player.activeFilter?.key
|
||||
? player.activeFilter.key.split("+").filter(Boolean)
|
||||
: [];
|
||||
@@ -340,10 +333,8 @@ export async function run(msg) {
|
||||
|
||||
resetTimer();
|
||||
|
||||
// Normalise emoji identifier across Fluxer reaction event shapes
|
||||
const emoji = e.emoji_id ?? e.emoji?.name ?? e.emoji?.id ?? e.emoji;
|
||||
|
||||
// ── Navigation ──────────────────────────────────────────────────────────
|
||||
if (emoji === CANCEL_EMOJI) {
|
||||
return close(this.t(msg, "responses.filter.pickerClosed"));
|
||||
}
|
||||
@@ -374,13 +365,12 @@ export async function run(msg) {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Filter selection ────────────────────────────────────────────────────
|
||||
const filter = FILTERS.find(f => f.emoji === emoji);
|
||||
if (!filter) return;
|
||||
|
||||
const track = player.queue.getCurrent();
|
||||
const previousActiveKeys = [...activeKeys];
|
||||
if (!track && false) { // pending filters are allowed; keep old fallback block unreachable
|
||||
if (!track && false) {
|
||||
await menuMsg.edit({
|
||||
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)]
|
||||
}).catch(() => {});
|
||||
@@ -396,20 +386,17 @@ export async function run(msg) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Toggle behavior: if already active, remove it; otherwise add it
|
||||
// "off" always clears everything
|
||||
if (filter.key === "off") {
|
||||
activeKeys = [];
|
||||
} else {
|
||||
const idx = activeKeys.indexOf(filter.key);
|
||||
if (idx !== -1) {
|
||||
activeKeys.splice(idx, 1); // Toggle off
|
||||
activeKeys.splice(idx, 1);
|
||||
} else {
|
||||
activeKeys.push(filter.key); // Toggle on
|
||||
activeKeys.push(filter.key);
|
||||
}
|
||||
}
|
||||
|
||||
// Build merged payload from all active keys
|
||||
const mergedPayload = mergeFilterPayloads(activeKeys);
|
||||
const meta = activeKeys.length > 0
|
||||
? {
|
||||
@@ -437,7 +424,6 @@ export async function run(msg) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update active key and refresh embed (player.activeFilter is already updated by applyFilter)
|
||||
activeKeys = meta ? meta.key.split("+") : [];
|
||||
|
||||
const successMsg = pending
|
||||
@@ -464,7 +450,6 @@ export async function run(msg) {
|
||||
await menuMsg.edit({ embeds: [confirmEmbed] }).catch(() => {});
|
||||
await Utils.sleep(1200);
|
||||
|
||||
// Restore picker (session stays open)
|
||||
if (!settled) {
|
||||
await menuMsg.edit({
|
||||
embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, player.queue.getCurrent())]
|
||||
|
||||
@@ -35,7 +35,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
||||
return message.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
// Guard: moonlink must be ready before we can play anything
|
||||
if (!this.moonlink) {
|
||||
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
||||
.setDescription(this.t(message, "responses.join.audioNodeConnecting"));
|
||||
@@ -59,7 +58,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
||||
const homeChannelId = String(p._home247Channel ?? activeChannelId).replace(/\D/g, "") || activeChannelId;
|
||||
const guildId = getGuildId(message);
|
||||
|
||||
// Check 24/7 mode for this channel
|
||||
const is247 = (() => {
|
||||
try {
|
||||
const raw = this.settingsMgr?.getServer?.(guildId)?.get?.("stay_247");
|
||||
@@ -67,7 +65,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
||||
} catch (_) { return false; }
|
||||
})();
|
||||
|
||||
// Determine per-channel mode
|
||||
const mode247 = (() => {
|
||||
if (!is247) return "off";
|
||||
try {
|
||||
@@ -87,7 +84,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
||||
p.destroy();
|
||||
|
||||
if (is247 && (mode247 === "on" || mode247 === "auto")) {
|
||||
// 24/7 mode — auto-rejoin after a delay
|
||||
const rejoinDelay = this.config?.timers?.rejoin247Delay ?? 3_000;
|
||||
const prefix = (() => {
|
||||
try { return this._commands?.getPrefix?.(guildId) ?? "%"; } catch (_) { return "%"; }
|
||||
@@ -105,7 +101,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
||||
}
|
||||
}, rejoinDelay);
|
||||
} else {
|
||||
// Not 24/7 — send inactivity message
|
||||
const prefix = (() => {
|
||||
try { return this._commands?.getPrefix?.(guildId) ?? "%"; } catch (_) { return "%"; }
|
||||
})();
|
||||
@@ -125,16 +120,12 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
||||
message.channel.send({ embeds: [embed] });
|
||||
});
|
||||
|
||||
// Mark as pending so concurrent commands see the channel is taken,
|
||||
// but don't add to playerMap until join() succeeds to avoid phantom
|
||||
// entries inflating the player count.
|
||||
this.players._pendingJoins.add(cleanChannelId);
|
||||
|
||||
const joiningEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joining"));
|
||||
const statusMsg = await message.reply({ embeds: [joiningEmbed] });
|
||||
try {
|
||||
await p.join(cleanChannelId);
|
||||
// Only add to playerMap after join succeeds
|
||||
this.players.playerMap.set(cleanChannelId, p);
|
||||
this.players._pendingJoins.delete(cleanChannelId);
|
||||
const okEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joined", { channel: cid }));
|
||||
@@ -162,11 +153,9 @@ export const command = new CommandBuilder()
|
||||
);
|
||||
|
||||
export async function run(message, data) {
|
||||
// Check if a channel argument was provided (mention like <#123456>, bare ID, or name)
|
||||
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
|
||||
|
||||
if (rawArg) {
|
||||
// Parse channel mention <#ID>, bare numeric ID, or channel name
|
||||
const mentionMatch = rawArg.match(/^<#(\d+)>$/);
|
||||
const idMatch = rawArg.match(/^(\d{15,})$/);
|
||||
let resolvedId = null;
|
||||
@@ -176,14 +165,12 @@ export async function run(message, data) {
|
||||
} else if (idMatch) {
|
||||
resolvedId = idMatch[1];
|
||||
} else {
|
||||
// Try to look up by name
|
||||
const guildId = cleanId(getGuildId(message));
|
||||
const allChannels = [
|
||||
...(this.client?.channels?.values?.() ?? [])
|
||||
];
|
||||
const match = allChannels.find(c => {
|
||||
const cServerId = cleanId(c.guildId ?? c.guild?.id ?? c.server_id ?? c.serverId);
|
||||
// Fluxer uses numeric channel types: 0=text, 2=voice, 4=category, 5=link
|
||||
const isVoice = c.type === 2;
|
||||
return isVoice && cServerId === guildId &&
|
||||
(c.name?.toLowerCase() === rawArg.toLowerCase());
|
||||
@@ -200,7 +187,6 @@ export async function run(message, data) {
|
||||
return this.players.initPlayer(message, resolvedId);
|
||||
}
|
||||
|
||||
// No argument — auto-detect the user's current voice channel
|
||||
const cid = this.players.checkVoiceChannels(message);
|
||||
|
||||
if (!cid) {
|
||||
|
||||
@@ -23,7 +23,6 @@ export const command = new CommandBuilder()
|
||||
.setRequired(false)
|
||||
);
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
function notConfigured(msg) {
|
||||
return {
|
||||
@@ -41,7 +40,6 @@ function notLinked(prefix) {
|
||||
};
|
||||
}
|
||||
|
||||
// Valid categories that can be played (without a sub-number)
|
||||
const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums"];
|
||||
|
||||
function buildLastFmTrackMeta(track) {
|
||||
@@ -72,7 +70,6 @@ async function resolveLastFmTrack(player, track, resolveProvider = "yt") {
|
||||
*
|
||||
* @param {object} ctx - The command `this` context (has .lastfm, .getPlayer, .handler, .t)
|
||||
* @param {object} msg - The message object
|
||||
* @param {string} userId - Discord user ID
|
||||
* @param {string} category - "loved", "top", "recent", or "playlist"
|
||||
* @param {object} [options]
|
||||
* @param {string} [options.period] - Period for top tracks
|
||||
@@ -88,7 +85,6 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
||||
|
||||
if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(msg));
|
||||
|
||||
// Validate category
|
||||
const validCategories = [...SIMPLE_CATEGORIES, "playlist"];
|
||||
if (!validCategories.includes(category)) {
|
||||
return msg.reply({
|
||||
@@ -98,7 +94,6 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
||||
});
|
||||
}
|
||||
|
||||
// Playlist requires an ID
|
||||
if (category === "playlist" && !options.playlistId) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
||||
@@ -107,19 +102,15 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
||||
});
|
||||
}
|
||||
|
||||
// Check if user is linked
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(prefix));
|
||||
|
||||
// Get a player (user must be in a voice channel)
|
||||
const p = await ctx.getPlayer(msg, true, true, true);
|
||||
if (!p) return;
|
||||
|
||||
// Fetch tracks from Last.fm
|
||||
const categoryEmoji = { loved: "❤️", top: "📊", recent: "🕐", playlist: "📋", albums: "💿" }[category];
|
||||
const categoryLabel = { loved: "Loved", top: "Top", recent: "Recent", playlist: "Playlist", albums: "Top Albums" }[category];
|
||||
|
||||
// Show which provider is being used for resolving tracks (if not the default YouTube)
|
||||
const resolveLabel = resolveProvider !== "yt" ? ` via ${resolveProvider.toUpperCase()}` : "";
|
||||
|
||||
let statusMsg;
|
||||
@@ -152,7 +143,6 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
||||
return;
|
||||
}
|
||||
|
||||
// Play each track sequentially — first one via play(), rest added to queue
|
||||
let added = 0;
|
||||
let failed = 0;
|
||||
|
||||
@@ -200,14 +190,12 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
||||
* @returns {{ category: string, playlistId?: string|number }}
|
||||
*/
|
||||
function parsePlayArgs(msg, data) {
|
||||
// Try from the token option first
|
||||
let raw = data.get("token")?.value;
|
||||
if (!raw) {
|
||||
const content = msg.message?.content ?? "";
|
||||
const args = content.split(/\s+/);
|
||||
const playIdx = args.indexOf("play");
|
||||
if (playIdx >= 0 && args[playIdx + 1]) {
|
||||
// Collect everything after "play"
|
||||
raw = args.slice(playIdx + 1).join(" ");
|
||||
}
|
||||
}
|
||||
@@ -216,9 +204,6 @@ function parsePlayArgs(msg, data) {
|
||||
|
||||
const lower = raw.toLowerCase().trim();
|
||||
|
||||
// Sub-provider syntax: "td:top", "sp", "lf:loved"
|
||||
// Non-lastfm providers only allow "top" (or bare provider defaults to "top")
|
||||
// Last.fm as resolve provider allows all categories: loved, top, recent, albums, playlist
|
||||
const subMatch = lower.match(/^([a-z]+):\s*(.*)$/);
|
||||
if (subMatch) {
|
||||
const maybeProvider = subMatch[1];
|
||||
@@ -227,16 +212,13 @@ function parsePlayArgs(msg, data) {
|
||||
const isLastFmProvider = maybeProvider === "lf" || maybeProvider === "lastfm";
|
||||
|
||||
if (!rest) {
|
||||
// No category specified — default based on provider
|
||||
if (isLastFmProvider) {
|
||||
return { category: "", resolveProvider: maybeProvider, showAllCategories: true };
|
||||
}
|
||||
// All other providers default to "top"
|
||||
return { category: "top", resolveProvider: maybeProvider };
|
||||
}
|
||||
|
||||
if (isLastFmProvider) {
|
||||
// Last.fm as resolve provider: all categories allowed
|
||||
const playlistMatch = rest.match(/^playlist\s+(\d+)$/);
|
||||
if (playlistMatch) {
|
||||
return { category: "playlist", playlistId: playlistMatch[1], resolveProvider: maybeProvider };
|
||||
@@ -245,18 +227,14 @@ function parsePlayArgs(msg, data) {
|
||||
return { category: rest, resolveProvider: maybeProvider };
|
||||
}
|
||||
} else {
|
||||
// Non-lastfm providers: only "top" allowed
|
||||
if (rest === "top") {
|
||||
return { category: "top", resolveProvider: maybeProvider };
|
||||
}
|
||||
// Any other category with a non-lastfm provider is invalid
|
||||
return { category: "", resolveProvider: maybeProvider, invalidCategory: rest };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Bare provider without colon: "td", "sp", "yt" → defaults to "top"
|
||||
// (lf/lastfm as bare provider shows all categories instead)
|
||||
if (PROVIDER_CHOICES.includes(lower)) {
|
||||
const isLastFmProvider = lower === "lf" || lower === "lastfm";
|
||||
if (isLastFmProvider) {
|
||||
@@ -265,13 +243,11 @@ function parsePlayArgs(msg, data) {
|
||||
return { category: "top", resolveProvider: lower };
|
||||
}
|
||||
|
||||
// "playlist 3" or "playlist 1"
|
||||
const playlistMatch = lower.match(/^playlist\s+(\d+)$/);
|
||||
if (playlistMatch) {
|
||||
return { category: "playlist", playlistId: playlistMatch[1] };
|
||||
}
|
||||
|
||||
// "loved", "top", "recent"
|
||||
if (SIMPLE_CATEGORIES.includes(lower)) {
|
||||
return { category: lower };
|
||||
}
|
||||
@@ -279,7 +255,6 @@ function parsePlayArgs(msg, data) {
|
||||
return { category: "" };
|
||||
}
|
||||
|
||||
// ── Run ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function run(msg, data) {
|
||||
const lastfm = this.lastfm;
|
||||
@@ -290,9 +265,7 @@ export async function run(msg, data) {
|
||||
const userId = msg.message?.author?.id ?? msg.author?.id;
|
||||
|
||||
switch (action) {
|
||||
// ── Link ────────────────────────────────────────────────────────────────
|
||||
case "link": {
|
||||
// Check if already linked
|
||||
const existing = await lastfm.getUser(userId);
|
||||
if (existing) {
|
||||
return msg.reply({
|
||||
@@ -302,7 +275,6 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// Step 1: Get auth token
|
||||
let token;
|
||||
try {
|
||||
token = await lastfm.getAuthToken();
|
||||
@@ -314,7 +286,6 @@ export async function run(msg, data) {
|
||||
|
||||
const authUrl = lastfm.getAuthUrl(token);
|
||||
|
||||
// Send auth URL via DM so it's private
|
||||
let sent = false;
|
||||
try {
|
||||
const dm = await msg.author.createDM();
|
||||
@@ -336,7 +307,6 @@ export async function run(msg, data) {
|
||||
});
|
||||
sent = true;
|
||||
} catch {
|
||||
// DM failed — send in channel with a warning
|
||||
}
|
||||
|
||||
const replyEmbed = new EmbedBuilder()
|
||||
@@ -350,9 +320,7 @@ export async function run(msg, data) {
|
||||
return msg.reply({ embeds: [replyEmbed] });
|
||||
}
|
||||
|
||||
// ── Confirm (completes the auth flow) ──────────────────────────────────
|
||||
case "confirm": {
|
||||
// Get token from the option, or fall back to parsing the message
|
||||
let tokenValue = data.get("token")?.value;
|
||||
if (!tokenValue) {
|
||||
const rawContent = msg.message?.content ?? "";
|
||||
@@ -385,7 +353,6 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// ── Unlink ─────────────────────────────────────────────────────────────
|
||||
case "unlink": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(prefix));
|
||||
@@ -396,7 +363,6 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// ── Toggle scrobbling ──────────────────────────────────────────────────
|
||||
case "scrobble": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(prefix));
|
||||
@@ -414,7 +380,6 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// ── Now playing info ───────────────────────────────────────────────────
|
||||
case "np": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(prefix));
|
||||
@@ -445,7 +410,6 @@ export async function run(msg, data) {
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
// ── Profile ────────────────────────────────────────────────────────────
|
||||
case "profile": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(prefix));
|
||||
@@ -459,7 +423,6 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// Sync scrobble count in background (keeps leaderboard fresh)
|
||||
lastfm.syncUserScrobbleCount(userId).catch(() => {});
|
||||
|
||||
const embed = new EmbedBuilder()
|
||||
@@ -477,7 +440,6 @@ export async function run(msg, data) {
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
// ── Playlists ──────────────────────────────────────────────────────────
|
||||
case "playlists": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(prefix));
|
||||
@@ -514,11 +476,9 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// ── Play (loved/top/recent/playlist tracks as queue) ────────────────────
|
||||
case "play": {
|
||||
const parsed = parsePlayArgs(msg, data);
|
||||
|
||||
// Invalid category used with a non-lastfm provider (e.g. "sp:loved", "td:recent")
|
||||
if (parsed.invalidCategory) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
||||
@@ -571,7 +531,6 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// ── Loved tracks ──────────────────────────────────────────────────────
|
||||
case "loved": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(prefix));
|
||||
@@ -594,7 +553,6 @@ export async function run(msg, data) {
|
||||
return msg.reply({ embeds: [buildTrackList(user.username, "❤️ Loved Tracks", tracks, false, prefix)] });
|
||||
}
|
||||
|
||||
// ── Top tracks ─────────────────────────────────────────────────────────
|
||||
case "top": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(prefix));
|
||||
@@ -617,7 +575,6 @@ export async function run(msg, data) {
|
||||
return msg.reply({ embeds: [buildTrackList(user.username, "📊 Top Tracks", tracks, true, prefix)] });
|
||||
}
|
||||
|
||||
// ── Leaderboard ─────────────────────────────────────────────────────
|
||||
case "leaderboard":
|
||||
case "lb": {
|
||||
let lb;
|
||||
@@ -637,18 +594,14 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// Single page — no pagination needed
|
||||
if (lb.totalPages <= 1) {
|
||||
const embed = buildLeaderboardEmbed(lb, 0, prefix);
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
// Multi-page with emoji navigation
|
||||
let currentPage = 0;
|
||||
|
||||
const buildPage = (pageIdx, expired = false) => {
|
||||
// Fetch for this page index (we pre-load only page 0;
|
||||
// subsequent pages are fetched on navigation)
|
||||
const footerText = expired
|
||||
? "Controls expired"
|
||||
: `Page ${pageIdx + 1}/${lb.totalPages} • Use ◀️▶️ to navigate`;
|
||||
@@ -701,7 +654,6 @@ export async function run(msg, data) {
|
||||
currentPage = currentPage < lb.totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
// Fetch the page data from DB
|
||||
try {
|
||||
lb = await lastfm.getLeaderboard(currentPage, 10);
|
||||
} catch {
|
||||
@@ -715,7 +667,6 @@ export async function run(msg, data) {
|
||||
break;
|
||||
}
|
||||
|
||||
// ── Recent tracks ──────────────────────────────────────────────────────
|
||||
case "recent": {
|
||||
const user = await lastfm.getUser(userId);
|
||||
if (!user) return msg.reply(notLinked(prefix));
|
||||
@@ -781,7 +732,6 @@ export async function run(msg, data) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Track list embed builder ──────────────────────────────────────────────────
|
||||
|
||||
function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") {
|
||||
const lines = tracks.map((t, i) => {
|
||||
@@ -802,7 +752,6 @@ function buildTrackList(username, title, tracks, showPlaycount = false, prefix =
|
||||
.setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` });
|
||||
}
|
||||
|
||||
// ── Leaderboard embed builder ─────────────────────────────────────────────────
|
||||
|
||||
function buildLeaderboardEmbed(lb, pageIdx, prefix) {
|
||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||
|
||||
@@ -49,19 +49,12 @@ export async function run(msg, data) {
|
||||
?? msg.message?.serverId;
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
|
||||
// Gather all active players in this guild.
|
||||
// resolvePlayerGuildId handles players whose _guildId is still null by
|
||||
// checking the channel cache — critical for the multi-voice use case where
|
||||
// a player may have been joined before _guildId was written.
|
||||
const client = this.client;
|
||||
const guildPlayers = [...this.players.playerMap.entries()].filter(([mapKey, p]) => {
|
||||
if (p?._destroyed) return false;
|
||||
return resolvePlayerGuildId(p, mapKey, client) === cleanGuildId;
|
||||
});
|
||||
|
||||
// Resolve the target channel to leave:
|
||||
// 1. If a channel option was provided, use that
|
||||
// 2. Otherwise, use the user's current voice channel
|
||||
const specifiedChannel = data?.get("channel")?.value;
|
||||
let targetChannelId = null;
|
||||
|
||||
@@ -72,12 +65,10 @@ export async function run(msg, data) {
|
||||
if (userChannelId) targetChannelId = cleanId(userChannelId);
|
||||
}
|
||||
|
||||
// If we still don't have a target channel
|
||||
if (!targetChannelId) {
|
||||
if (guildPlayers.length === 0) {
|
||||
return msg.reply(embed(this.t(msg, "responses.leave.notInVoice")));
|
||||
}
|
||||
// User not in voice and no channel specified — list all channels the bot is in
|
||||
const channelList = guildPlayers.map(([mapKey, p]) => {
|
||||
const id = cleanId(p._channelId ?? mapKey);
|
||||
return id ? `<#${id}>` : "`unknown`";
|
||||
@@ -90,10 +81,6 @@ export async function run(msg, data) {
|
||||
));
|
||||
}
|
||||
|
||||
// Find the player for the target channel.
|
||||
// Match against both the map key and _channelId because after a voice-move
|
||||
// these can differ (the map key stays as the original join channel ID while
|
||||
// _channelId updates to the new channel).
|
||||
const player = this.players.playerMap.get(targetChannelId)
|
||||
?? guildPlayers.find(([mapKey, p]) =>
|
||||
cleanId(p._channelId) === targetChannelId || cleanId(mapKey) === targetChannelId
|
||||
@@ -101,7 +88,6 @@ export async function run(msg, data) {
|
||||
?? null;
|
||||
|
||||
if (!player) {
|
||||
// No player in that channel — check if user picked a non-voice channel
|
||||
if (guildPlayers.length === 0) {
|
||||
return msg.reply(embed(this.t(msg, "responses.leave.notInVoice")));
|
||||
}
|
||||
@@ -122,7 +108,6 @@ export async function run(msg, data) {
|
||||
const activeChannelId = cleanId(player._channelId) || targetChannelId;
|
||||
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
|
||||
|
||||
// ── 24/7 handling ────────────────────────────────────────────────────────
|
||||
const set = this.getSettings(msg);
|
||||
const raw = set?.get("stay_247");
|
||||
const ch247 = (!raw || raw === "none")
|
||||
@@ -131,11 +116,6 @@ export async function run(msg, data) {
|
||||
? new Set(raw.map(id => cleanId(id)).filter(Boolean))
|
||||
: new Set([cleanId(raw)]);
|
||||
|
||||
// ── Snapshot all 247 auto channels in this guild BEFORE leaving ────────
|
||||
// When the bot leaves one channel, the gateway may send a guild-level
|
||||
// disconnect that kills ALL voice connections in the guild (not just the
|
||||
// target). By snapshotting beforehand, we can schedule rejoins for every
|
||||
// 24/7 auto channel that was collateral-disconnected.
|
||||
const other247AutoChannels = [...ch247].filter(id => {
|
||||
if (id === activeChannelId || id === homeChannelId || id === targetChannelId) return false;
|
||||
const mode = get247ChannelMode(set, id);
|
||||
@@ -165,19 +145,13 @@ export async function run(msg, data) {
|
||||
}
|
||||
}, leave247Delay);
|
||||
|
||||
// ── Rejoin other 24/7 auto channels that may have been disconnected ──
|
||||
// If the gateway sent a guild-level leave, all other 24/7 auto channels
|
||||
// also lost their connections. Schedule a rejoin for each one with a
|
||||
// staggered delay to avoid overloading the global join queue.
|
||||
if (other247AutoChannels.length > 0) {
|
||||
const rejoinBaseDelay = leave247Delay;
|
||||
const rejoinStagger = this.config?.timers?.rejoin247Delay ?? 3000;
|
||||
for (let i = 0; i < other247AutoChannels.length; i++) {
|
||||
const otherChannelId = other247AutoChannels[i];
|
||||
const otherPlayer = this.players.playerMap.get(otherChannelId);
|
||||
// Only rejoin if the player is gone (was collateral-disconnected)
|
||||
if (!otherPlayer || otherPlayer._destroyed) {
|
||||
// Clean up the dead player from the map
|
||||
if (otherPlayer) {
|
||||
this.players.playerMap.delete(otherChannelId);
|
||||
try { otherPlayer.destroy(); } catch (_) {}
|
||||
@@ -197,8 +171,6 @@ export async function run(msg, data) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Mode is "on" — bot left, won't rejoin automatically for this channel.
|
||||
// But still check if other 24/7 auto channels need rejoining.
|
||||
msg.reply(embed(this.t(msg, "responses.leave.left247On", { prefix: set?.get("prefix") ?? "%" })));
|
||||
|
||||
if (other247AutoChannels.length > 0) {
|
||||
|
||||
@@ -41,11 +41,9 @@ export async function run(message, data) {
|
||||
|
||||
let desc = "";
|
||||
|
||||
// ── Header: track count + remaining time ──────────────────────────────
|
||||
const remaining = p.getQueueRemainingTime();
|
||||
desc += `📋 **${totalTracks} track${totalTracks !== 1 ? "s" : ""} in queue** • ⏱️ \`${remaining}\`\n`;
|
||||
|
||||
// ── Now Playing block ─────────────────────────────────────────────────
|
||||
if (current) {
|
||||
const elapsed = p.getCurrentElapsedDuration();
|
||||
const total = p.getCurrentDuration();
|
||||
@@ -60,7 +58,6 @@ export async function run(message, data) {
|
||||
|
||||
desc += `\n`;
|
||||
|
||||
// ── Queue list ────────────────────────────────────────────────────────
|
||||
if (totalTracks === 0) {
|
||||
desc += this.t(message, "responses.list.emptyInline");
|
||||
} else {
|
||||
@@ -73,8 +70,6 @@ export async function run(message, data) {
|
||||
let title = vid.title;
|
||||
if (title.length > 45) title = title.slice(0, 42) + "...";
|
||||
title = link ? `[${title}](${link})` : title;
|
||||
// Mark the very first item in the queue as "Up Next" — useful after
|
||||
// a bot recovery or shuffle so the next song's position is obvious.
|
||||
const upNext = (start + i === 0) ? " ▶" : "";
|
||||
desc += `\`${index}.\` ${title}${upNext} • \`${dur}\`\n`;
|
||||
});
|
||||
|
||||
+2
-10
@@ -24,7 +24,6 @@ export async function run(message) {
|
||||
return message.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
// Animated loading spinner
|
||||
let frame = 0;
|
||||
const loadingMsg = await message.reply({ embeds: [
|
||||
new EmbedBuilder().setColor(getGlobalColor())
|
||||
@@ -67,25 +66,21 @@ export async function run(message) {
|
||||
const MAX_DESC = 4096;
|
||||
let totalPages = Math.ceil(totalLines / LINES_PER_PAGE);
|
||||
|
||||
// Build page payloads — each is the raw lyric lines for that page
|
||||
const pages = [];
|
||||
for (let i = 0; i < totalLines; i += LINES_PER_PAGE) {
|
||||
pages.push(lines.slice(i, i + LINES_PER_PAGE).join("\n"));
|
||||
}
|
||||
|
||||
// ── Re-check: if a page's content + header + code block exceeds 4096, re-split
|
||||
// into smaller chunks so setDescription never throws RangeError. ──────────
|
||||
const CODE_WRAP = 13; // "```\n" (4) + "\n```" (5) + header-ish overhead
|
||||
const CODE_WRAP = 13;
|
||||
{
|
||||
const reshaped = [];
|
||||
for (const pageText of pages) {
|
||||
const headerLine = `by *${artist}*${syncIndicator}`;
|
||||
const overhead = headerLine.length + 1 + 1 + CODE_WRAP; // header + blank + ``` + ```
|
||||
const overhead = headerLine.length + 1 + 1 + CODE_WRAP;
|
||||
const budget = MAX_DESC - overhead;
|
||||
if (pageText.length <= budget) {
|
||||
reshaped.push(pageText);
|
||||
} else {
|
||||
// Split this page's text into chunks that fit
|
||||
const pageLines = pageText.split("\n");
|
||||
let chunk = "";
|
||||
for (const ln of pageLines) {
|
||||
@@ -104,7 +99,6 @@ export async function run(message) {
|
||||
totalPages = pages.length;
|
||||
}
|
||||
|
||||
// ── Single page — no pagination needed ────────────────────────────────────
|
||||
if (totalPages === 1) {
|
||||
const headerLine = `by *${artist}*${syncIndicator}`;
|
||||
const descBody = pages[0];
|
||||
@@ -119,7 +113,6 @@ export async function run(message) {
|
||||
return message.reply({ embeds: [singleEmbed] });
|
||||
}
|
||||
|
||||
// ── Multi-page ────────────────────────────────────────────────────────────
|
||||
let currentPage = 0;
|
||||
let emojiRemoveTimeout;
|
||||
|
||||
@@ -177,7 +170,6 @@ export async function run(message) {
|
||||
|
||||
resetEmojiTimer();
|
||||
|
||||
// Full session close after SESSION_MS
|
||||
setTimeout(() => {
|
||||
clearTimeout(emojiRemoveTimeout);
|
||||
unobserve();
|
||||
|
||||
+4
-42
@@ -7,10 +7,10 @@ import { playLastFmCategory } from "./lastfm.mjs";
|
||||
/**
|
||||
* Parse a Last.fm music URL and extract artist and track info.
|
||||
* Supports:
|
||||
* https://www.last.fm/music/Drake/ICEMAN/Make+Them+Cry
|
||||
* https://www.last.fm/music/SAJA+BOYS/_/Soda+Pop
|
||||
* https://www.last.fm/music/Drake/_/Make+Them+Cry ("_" = album placeholder)
|
||||
* https://www.last.fm/music/Drake (artist only)
|
||||
* https:
|
||||
* https:
|
||||
* https:
|
||||
* https:
|
||||
*
|
||||
* @param {string} url
|
||||
* @returns {{ artist: string, track: string|null, album: string|null, url: string } | null}
|
||||
@@ -20,8 +20,6 @@ function parseLastFmUrl(url) {
|
||||
const u = new URL(url);
|
||||
if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null;
|
||||
|
||||
// Path format: /music/Artist[/Album][/Track]
|
||||
// Or: /music/Artist/_/Track (underscore = album placeholder)
|
||||
const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/);
|
||||
if (!match) return null;
|
||||
|
||||
@@ -33,12 +31,9 @@ function parseLastFmUrl(url) {
|
||||
let album = null;
|
||||
|
||||
if (segment3) {
|
||||
// /music/Artist/Album/Track or /music/Artist/_/Track
|
||||
album = segment2 === "_" ? null : segment2;
|
||||
track = segment3;
|
||||
} else if (segment2 && segment2 !== "_") {
|
||||
// /music/Artist/Track (no album segment)
|
||||
// Could be an album page or track page — treat as track if short enough
|
||||
track = segment2;
|
||||
}
|
||||
|
||||
@@ -63,7 +58,6 @@ function isLastFmUrl(str) {
|
||||
}
|
||||
}
|
||||
|
||||
// Last.fm provider keywords that trigger special play logic
|
||||
const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
|
||||
|
||||
/**
|
||||
@@ -73,8 +67,6 @@ const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
|
||||
*/
|
||||
function parseLastFmSubProvider(query) {
|
||||
const value = query.trim();
|
||||
// Non-lastfm providers only allow "top" (or bare provider defaults to "top")
|
||||
// Last.fm as resolve provider allows all categories: loved, top, recent, albums, playlist
|
||||
const subMatch = value.match(/^([a-z]+):\s*(.*)$/i);
|
||||
if (subMatch) {
|
||||
const maybeProvider = subMatch[1].toLowerCase();
|
||||
@@ -90,12 +82,10 @@ function parseLastFmSubProvider(query) {
|
||||
}
|
||||
|
||||
if (isLastFmProvider) {
|
||||
// Last.fm as resolve provider: all categories allowed
|
||||
if (LASTFM_PLAY_CATEGORIES.includes(rest) || rest.startsWith("playlist")) {
|
||||
return { category: rest, resolveProvider: maybeProvider };
|
||||
}
|
||||
} else {
|
||||
// Non-lastfm providers: only "top" allowed
|
||||
if (rest === "top") {
|
||||
return { category: "top", resolveProvider: maybeProvider };
|
||||
}
|
||||
@@ -104,7 +94,6 @@ function parseLastFmSubProvider(query) {
|
||||
}
|
||||
}
|
||||
|
||||
// Bare provider without colon: "td", "sp", "yt" → defaults to "top"
|
||||
const lower = value.toLowerCase();
|
||||
if (PROVIDER_CHOICES.includes(lower)) {
|
||||
const isLastFmProvider = lower === "lf" || lower === "lastfm";
|
||||
@@ -196,20 +185,11 @@ export async function run(message, data) {
|
||||
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
|
||||
const provider = inlineProvider ?? flagProvider ?? "ytm";
|
||||
|
||||
// ── Last.fm URL detection ────────────────────────────────────────────────
|
||||
// If the raw query (or extracted query) is a Last.fm URL, parse it to get
|
||||
// the artist and track name, then play it through the normal search pipeline
|
||||
// with Last.fm metadata attached for accurate scrobbling.
|
||||
//
|
||||
// Examples:
|
||||
// %play https://www.last.fm/music/Drake/ICEMAN/Make+Them+Cry
|
||||
// %play https://www.last.fm/music/SAJA+BOYS/_/Soda+Pop
|
||||
if (isLastFmUrl(rawQuery) || isLastFmUrl(query)) {
|
||||
const lfUrl = isLastFmUrl(rawQuery) ? rawQuery : query;
|
||||
const parsed = parseLastFmUrl(lfUrl);
|
||||
|
||||
if (parsed && parsed.track) {
|
||||
// We have artist + track — search using the combined query with Last.fm metadata
|
||||
const lastfmTrackMeta = {
|
||||
artist: parsed.artist,
|
||||
name: parsed.track,
|
||||
@@ -237,7 +217,6 @@ export async function run(message, data) {
|
||||
}
|
||||
|
||||
if (parsed && !parsed.track) {
|
||||
// Artist-only URL (e.g. /music/Drake) — search for the artist
|
||||
const p = await this.getPlayer(message, true, true, true);
|
||||
if (!p) return;
|
||||
|
||||
@@ -258,15 +237,11 @@ export async function run(message, data) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Last.fm special provider: %play lastfm:loved / lastfm:top / lastfm:recent / lastfm:playlist 1 ──
|
||||
// Also supports sub-provider syntax: %play lastfm:td:top (play Last.fm top tracks, search on Tidal)
|
||||
// Bare provider defaults: %play lastfm:sp → top tracks on Spotify, %play lastfm:td → top tracks on Tidal
|
||||
if (provider === "lastfm" || provider === "lf") {
|
||||
const parsed = parseLastFmSubProvider(query);
|
||||
const lowerQuery = parsed.category;
|
||||
const resolveProvider = parsed.resolveProvider;
|
||||
|
||||
// Invalid category used with a non-lastfm provider (e.g. "sp:loved", "td:recent")
|
||||
if (parsed.invalidCategory) {
|
||||
return message.reply({
|
||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(
|
||||
@@ -275,7 +250,6 @@ export async function run(message, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// If lf/lastfm used as resolve provider without a category, show help
|
||||
if (!lowerQuery && resolveProvider && (resolveProvider === "lf" || resolveProvider === "lastfm")) {
|
||||
return message.reply({
|
||||
embeds: [new EmbedBuilder().setColor("#ff0000").setDescription([
|
||||
@@ -291,13 +265,11 @@ export async function run(message, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// Simple categories: lastfm:loved, lastfm:top, lastfm:recent
|
||||
if (LASTFM_PLAY_CATEGORIES.includes(lowerQuery)) {
|
||||
const userId = message.message?.author?.id ?? message.author?.id;
|
||||
return playLastFmCategory(this, message, userId, lowerQuery, { resolveProvider });
|
||||
}
|
||||
|
||||
// Playlist: lastfm:playlist 1 or lastfm:playlist 3
|
||||
const playlistMatch = lowerQuery.match(/^playlist\s+(\d+)$/);
|
||||
if (playlistMatch) {
|
||||
const userId = message.message?.author?.id ?? message.author?.id;
|
||||
@@ -307,22 +279,15 @@ export async function run(message, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// ── Freeform Last.fm search: %play lastfm:soda pop or %play lastfm:drake make them cry ──
|
||||
// If the query after lastfm: is NOT a recognized category, treat it as a
|
||||
// freeform track search on Last.fm. This uses Last.fm's track.search API
|
||||
// to find the best match, then resolves it for playback.
|
||||
if (lowerQuery && !LASTFM_PLAY_CATEGORIES.includes(lowerQuery) && !lowerQuery.startsWith("playlist")) {
|
||||
const lastfm = this.lastfm;
|
||||
if (lastfm && lastfm.enabled) {
|
||||
// Try to parse as "track by artist" or "artist - track" first
|
||||
const trackMeta = parseLastFmTrackQuery(query);
|
||||
let searchResult;
|
||||
|
||||
if (trackMeta) {
|
||||
// Direct artist+track from the query — use it directly
|
||||
searchResult = { artist: trackMeta.artist, name: trackMeta.name, url: "" };
|
||||
} else {
|
||||
// Freeform query — search Last.fm for the best match
|
||||
let statusMsg = null;
|
||||
try {
|
||||
statusMsg = await message.reply({
|
||||
@@ -346,7 +311,6 @@ export async function run(message, data) {
|
||||
}
|
||||
}
|
||||
|
||||
// We have a Last.fm result — play it using the combined query with metadata
|
||||
const lastfmTrackMeta = {
|
||||
artist: searchResult.artist,
|
||||
name: searchResult.name,
|
||||
@@ -394,7 +358,6 @@ export async function run(message, data) {
|
||||
try {
|
||||
statusMsg = await message.reply({ embeds: [searchEmbed] });
|
||||
} catch (err) {
|
||||
// Fluxer API timed out sending the status message — continue without it
|
||||
}
|
||||
|
||||
const playQuery = lastfmTrackMeta
|
||||
@@ -407,7 +370,6 @@ export async function run(message, data) {
|
||||
if (statusMsg) {
|
||||
statusMsg.edit({ embeds: [embed] }).catch(() => {});
|
||||
} else {
|
||||
// statusMsg failed to send earlier, fall back to a fresh reply
|
||||
message.reply({ embeds: [embed] }).catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -8,7 +8,6 @@ export const command = new CommandBuilder()
|
||||
.setDescription("Create an interactive player control panel with live progress", "commands.player")
|
||||
.setCategory("music");
|
||||
|
||||
// Visual states
|
||||
const STATES = {
|
||||
playing: "🎵",
|
||||
paused: "⏸️",
|
||||
@@ -16,7 +15,6 @@ const STATES = {
|
||||
loading: "⏳"
|
||||
};
|
||||
|
||||
// Control layout
|
||||
const CONTROLS = {
|
||||
prev: { emoji: "⏮️", action: "previous", desc: "Previous" },
|
||||
play: { emoji: "▶️", action: "resume", desc: "Play" },
|
||||
@@ -32,7 +30,6 @@ const CONTROLS = {
|
||||
close: { emoji: "❌", action: "close", desc: "Close" }
|
||||
};
|
||||
|
||||
// Progress bar characters
|
||||
const PROGRESS = {
|
||||
filled: "▰",
|
||||
empty: "▱",
|
||||
@@ -41,7 +38,6 @@ const PROGRESS = {
|
||||
end: "▕"
|
||||
};
|
||||
|
||||
// Auto-remove timer: 1 minute
|
||||
const EMOJI_REMOVE_TIMEOUT = 60000;
|
||||
|
||||
export async function run(msg) {
|
||||
@@ -98,7 +94,6 @@ export async function run(msg) {
|
||||
const queueSize = player.queue.size();
|
||||
const loopStatus = player.queue.songLoop ? "🔂 Song" : player.queue.loop ? "🔁 Queue" : "❌ Off";
|
||||
|
||||
// FIXED: Show stacked filters if multiple are active
|
||||
let filterStatus = "🔇 Off";
|
||||
if (player.activeFilter) {
|
||||
if (player.activeFilter.label.includes("+")) {
|
||||
|
||||
@@ -23,7 +23,6 @@ function embed(desc) {
|
||||
const __dirname = path.dirname(new URL(import.meta.url).pathname);
|
||||
const ROOT = path.resolve(__dirname, "..");
|
||||
|
||||
// ── Reload a single command ───────────────────────────────────────────────────
|
||||
async function reloadCommand(ctx, msg, name) {
|
||||
if (name === "index")
|
||||
return { ok: false, msg: ctx.t(msg, "responses.reload.indexNoReload") };
|
||||
@@ -34,14 +33,11 @@ async function reloadCommand(ctx, msg, name) {
|
||||
const file = ctx.commandFiles.get(command.uid);
|
||||
if (!file) return { ok: false, msg: ctx.t(msg, "responses.reload.noFileTracked", { name }) };
|
||||
|
||||
// Unregister old
|
||||
command.subcommands.forEach(sub => ctx.runnables.delete(sub.uid));
|
||||
ctx.handler.removeCommand(command);
|
||||
ctx.runnables.delete(command.uid);
|
||||
ctx.commandFiles.delete(command.uid);
|
||||
|
||||
// Re-import with cache-buster — use pathToFileURL so Windows drive letters and
|
||||
// spaces in paths are handled correctly (plain "file://" + path breaks on Windows).
|
||||
const url = pathToFileURL(file).href + "?t=" + Date.now();
|
||||
const cData = await import(url);
|
||||
|
||||
@@ -63,7 +59,6 @@ async function reloadCommand(ctx, msg, name) {
|
||||
return { ok: true, msg: ctx.t(msg, "responses.reload.reloaded", { name }) };
|
||||
}
|
||||
|
||||
// ── Reload a src/ or audio/ module ───────────────────────────────────────────
|
||||
async function reloadModule(ctx, msg, filePath, label) {
|
||||
if (!fs.existsSync(filePath))
|
||||
return { ok: false, msg: ctx.t(msg, "responses.reload.fileNotFound", { label }) };
|
||||
@@ -75,7 +70,6 @@ async function reloadModule(ctx, msg, filePath, label) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── List all module files in a subdirectory ───────────────────────────────────
|
||||
function allModuleFiles(subdir) {
|
||||
const dir = path.join(ROOT, subdir);
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
@@ -84,7 +78,6 @@ function allModuleFiles(subdir) {
|
||||
.map(f => ({ file: path.join(dir, f), label: `${subdir}/${f}` }));
|
||||
}
|
||||
|
||||
// ── Paginated embed helper ────────────────────────────────────────────────────
|
||||
async function showPaged(msg, title, lines, pageSize = 14) {
|
||||
const pages = [];
|
||||
for (let i = 0; i < lines.length; i += pageSize)
|
||||
@@ -120,7 +113,6 @@ async function showPaged(msg, title, lines, pageSize = 14) {
|
||||
setTimeout(() => { unsub?.(); }, 5 * 60_000);
|
||||
}
|
||||
|
||||
// ── Batch results → paginated display ────────────────────────────────────────
|
||||
async function showResults(msg, results, label) {
|
||||
const ok = results.filter(r => r.ok).length;
|
||||
const bad = results.filter(r => !r.ok).length;
|
||||
@@ -128,11 +120,9 @@ async function showResults(msg, results, label) {
|
||||
await showPaged(msg, `🔄 Reload — ${label}`, [header, "", ...results.map(r => r.msg)]);
|
||||
}
|
||||
|
||||
// ── Main ──────────────────────────────────────────────────────────────────────
|
||||
export async function run(msg, data) {
|
||||
const target = (data.get("target")?.value ?? "").trim().toLowerCase();
|
||||
|
||||
// No target — show paginated list of everything reloadable
|
||||
if (!target) {
|
||||
const cmdLines = this.handler.commands.map(c => `📦 \`${c.name}\` *(command)*`);
|
||||
const srcLines = allModuleFiles("src").map(m => `🔧 \`${m.label}\` *(src)*`);
|
||||
@@ -150,7 +140,6 @@ export async function run(msg, data) {
|
||||
return showPaged(msg, this.t(msg, "responses.reload.availableTargetsTitle"), lines);
|
||||
}
|
||||
|
||||
// Batch keywords
|
||||
if (target === "commands") {
|
||||
const results = [];
|
||||
for (const c of [...this.handler.commands]) {
|
||||
@@ -187,13 +176,11 @@ export async function run(msg, data) {
|
||||
return showResults(msg, results, "Everything");
|
||||
}
|
||||
|
||||
// Single command by name
|
||||
if (this.handler.commands.some(c => c.name === target)) {
|
||||
const res = await reloadCommand(this, msg, target);
|
||||
return msg.reply(embed(res.msg));
|
||||
}
|
||||
|
||||
// Single src/ or audio/ module by filename (with or without extension/subdir)
|
||||
const allMods = [...allModuleFiles("src"), ...allModuleFiles("audio")];
|
||||
const mod = allMods.find(m =>
|
||||
m.label.toLowerCase() === target ||
|
||||
|
||||
+1
-8
@@ -5,7 +5,6 @@ import { PROVIDER_CHOICES, PROVIDER_NAMES } from "../src/constants/providers.mjs
|
||||
|
||||
const NUMBER_EMOJIS = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"];
|
||||
const CANCEL_EMOJI = "❌";
|
||||
// SESSION_MS is now read from config.timers.searchSessionTimeout (fallback: 30s)
|
||||
|
||||
function parseInlineProvider(raw) {
|
||||
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
|
||||
@@ -53,7 +52,6 @@ export async function run(msg, data) {
|
||||
|
||||
const name = PROVIDER_NAMES[provider] ?? "YouTube Music";
|
||||
|
||||
// Send loading embed
|
||||
const channel = msg.channel?.channel ?? msg.message?.channel;
|
||||
if (!channel?.send) return;
|
||||
|
||||
@@ -79,14 +77,12 @@ export async function run(msg, data) {
|
||||
).catch(() => null);
|
||||
if (!rawMsg) return;
|
||||
|
||||
// Fetch results
|
||||
const res = await p.fetchResults(query, msg.authorId, provider);
|
||||
if (!res?.count) {
|
||||
rawMsg.edit({ embeds: [makeEmbed(this.t(msg, "responses.search.noResults"))] }).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
// Build results embed
|
||||
const results = p.searches.get(msg.authorId) ?? [];
|
||||
const reactions = NUMBER_EMOJIS.slice(0, res.count);
|
||||
|
||||
@@ -107,7 +103,6 @@ export async function run(msg, data) {
|
||||
)]
|
||||
}).catch(() => {});
|
||||
|
||||
// Add reactions
|
||||
for (const emoji of [...reactions, CANCEL_EMOJI]) {
|
||||
await rawMsg.react(emoji).catch(() => {});
|
||||
}
|
||||
@@ -127,7 +122,6 @@ export async function run(msg, data) {
|
||||
const authorId = msg.message?.author?.id ?? msg.authorId;
|
||||
|
||||
const unobserve = wrapped.onReaction(allReactions, async (e, reactionMsg) => {
|
||||
// Only react to the command author — normalise across Fluxer reaction event shapes
|
||||
const reactorId = e.user_id ?? e.userId ?? e.user?.id ?? null;
|
||||
if (reactorId && reactorId !== authorId) return;
|
||||
|
||||
@@ -157,7 +151,6 @@ export async function run(msg, data) {
|
||||
}).catch(() => {});
|
||||
});
|
||||
|
||||
// Read session timeout from config (fallback 30 s)
|
||||
const SESSION_MS = this.config?.timers?.searchSessionTimeout ?? 30_000;
|
||||
const timer = setTimeout(() => {
|
||||
unobserve();
|
||||
@@ -165,5 +158,5 @@ export async function run(msg, data) {
|
||||
rawMsg.edit({
|
||||
embeds: [makeEmbed(this.t(msg, "responses.search.timedOut"), this.t(msg, "responses.search.sessionClosed"), `${name} — Search Results`)]
|
||||
}).catch(() => {});
|
||||
}, SESSION_MS); // configurable via config.timers.searchSessionTimeout
|
||||
}, SESSION_MS);
|
||||
}
|
||||
+2
-17
@@ -8,13 +8,11 @@ export const command = new CommandBuilder()
|
||||
.setRequirement(r => r.setOwnerOnly(true))
|
||||
.setCategory("util");
|
||||
|
||||
// Auto-remove timer: 1 minute
|
||||
const EMOJI_REMOVE_TIMEOUT = 60000;
|
||||
|
||||
export async function run(msg) {
|
||||
const guilds = [...this.client.guilds.values()];
|
||||
|
||||
// Fallback if the bot is in 0 servers
|
||||
if (guilds.length === 0) {
|
||||
const emptyEmbed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
@@ -27,8 +25,6 @@ export async function run(msg) {
|
||||
const MAX_DESC = 4096;
|
||||
const pages = [];
|
||||
|
||||
// Build pages dynamically — each page accumulates lines until it would
|
||||
// exceed the 4096-char description limit, then starts a new page.
|
||||
let currentLines = [];
|
||||
let currentLen = 0;
|
||||
|
||||
@@ -37,7 +33,7 @@ export async function run(msg) {
|
||||
let name = g.name || "unknown";
|
||||
if (name.length > 40) name = name.slice(0, 37) + "...";
|
||||
const line = `${i + 1}. **${name}** (\`${g.id}\`)`;
|
||||
const addedLen = line.length + (currentLines.length ? 1 : 0); // +1 for \n
|
||||
const addedLen = line.length + (currentLines.length ? 1 : 0);
|
||||
|
||||
if (currentLen + addedLen > MAX_DESC - 20 && currentLines.length > 0) {
|
||||
pages.push(currentLines.join("\n"));
|
||||
@@ -53,7 +49,6 @@ export async function run(msg) {
|
||||
|
||||
let currentPage = 0;
|
||||
|
||||
// Helper function to generate the embed for a specific page
|
||||
const buildPageContent = (pageIdx, expired = false) => {
|
||||
const embed = new EmbedBuilder()
|
||||
.setColor(getGlobalColor())
|
||||
@@ -71,10 +66,8 @@ export async function run(msg) {
|
||||
return { embeds: [embed] };
|
||||
};
|
||||
|
||||
// Send the initial message using the framework's wrapper
|
||||
const replyMsg = await msg.reply(buildPageContent(0));
|
||||
|
||||
// Safety check and single-page exit
|
||||
if (!replyMsg?.message) return;
|
||||
if (totalPages <= 1) return;
|
||||
|
||||
@@ -82,12 +75,10 @@ export async function run(msg) {
|
||||
let unobserve = null;
|
||||
let emojiTimeout = null;
|
||||
|
||||
// Add reactions
|
||||
for (const emoji of navEmojis) {
|
||||
await replyMsg.message.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
// Helper: Clear all reactions (matches player.mjs fallback logic)
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await replyMsg.message.removeAllReactions();
|
||||
@@ -100,7 +91,6 @@ export async function run(msg) {
|
||||
}
|
||||
};
|
||||
|
||||
// Helper: Reset the expiration timer
|
||||
const resetTimer = () => {
|
||||
clearTimeout(emojiTimeout);
|
||||
emojiTimeout = setTimeout(async () => {
|
||||
@@ -110,22 +100,17 @@ export async function run(msg) {
|
||||
}, EMOJI_REMOVE_TIMEOUT);
|
||||
};
|
||||
|
||||
// Start listening for reactions using the framework's native listener
|
||||
unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||
resetTimer(); // Reset the 1-minute timer when interacting
|
||||
resetTimer();
|
||||
|
||||
if (e.emoji_id === "⬅️") {
|
||||
// Go backward (loops to the end if on the first page)
|
||||
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
||||
} else if (e.emoji_id === "➡️") {
|
||||
// Go forward (loops to the beginning if on the last page)
|
||||
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
||||
}
|
||||
|
||||
// Update the embed using the framework's native edit method
|
||||
await replyMsg.edit(buildPageContent(currentPage)).catch(() => {});
|
||||
});
|
||||
|
||||
// Start the initial countdown
|
||||
resetTimer();
|
||||
}
|
||||
+2
-48
@@ -11,7 +11,6 @@ function embed(desc, opts = {}) {
|
||||
}
|
||||
|
||||
/** Build a rich embed with fields for the 24/7 status panel.
|
||||
* Fluxer EmbedBuilder does not have addField() (that's discord.js).
|
||||
* Instead, we build the base embed with EmbedBuilder, call .toJSON()
|
||||
* to get the raw object, then attach a `fields` array directly.
|
||||
*/
|
||||
@@ -21,7 +20,6 @@ function richEmbed(fields, opts = {}) {
|
||||
if (opts.description) b.setDescription(opts.description);
|
||||
if (opts.footer) b.setFooter({ text: opts.footer });
|
||||
if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL });
|
||||
// EmbedBuilder doesn't have addField — use .toJSON() + raw fields
|
||||
const raw = b.toJSON();
|
||||
raw.fields = fields.map(f => ({
|
||||
name: f.name,
|
||||
@@ -31,7 +29,6 @@ function richEmbed(fields, opts = {}) {
|
||||
return { embeds: [raw] };
|
||||
}
|
||||
|
||||
// ── Constants ─────────────────────────────────────────────────────────────────
|
||||
|
||||
const SHORTCUTS = {
|
||||
prefix: "prefix",
|
||||
@@ -54,7 +51,6 @@ const VOLUME_MIN = 1;
|
||||
const VOLUME_MAX = 200;
|
||||
const MAX_247_CHANNELS = 10;
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Extract clean numeric channel ID from any format */
|
||||
function cleanId(raw) {
|
||||
@@ -103,7 +99,6 @@ function getGuildName(message) {
|
||||
return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server";
|
||||
}
|
||||
|
||||
// ── 24/7 helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get the 24/7 mode for a specific channel.
|
||||
@@ -120,7 +115,6 @@ function get247ChannelMode(set, channelId) {
|
||||
const perChannel = modes[channelId];
|
||||
if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel;
|
||||
}
|
||||
// Fallback: guild-wide mode (legacy)
|
||||
const guildMode = set.get("stay_247_mode") ?? "off";
|
||||
return guildMode;
|
||||
}
|
||||
@@ -137,7 +131,6 @@ function set247ChannelMode(set, channelId, mode) {
|
||||
if (!modes || typeof modes !== "object" || Array.isArray(modes)) modes = {};
|
||||
modes[channelId] = mode;
|
||||
set.set("stay_247_modes", modes);
|
||||
// Also update guild-wide mode for backward compat with older code
|
||||
set.set("stay_247_mode", mode);
|
||||
}
|
||||
|
||||
@@ -154,7 +147,6 @@ function remove247ChannelMode(set, channelId, currentChannels) {
|
||||
if (!modes || typeof modes !== "object" || Array.isArray(modes)) return;
|
||||
delete modes[channelId];
|
||||
set.set("stay_247_modes", modes);
|
||||
// Update guild-wide mode to match the first remaining channel, or "off"
|
||||
if (currentChannels.size === 0) {
|
||||
set.set("stay_247_mode", "off");
|
||||
} else {
|
||||
@@ -177,8 +169,6 @@ function get247Channels(set) {
|
||||
}
|
||||
|
||||
function save247Channels(set, channels) {
|
||||
// Only keep valid Fluxer IDs — strip anything that isn't
|
||||
// a proper channel ID (e.g. garbage from DB corruption).
|
||||
const arr = [...channels].filter(id => id && isValidFluxerId(id));
|
||||
set.set("stay_247", arr.length > 0 ? arr : "none");
|
||||
}
|
||||
@@ -239,7 +229,6 @@ function build247StatusPanel(set, ctx, message, t, guildId) {
|
||||
});
|
||||
}
|
||||
|
||||
// Simple per-channel list: emoji + channel mention + mode
|
||||
const lines = channels.map(chId => {
|
||||
const mode = get247ChannelMode(set, chId);
|
||||
const chName = resolveChannelName(ctx.client, chId);
|
||||
@@ -288,7 +277,6 @@ function build247EnabledPanel(set, channelId, mode, joined, ctx, guildId, t) {
|
||||
const chName = resolveChannelName(ctx.client, channelId);
|
||||
const label = chName ? `**${chName}** <#${channelId}>` : `<#${channelId}>`;
|
||||
|
||||
// Build simple list of all saved channels
|
||||
const lines = channels.map(id => {
|
||||
const m = get247ChannelMode(set, id);
|
||||
const n = resolveChannelName(ctx.client, id);
|
||||
@@ -420,7 +408,6 @@ async function handle247(ctx, message, value) {
|
||||
const guildId = getGuildId(message);
|
||||
const mode = value.toLowerCase().trim();
|
||||
|
||||
// Normalise legacy true/false
|
||||
const resolved = mode === "true" ? "auto" : mode === "false" ? "off" : mode;
|
||||
|
||||
if (!["off", "on", "auto"].includes(resolved)) {
|
||||
@@ -429,7 +416,6 @@ async function handle247(ctx, message, value) {
|
||||
));
|
||||
}
|
||||
|
||||
// ── OFF ───────────────────────────────────────────────────────────────────
|
||||
if (resolved === "off") {
|
||||
if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer")));
|
||||
|
||||
@@ -458,7 +444,6 @@ async function handle247(ctx, message, value) {
|
||||
return message.reply(build247DisabledPanel(set, id, guildId, t247));
|
||||
}
|
||||
|
||||
// Not in a channel — disable all for this guild
|
||||
save247Channels(set, new Set());
|
||||
set.set("stay_247_mode", "off");
|
||||
set.set("stay_247_modes", {});
|
||||
@@ -488,7 +473,6 @@ async function handle247(ctx, message, value) {
|
||||
}));
|
||||
}
|
||||
|
||||
// ── ON / AUTO ─────────────────────────────────────────────────────────────
|
||||
if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer")));
|
||||
|
||||
const userChannelId = ctx.players.checkVoiceChannels(message);
|
||||
@@ -498,9 +482,6 @@ async function handle247(ctx, message, value) {
|
||||
));
|
||||
}
|
||||
|
||||
// Save only the channel the user explicitly toggled.
|
||||
// Multi-voice 24/7 should be opt-in per voice channel, not "whatever
|
||||
// channels the bot currently happens to be in".
|
||||
const id = cleanId(userChannelId);
|
||||
const channels = get247Channels(set);
|
||||
if (!channels.has(id) && channels.size >= MAX_247_CHANNELS) {
|
||||
@@ -540,7 +521,6 @@ async function handle247(ctx, message, value) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Per-setting validation & apply ───────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Validate and save a setting value.
|
||||
@@ -548,7 +528,6 @@ async function handle247(ctx, message, value) {
|
||||
* For stay_247, replies directly and always returns null.
|
||||
*/
|
||||
async function applySet(ctx, message, set, key, rawValue) {
|
||||
// Boolean settings
|
||||
if (BOOL_SETTINGS.has(key)) {
|
||||
const bool = parseBool(rawValue);
|
||||
if (bool === null) {
|
||||
@@ -558,13 +537,11 @@ async function applySet(ctx, message, set, key, rawValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 24/7 mode — replies on its own
|
||||
if (key === "stay_247") {
|
||||
await handle247(ctx, message, rawValue);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Volume
|
||||
if (key === "volume") {
|
||||
const num = parseInt(rawValue, 10);
|
||||
if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) {
|
||||
@@ -574,7 +551,6 @@ async function applySet(ctx, message, set, key, rawValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Locale
|
||||
if (key === "locale") {
|
||||
if (!VALID_LOCALES.has(rawValue)) {
|
||||
return ctx.t(message, "responses.settings.invalidLocale", {
|
||||
@@ -583,14 +559,11 @@ async function applySet(ctx, message, set, key, rawValue) {
|
||||
});
|
||||
}
|
||||
set.set(key, rawValue);
|
||||
// Invalidate locale cache so the new locale takes effect immediately
|
||||
// without requiring a bot reboot.
|
||||
const guildId = getGuildId(message);
|
||||
if (guildId) ctx.locale.invalidateCache(guildId);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Prefix
|
||||
if (key === "prefix") {
|
||||
if (!rawValue || rawValue.length > 5) {
|
||||
return ctx.t(message, "responses.settings.prefixLength");
|
||||
@@ -600,7 +573,6 @@ async function applySet(ctx, message, set, key, rawValue) {
|
||||
}
|
||||
}
|
||||
|
||||
// General: run the runnable hook if present
|
||||
if (runnables[key]) {
|
||||
const err = runnables[key].call(ctx, rawValue, { msg: message });
|
||||
if (err) return `❌ ${err}`;
|
||||
@@ -610,12 +582,10 @@ async function applySet(ctx, message, set, key, rawValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ── Shortcut handler (%prefix, %pfx, %247) ───────────────────────────────────
|
||||
|
||||
async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
||||
const set = ctx.getSettings(message);
|
||||
|
||||
// GET (no value provided) — show rich 24/7 panel
|
||||
if (valueTokens.length === 0) {
|
||||
if (settingKey === "stay_247") {
|
||||
const t247 = ctx.locale?.translate?.bind(ctx.locale);
|
||||
@@ -625,23 +595,18 @@ async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
||||
return message.reply(embed(`\`${settingKey}\` → ${displayValue(settingKey, val)}`));
|
||||
}
|
||||
|
||||
// SET
|
||||
const rawValue = valueTokens.join(" ");
|
||||
const err = await applySet(ctx, message, set, settingKey, rawValue);
|
||||
if (err) return message.reply(embed(err));
|
||||
|
||||
// handle247 replies on its own
|
||||
if (settingKey !== "stay_247") {
|
||||
const val = set.get(settingKey);
|
||||
return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label: settingKey, value: displayValue(settingKey, val) })));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Command definition ────────────────────────────────────────────────────────
|
||||
|
||||
export const command = function() {
|
||||
// Populate valid locales from the Locale instance so the list stays
|
||||
// in sync when new locale files are added to storage/locales/bot/.
|
||||
if (this.locale) {
|
||||
VALID_LOCALES = this.locale.availableLocales();
|
||||
}
|
||||
@@ -737,13 +702,11 @@ export const command = function() {
|
||||
);
|
||||
};
|
||||
|
||||
// ── Command runner ────────────────────────────────────────────────────────────
|
||||
|
||||
export async function run(message, data) {
|
||||
const set = this.getSettings(message);
|
||||
const cmd = data.commandId || "getSettings";
|
||||
|
||||
// ── Shortcut commands (%prefix, %pfx, %247) ───────────────────────────────
|
||||
if (cmd?.startsWith("shortcut_")) {
|
||||
const alias = cmd.replace("shortcut_", "");
|
||||
const settingKey = SHORTCUTS[alias];
|
||||
@@ -754,7 +717,6 @@ export async function run(message, data) {
|
||||
return handleShortcut(this, message, settingKey, tokens);
|
||||
}
|
||||
|
||||
// ── Inline shortcut: %settings <alias> [value] ────────────────────────────
|
||||
const raw = (message.content ?? message.message?.content ?? "").trim();
|
||||
const prefix = set.get("prefix") ?? "%";
|
||||
const body = raw.startsWith(prefix) ? raw.slice(prefix.length).trim() : raw;
|
||||
@@ -766,7 +728,6 @@ export async function run(message, data) {
|
||||
|
||||
const settingKey = data.get("setting")?.value;
|
||||
|
||||
// ── set ───────────────────────────────────────────────────────────────────
|
||||
if (cmd === "setSettings") {
|
||||
const rawValue = data.get("value")?.value;
|
||||
|
||||
@@ -780,13 +741,12 @@ export async function run(message, data) {
|
||||
const err = await applySet(this, message, set, settingKey, rawValue);
|
||||
if (err) return message.reply(embed(err));
|
||||
|
||||
if (settingKey === "stay_247") return; // handle247 replied already
|
||||
if (settingKey === "stay_247") return;
|
||||
|
||||
const newVal = set.get(settingKey);
|
||||
return message.reply(embed(this.t(message, "responses.settings.setSuccess", { label: prettifySettingLabel(settingKey), value: displayValue(settingKey, newVal) })));
|
||||
}
|
||||
|
||||
// ── get ───────────────────────────────────────────────────────────────────
|
||||
if (cmd === "getSettings") {
|
||||
if (settingKey) {
|
||||
if (settingKey === "stay_247") {
|
||||
@@ -800,18 +760,15 @@ export async function run(message, data) {
|
||||
return message.reply(embed(reply));
|
||||
}
|
||||
|
||||
// List all settings
|
||||
const d = set.getAll();
|
||||
const guildName = getGuildName(message);
|
||||
// Use the Fluxer CDN raw property pattern (guild.icon is a hash string, not a URL).
|
||||
// guild.iconURL() is a method that does not exist on @fluxerjs/core Guild objects.
|
||||
const rawGuild = message.message?.guild;
|
||||
const iconUrl = rawGuild?.icon
|
||||
? `https://cdn.fluxer.app/icons/${rawGuild.id}/${rawGuild.icon}.webp`
|
||||
: null;
|
||||
|
||||
const lines = Object.entries(d)
|
||||
.filter(([k]) => k !== "stay_247_mode") // surfaced inline with stay_247
|
||||
.filter(([k]) => k !== "stay_247_mode")
|
||||
.map(([k]) => {
|
||||
if (k === "stay_247") {
|
||||
return `• **24/7 mode** — ${format247Status(set, this.locale?.translate?.bind(this.locale), getGuildId(message))}`;
|
||||
@@ -826,13 +783,11 @@ export async function run(message, data) {
|
||||
));
|
||||
}
|
||||
|
||||
// ── reset ─────────────────────────────────────────────────────────────────
|
||||
if (cmd === "resetSettings") {
|
||||
if (!this.settingsMgr.isOption(settingKey)) {
|
||||
return message.reply(embed(this.t(message, "responses.settings.unknownSetting", { setting: settingKey })));
|
||||
}
|
||||
set.reset(settingKey);
|
||||
// Invalidate locale cache if the locale setting was reset
|
||||
if (settingKey === "locale") {
|
||||
const guildId = getGuildId(message);
|
||||
if (guildId) this.locale.invalidateCache(guildId);
|
||||
@@ -843,7 +798,6 @@ export async function run(message, data) {
|
||||
));
|
||||
}
|
||||
|
||||
// ── help ──────────────────────────────────────────────────────────────────
|
||||
if (cmd === "helpSettings") {
|
||||
const pfx = set.get("prefix") ?? "%";
|
||||
|
||||
|
||||
+2
-13
@@ -9,7 +9,6 @@ export const command = new CommandBuilder()
|
||||
.addAliases("info")
|
||||
.setCategory("util");
|
||||
|
||||
// ── User count cache ──────────────────────────────────────────────────────────
|
||||
|
||||
const CACHE_TTL_MS = 5 * 60 * 1000;
|
||||
|
||||
@@ -97,20 +96,15 @@ function getLivePlayerCount(playerMap) {
|
||||
return live;
|
||||
}
|
||||
|
||||
// ── Guild count helper (paginated REST) ───────────────────────────────────────
|
||||
// client.guilds.size only reflects guilds Fluxer has cached — which is
|
||||
// but caps at 200 per page, so we paginate until we get them all.
|
||||
|
||||
let cachedGuildCount = null;
|
||||
let guildCacheExpiresAt = 0;
|
||||
|
||||
async function getGuildCount(client) {
|
||||
// Return cached value if still fresh
|
||||
if (cachedGuildCount !== null && Date.now() < guildCacheExpiresAt) {
|
||||
return cachedGuildCount;
|
||||
}
|
||||
|
||||
// Paginate through /users/@me/guilds
|
||||
try {
|
||||
let total = 0;
|
||||
let after = null;
|
||||
@@ -119,12 +113,11 @@ async function getGuildCount(client) {
|
||||
const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : "");
|
||||
const chunk = await client.rest.get(url);
|
||||
|
||||
// chunk should be an array; guard against null/non-array responses
|
||||
if (!Array.isArray(chunk) || chunk.length === 0) break;
|
||||
|
||||
total += chunk.length;
|
||||
|
||||
if (chunk.length < 200) break; // last page
|
||||
if (chunk.length < 200) break;
|
||||
|
||||
after = chunk[chunk.length - 1].id;
|
||||
}
|
||||
@@ -133,13 +126,11 @@ async function getGuildCount(client) {
|
||||
guildCacheExpiresAt = Date.now() + CACHE_TTL_MS;
|
||||
return total;
|
||||
} catch {
|
||||
// REST failed — fall back to local cache
|
||||
if (typeof client.guilds?.size === "number") return client.guilds.size;
|
||||
return Object.keys(client.guilds ?? {}).length;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Embed builder ─────────────────────────────────────────────────────────────
|
||||
|
||||
function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) {
|
||||
const num = (v) => Utils.formatNumber(v);
|
||||
@@ -178,14 +169,13 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
|
||||
return builder;
|
||||
}
|
||||
|
||||
// ── Runner ────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function run(message) {
|
||||
const lastfm = this.lastfm;
|
||||
const lastfmEnabled = lastfm?.enabled ?? false;
|
||||
|
||||
const shared = {
|
||||
guildCount: cachedGuildCount ?? this.client.guilds.size, // use cache or local fallback for instant reply
|
||||
guildCount: cachedGuildCount ?? this.client.guilds.size,
|
||||
playerCount: getLivePlayerCount(this.players.playerMap),
|
||||
scrobbleCount: 0,
|
||||
linkedUsers: 0,
|
||||
@@ -208,7 +198,6 @@ export async function run(message) {
|
||||
});
|
||||
const ping = Date.now() - start;
|
||||
|
||||
// Fetch everything in parallel including the real paginated guild count
|
||||
const [users, scrobbleCount, linkedUsers, guildCount] = await Promise.all([
|
||||
getUserCount(this.client),
|
||||
scrobblePromise,
|
||||
|
||||
@@ -16,10 +16,8 @@ export async function run(msg, data) {
|
||||
|
||||
const channelCounts = new Map();
|
||||
|
||||
// Use VoiceStateCache API for both humans and bots
|
||||
const cache = this.voiceCache ?? this.observedVoiceUsers;
|
||||
if (cache) {
|
||||
// Humans
|
||||
if (typeof cache.iterateHumanUsers === "function") {
|
||||
for (const [, state] of cache.iterateHumanUsers()) {
|
||||
if (state.guildId !== guild.id) continue;
|
||||
@@ -31,7 +29,6 @@ export async function run(msg, data) {
|
||||
channelCounts.set(state.channelId, (channelCounts.get(state.channelId) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
// Bots
|
||||
if (typeof cache.iterateBotUsers === "function") {
|
||||
for (const [, state] of cache.iterateBotUsers()) {
|
||||
if (state.guildId !== guild.id) continue;
|
||||
@@ -67,7 +64,6 @@ export async function run(msg, data) {
|
||||
for (const [channelId, total] of channelCounts) {
|
||||
const name = await getChannelName(channelId);
|
||||
const entry = this.t(msg, "responses.test.channelEntry", { name, count: total });
|
||||
// Guard against 4096-char embed description limit
|
||||
if (desc.length + entry.length > 4080) break;
|
||||
desc += entry;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
|
||||
import { Utils } from "../src/Utils.mjs";
|
||||
import { FLUXERLIST, buildVoteLink } from "../src/constants/API.mjs";
|
||||
|
||||
// Auto-remove timer for reaction navigation: 60 seconds
|
||||
const EMOJI_REMOVE_TIMEOUT = 60_000;
|
||||
|
||||
export const command = new CommandBuilder()
|
||||
@@ -35,7 +34,6 @@ export const command = new CommandBuilder()
|
||||
.setRequired(false)
|
||||
);
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
function notConfigured(prefix) {
|
||||
return {
|
||||
@@ -97,7 +95,6 @@ function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired
|
||||
return { embeds: [embed] };
|
||||
}
|
||||
|
||||
// ── Run ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function run(msg, data) {
|
||||
const fluxerlist = this.fluxerlist;
|
||||
@@ -108,7 +105,6 @@ export async function run(msg, data) {
|
||||
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);
|
||||
@@ -132,7 +128,6 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// Use slug for website links (slugs work on the website; numeric IDs don't)
|
||||
const slug = resourceId || (resolvedType === "server" ? fluxerlist?.serverSlug : fluxerlist?.botSlug);
|
||||
const voteUrl = slug ? buildVoteLink(resolvedType, slug) : null;
|
||||
const label = resolvedType === "server" ? "Server" : "Bot";
|
||||
@@ -158,7 +153,6 @@ export async function run(msg, data) {
|
||||
return msg.reply({ embeds: [embed] });
|
||||
}
|
||||
|
||||
// ── Check / Voters — Show voter list ───────────────────────────────────────
|
||||
case "check":
|
||||
case "voters": {
|
||||
if (!fluxerlist || !fluxerlist.enabled) return msg.reply(notConfigured(prefix));
|
||||
@@ -168,7 +162,6 @@ export async function run(msg, data) {
|
||||
|
||||
if (!id) return msg.reply(noResourceId(resolvedType, prefix));
|
||||
|
||||
// Fetch the first page
|
||||
let voterData;
|
||||
try {
|
||||
voterData = await fluxerlist.getVoters(resolvedType, id, { page, limit: 20 });
|
||||
@@ -180,7 +173,6 @@ export async function run(msg, data) {
|
||||
});
|
||||
}
|
||||
|
||||
// No voters at all
|
||||
if (voterData.total === 0) {
|
||||
return msg.reply({
|
||||
embeds: [new EmbedBuilder()
|
||||
@@ -191,13 +183,11 @@ export async function run(msg, data) {
|
||||
|
||||
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) => {
|
||||
@@ -248,7 +238,6 @@ export async function run(msg, data) {
|
||||
currentPage = currentPage < totalPages ? currentPage + 1 : 1;
|
||||
}
|
||||
|
||||
// Fetch the new page data
|
||||
try {
|
||||
voterData = await fluxerlist.getVoters(resolvedType, id, { page: currentPage, limit: 20 });
|
||||
} catch {
|
||||
|
||||
Reference in new issue
Block a user