mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
- Add Locale class (src/constants/Locale.mjs) with per-guild translation
support and settings-manager binding
- Wire locale into CommandHandler, MessageHandler, Player, PlayerManager,
and index.mjs via setLocale() / t() helpers
- Replace all hardcoded English strings (help pages, errors, now-playing,
permission messages, session-closed footers) with locale key lookups
- Fix: %help triggering "Unknown command" — replyHandler intercept now
uses case-insensitive check for "unknown command"
- Fix: TypeError crash in closeSession when embed has no footer — guard
with `if (!footer) footer = { text: "" }` before appending
- Fix: media player teardown now calls destroy() and nulls the instance
instead of relying on _stopMediaPlayer(), preventing stale state
- Refactor: reply() and send() auto-wrap plain strings in embeds,
matching old replyEmbed/sendEmbed behaviour
- Refactor: permission errors and invalid-flag errors use t() lookups
- Add top-level t(message, key, data) helper on the bot instance for
command files to resolve guild locale without manual guildId plumbing
234 lines
7.2 KiB
JavaScript
234 lines
7.2 KiB
JavaScript
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
|
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 = [
|
|
"token",
|
|
"config",
|
|
"key",
|
|
"clientsecret",
|
|
"clientid",
|
|
"password",
|
|
"secret",
|
|
"authorization",
|
|
"mysql",
|
|
"nodelink",
|
|
"_nl",
|
|
"credential",
|
|
"apikey",
|
|
"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;
|
|
visited.add(obj);
|
|
for (const key in obj) {
|
|
if (RESTRICTED.some(r => key.toLowerCase().includes(r))) return true;
|
|
if (typeof obj[key] === "object" && hasSensitive(obj[key], level + 1, visited)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function removeSensitive(obj, level = 0, visited = new WeakSet()) {
|
|
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return obj;
|
|
if (visited.has(obj)) return "[Circular]";
|
|
visited.add(obj);
|
|
|
|
const isArray = Array.isArray(obj);
|
|
const newObj = isArray ? [...obj] : { ...obj };
|
|
let modified = false;
|
|
|
|
for (const key in newObj) {
|
|
const isSensitive = !isArray && RESTRICTED.some(r => key.toLowerCase().includes(r));
|
|
|
|
if (isSensitive) {
|
|
newObj[key] = "[REDACTED]";
|
|
modified = true;
|
|
} else if (typeof newObj[key] === "object" && newObj[key] !== null) {
|
|
const cleaned = removeSensitive(newObj[key], level + 1, visited);
|
|
if (cleaned !== newObj[key]) {
|
|
newObj[key] = cleaned;
|
|
modified = true;
|
|
}
|
|
}
|
|
}
|
|
return modified ? newObj : obj;
|
|
}
|
|
|
|
async function clean(value) {
|
|
if (value instanceof Promise) value = await value;
|
|
|
|
if (typeof value === "object" && value !== null) {
|
|
if (hasSensitive(value)) {
|
|
value = removeSensitive(value);
|
|
}
|
|
}
|
|
|
|
let output;
|
|
try {
|
|
output = typeof value === "string" ? value : inspect(value, { depth: 1, compact: false });
|
|
} catch (err) {
|
|
output = `[Inspection Error]: ${err.message}`;
|
|
}
|
|
|
|
return output
|
|
.replace(/`/g, "`\u200b")
|
|
.replace(/@/g, "@\u200b") || "undefined"; // Fallback if output is empty
|
|
}
|
|
|
|
/**
|
|
* Executes the code and returns the raw data instead of a formatted string,
|
|
* so we can paginate it inside Embeds later.
|
|
*/
|
|
async function runEval(expression, context) {
|
|
const start = Date.now();
|
|
let result, isError = false, type = "undefined";
|
|
|
|
try {
|
|
result = await eval(`(async function() { ${expression} })`).call(context);
|
|
type = result === null ? "null" : typeof result;
|
|
} catch (e) {
|
|
result = e;
|
|
isError = true;
|
|
type = "error";
|
|
}
|
|
|
|
const elapsed = Date.now() - start;
|
|
const output = await clean(result);
|
|
|
|
return { output, isError, type, elapsed };
|
|
}
|
|
|
|
export const command = new CommandBuilder()
|
|
.setName("eval")
|
|
.setDescription("Evaluates JavaScript code (Owner Only).")
|
|
.setRequirement(r => r.setOwnerOnly(true))
|
|
.setCategory("util")
|
|
.addTextOption(o =>
|
|
o.setName("expression")
|
|
.setDescription("The JavaScript expression to evaluate")
|
|
.setRequired(true)
|
|
);
|
|
|
|
export async function run(msg, data) {
|
|
const expression = data.get("expression").value;
|
|
const context = Object.assign({ message: msg }, 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) {
|
|
chunks.push(output.slice(i, i + chunkSize));
|
|
}
|
|
|
|
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\`\`\``;
|
|
|
|
// 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
|
|
.setTitle(title)
|
|
.setDescription(desc)
|
|
.setFooter({ text: footerText })
|
|
;
|
|
|
|
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;
|
|
|
|
for (const emoji of navEmojis) {
|
|
await replyMsg.message.react(emoji).catch(() => {});
|
|
}
|
|
|
|
// Helper: Clear reactions when time runs out
|
|
const clearReactions = async () => {
|
|
try {
|
|
await replyMsg.message.removeAllReactions();
|
|
} catch (e) {
|
|
for (const emoji of navEmojis) {
|
|
try {
|
|
await replyMsg.message.removeReaction(emoji);
|
|
} catch (_) {}
|
|
}
|
|
}
|
|
};
|
|
|
|
// Helper: Reset inactivity timer
|
|
const resetTimer = () => {
|
|
clearTimeout(emojiTimeout);
|
|
emojiTimeout = setTimeout(async () => {
|
|
if (unobserve) unobserve();
|
|
await clearReactions();
|
|
await replyMsg.edit(buildPageContent(currentPage, true)).catch(() => {});
|
|
}, 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
|
|
}
|
|
|
|
resetTimer();
|
|
|
|
if (e.emoji_id === "⬅️") {
|
|
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
|
} else if (e.emoji_id === "➡️") {
|
|
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
|
}
|
|
|
|
// Update Embed
|
|
await replyMsg.edit(buildPageContent(currentPage)).catch(() => {});
|
|
});
|
|
|
|
resetTimer();
|
|
} |