mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
Remix — the complete rewrite
Upgrades the bot from fluxerjs 2.2 to 3.0 and restructures everything into a layered architecture (~28K lines): Dependencies: - @fluxerjs/core, util, voice: ^2.2.0 -> ^3.0.0 (typed events, PartialMessage payloads, camelCase API) - @fluxerjs/sharding ^3.0.0 added — built-in sharding mode (shard.mjs, one process per shard) - @discordjs/opus dropped — opusscript + prism-media cover encoding Architecture: - commands: every command split into submodules (player, lastfm, settings, debug) with a shared CommandBuilder/Loader/Handler core - ui: embeds, paginators, help command, permission checks - voice: gateway event routing, rejoin/247 boot recovery, state resolver - music: player split into Queue/Search/Playback/Display mixins, stream pipeline + WebM/Opus muxer (no FFmpeg needed) - dashboard: Redis pub/sub, RPC handlers, serializers - db: MySQL manager + per-guild settings - services: LastFm manager split into focused mixins - utils: sharding, 24/7 helpers, API client Runtime fixes over v2: - Redis v5 reconnect: capped numeric backoff (0.5s ramp to 15s), never exhausts, auto-recovers when the server comes back - Redis main/subscriber clients connect in parallel; clean shutdown - Logger storm guard: identical error/warn lines deduped in a 60s window - self-deaf fix on voice join - config example uses redis://127.0.0.1 (avoids IPv6 ENETUNREACH) Housekeeping: dead code removed (Tuna.mjs + follow-redirects dep), .gitignore added (config.json, .env, node_modules, runtime state).
This commit is contained in:
1 parent
0f085a6ae4
commit
253d11cd57
150 files changed
+19935
-16894
No files matched your search
@@ -0,0 +1,588 @@
|
||||
/**
|
||||
* @module src/core/Bot
|
||||
* @description The Remix bot class: config loading, client construction,
|
||||
* service wiring (settings, commands, players, gateway, dashboard, Last.fm,
|
||||
* FluxerList, track options), presence rotation, alone-check loop, and
|
||||
* WebSocket error guards. Channel/voice operations live in BotVoiceMixin.
|
||||
*/
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import childProcess from "node:child_process";
|
||||
import { Client, Events } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { initLogger, logger, _wsErrorCooldown } from "./Logger.mjs";
|
||||
import { Locale } from "./Locale.mjs";
|
||||
import { CommandHandler, CommandLoader, PrefixManager } from "../commands/index.mjs";
|
||||
import { MessageHandler, HelpCommand, setGlobalColor } from "../ui/index.mjs";
|
||||
import { cleanId } from "../utils/Utils.mjs";
|
||||
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
|
||||
import { RemoteSettingsManager } from "../db/Settings.mjs";
|
||||
import { PlayerManager } from "../music/PlayerManager.mjs";
|
||||
import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||
import { VoiceStateCache } from "../voice/VoiceStateCache.mjs";
|
||||
import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
|
||||
import { LastFmManager } from "../services/lastfm/LastFmManager.mjs";
|
||||
import { FluxerListManager } from "../services/FluxerListManager.mjs";
|
||||
import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs";
|
||||
import { applyMixins } from "../utils/mixins.mjs";
|
||||
import BotVoiceMixin from "./BotVoiceMixin.mjs";
|
||||
|
||||
/**
|
||||
* Create a Map-like view object that proxies bot voice-state lookups through
|
||||
* the VoiceStateCache's bot-specific methods.
|
||||
* @param {VoiceStateCache} voiceCache
|
||||
* @returns {Map}
|
||||
*/
|
||||
function createBotView(voiceCache) {
|
||||
return {
|
||||
get size() { return voiceCache.botLocations.size; },
|
||||
get(key) { return voiceCache.botLocations.get(key); },
|
||||
set(key, val) { return voiceCache.setBotUser(key, val); },
|
||||
has(key) { return voiceCache.botLocations.has(key); },
|
||||
delete(key) { return voiceCache.deleteBotUser(key); },
|
||||
forEach(fn) { for (const [k, v] of voiceCache.iterateBotUsers()) fn(v, k, this); },
|
||||
*[Symbol.iterator]() { yield* voiceCache.iterateBotUsers(); },
|
||||
*entries() { yield* voiceCache.iterateBotUsers(); },
|
||||
*keys() { for (const [k] of voiceCache.iterateBotUsers()) yield k; },
|
||||
*values() { for (const [, v] of voiceCache.iterateBotUsers()) yield v; },
|
||||
get observedVoiceBotsSize() { return voiceCache.botLocations.size; },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a runtime presence update payload from a config entry (string or
|
||||
* object with text/emoji/activity).
|
||||
* @param {string|object} entry
|
||||
* @returns {object}
|
||||
*/
|
||||
function buildRuntimePresence(entry) {
|
||||
const isObj = typeof entry === "object" && entry !== null;
|
||||
const customStatus = {};
|
||||
if (isObj) {
|
||||
if (entry.text) customStatus.text = entry.text;
|
||||
if (entry.emoji_name) customStatus.emojiName = entry.emoji_name;
|
||||
if (entry.emoji_id) customStatus.emojiId = entry.emoji_id;
|
||||
} else {
|
||||
customStatus.text = String(entry);
|
||||
}
|
||||
|
||||
const update = { status: "online", afk: false, customStatus };
|
||||
|
||||
if (isObj && entry.activity) {
|
||||
update.activities = [{
|
||||
name: entry.activity.name ?? "music",
|
||||
type: entry.activity.type ?? 0,
|
||||
url: entry.activity.url ?? undefined,
|
||||
}];
|
||||
}
|
||||
|
||||
return update;
|
||||
}
|
||||
|
||||
/**
|
||||
* @class Remix
|
||||
* @description Main bot class. Orchestrates client, settings, players,
|
||||
* lavalink, gateway events, commands, and 24/7 voice channel management.
|
||||
*/
|
||||
class Remix {
|
||||
/**
|
||||
* Bootstrap the entire bot: load config, create the Fluxer client,
|
||||
* initialise settings/commands/players/dashboard, set up event handlers,
|
||||
* load modules, and log in.
|
||||
*/
|
||||
constructor() {
|
||||
let config;
|
||||
try {
|
||||
config = JSON.parse(fs.readFileSync("config.json", "utf8"));
|
||||
} catch (e) {
|
||||
const reason = e.code === "ENOENT"
|
||||
? "config.json not found. Copy config_example.json → config.json and fill in your values."
|
||||
: `config.json is malformed JSON: ${e.message}`;
|
||||
console.error(`[Startup] FATAL: ${reason}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const REQUIRED_KEYS = ["token", "mysql"];
|
||||
for (const key of REQUIRED_KEYS) {
|
||||
if (config[key] == null) {
|
||||
console.error(`[Startup] FATAL: config.json is missing required key "${key}".`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
this.config = config;
|
||||
|
||||
setGlobalColor(config.embedColor);
|
||||
|
||||
this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
|
||||
this.locale.load();
|
||||
|
||||
this.dashboard = new Dashboard(this, {
|
||||
enabled: config.dashboard?.enabled,
|
||||
redis: config.dashboard?.redis,
|
||||
mysql: config.mysql,
|
||||
});
|
||||
|
||||
const presenceContents = config.presenceContents ?? [];
|
||||
const presenceInterval = config.presenceInterval ?? 30_000;
|
||||
|
||||
let presenceRotationIndex = presenceContents.length > 1 ? 1 : 0;
|
||||
let presenceRotationStarted = false;
|
||||
let wsHandlerRearmStarted = false;
|
||||
|
||||
const timers = config.timers ?? {};
|
||||
this.T = {
|
||||
aloneCheckInterval: timers.aloneCheckInterval ?? 60_000,
|
||||
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
|
||||
rejoin247Delay: timers.rejoin247Delay ?? 3_000,
|
||||
leave247RejoinDelay: timers.leave247RejoinDelay ?? 5_000,
|
||||
intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000,
|
||||
};
|
||||
|
||||
// Fluxer 3.0: ClientOptions.presence is the normalized PresenceUpdateOptions
|
||||
// shape (customStatus/emojiName/emojiId) — the 2.2 wire format
|
||||
// (custom_status) is no longer read here. buildRuntimePresence() outputs
|
||||
// exactly the normalized shape, so the initial presence reuses it.
|
||||
const client = new Client({
|
||||
waitForGuilds: true,
|
||||
cache: { guilds: false, channels: false, users: false, members: false },
|
||||
...config["fluxer.js"],
|
||||
presence: presenceContents.length === 0 ? undefined : buildRuntimePresence(presenceContents[0]),
|
||||
});
|
||||
|
||||
client.setMaxListeners(50);
|
||||
this.client = client;
|
||||
|
||||
try {
|
||||
getVoiceManager(client);
|
||||
logger.player("[Startup] VoiceManager initialized before login.");
|
||||
} catch (e) {
|
||||
logger.warn("[Startup] VoiceManager pre-login init failed:", e.message);
|
||||
}
|
||||
|
||||
const messages = new MessageHandler(this.client);
|
||||
this.messages = messages;
|
||||
|
||||
const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
|
||||
this.settingsMgr = settings;
|
||||
|
||||
const configPrefix = config.prefix ?? null;
|
||||
if (configPrefix && settings.defaults) {
|
||||
settings.defaults.prefix = configPrefix;
|
||||
}
|
||||
|
||||
this.locale.bind(this.settingsMgr);
|
||||
|
||||
const commands = new CommandHandler(messages, configPrefix);
|
||||
this.handler = commands;
|
||||
|
||||
const prefixMgr = new PrefixManager(settings, configPrefix);
|
||||
commands.setPrefixManager(prefixMgr);
|
||||
commands.setLocale(this.locale);
|
||||
messages.setLocale(this.locale);
|
||||
this.locale.setPrefixResolver((guildId) => commands.getPrefix(guildId));
|
||||
|
||||
new HelpCommand(commands, messages, (msg) => this.getSettings(msg)).register();
|
||||
|
||||
commands.onPing = (msg) => {
|
||||
msg.replyEmbed(
|
||||
this.handler.format(
|
||||
"My prefix in this server is `$prefix`\n\nRun `$prefix$helpCmd` to get started!",
|
||||
msg.message.guildId
|
||||
),
|
||||
false,
|
||||
{
|
||||
icon_url: msg.channel.channel.guild?.icon
|
||||
? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp`
|
||||
: null,
|
||||
title: msg.channel.channel.guild?.name ?? null,
|
||||
}
|
||||
);
|
||||
};
|
||||
commands.owners = config.owners ?? [];
|
||||
|
||||
this.lavalink = null;
|
||||
let lavalinkInitialised = false;
|
||||
|
||||
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
|
||||
|
||||
this.observedVoiceUsers = this.voiceCache;
|
||||
this.observedVoiceBots = createBotView(this.voiceCache);
|
||||
|
||||
this._announcementChannelCache = new Map();
|
||||
this._announcementChannelTTL = 5 * 60 * 1000;
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [k, v] of this._announcementChannelCache) {
|
||||
if (v.timestamp && now - v.timestamp > this._announcementChannelTTL) this._announcementChannelCache.delete(k);
|
||||
}
|
||||
}, 60_000);
|
||||
this.intentionalLeaves = new Map();
|
||||
|
||||
this.gatewayHandler = new GatewayHandler(this);
|
||||
this.gatewayHandler.setupEventHandlers();
|
||||
|
||||
this.lastfm = new LastFmManager(config.lastfm, config.mysql);
|
||||
this.fluxerlist = new FluxerListManager(config.fluxerlist);
|
||||
this.trackOptions = new TrackOptionsManager(config.mysql);
|
||||
|
||||
settings.on("ready", () => this._onSettingsReady());
|
||||
|
||||
client.on(Events.Ready, async () => {
|
||||
try {
|
||||
logger.player("Logged in as " + (client.user?.username ?? "bot"));
|
||||
|
||||
this._attachWsErrorHandlers();
|
||||
|
||||
if (!wsHandlerRearmStarted) {
|
||||
wsHandlerRearmStarted = true;
|
||||
setInterval(() => {
|
||||
this._attachWsErrorHandlers();
|
||||
this.gatewayHandler.attachRawListener();
|
||||
}, 5_000).unref?.();
|
||||
}
|
||||
|
||||
const botId = client.user?.id ?? "0";
|
||||
|
||||
await this.settingsMgr.setBotId(botId);
|
||||
await this.lastfm.setBotId(botId);
|
||||
this.dashboard.setBotId(botId);
|
||||
this.trackOptions.setBotId(botId);
|
||||
|
||||
if (!lavalinkInitialised) {
|
||||
lavalinkInitialised = true;
|
||||
this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" });
|
||||
this.lavalink.on("ready", () => {
|
||||
logger.lavalink("[Lavalink] Session ready");
|
||||
});
|
||||
await this.lavalink.init();
|
||||
this.playerContext.lavalink = this.lavalink;
|
||||
}
|
||||
|
||||
this.gatewayHandler.onReady();
|
||||
|
||||
if (!presenceRotationStarted && presenceContents.length > 1) {
|
||||
presenceRotationStarted = true;
|
||||
setInterval(() => {
|
||||
try {
|
||||
const entry = presenceContents[presenceRotationIndex % presenceContents.length];
|
||||
client.user?.setPresence(buildRuntimePresence(entry));
|
||||
presenceRotationIndex = (presenceRotationIndex + 1) % presenceContents.length;
|
||||
} catch (e) {
|
||||
logger.warn("[Presence] Rotation update failed:", e?.message);
|
||||
}
|
||||
}, presenceInterval).unref?.();
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error("[Ready] Fatal error in Ready handler:", e);
|
||||
}
|
||||
});
|
||||
|
||||
client._remix = this;
|
||||
|
||||
this.playerContext = {
|
||||
client: this.client,
|
||||
config,
|
||||
lavalink: null,
|
||||
};
|
||||
this.players = new PlayerManager(settings, commands, {
|
||||
config,
|
||||
player: this.playerContext,
|
||||
dashboard: this.dashboard,
|
||||
locale: this.locale,
|
||||
timers: this.T,
|
||||
trackOptions: this.trackOptions,
|
||||
});
|
||||
this.players.observedVoiceUsers = this.observedVoiceUsers;
|
||||
this.players.voiceCache = this.voiceCache;
|
||||
this.players._lastfm = this.lastfm;
|
||||
|
||||
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
|
||||
setInterval(() => this._runAloneCheck(), ALONE_CHECK_INTERVAL);
|
||||
|
||||
this.players.checkVoiceChannels = (message) => this._checkVoiceChannelsImpl(message);
|
||||
|
||||
const __dirname = import.meta.dirname;
|
||||
try {
|
||||
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||
this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||
} catch (e) {
|
||||
logger.warn("[Git] comhash error:", e?.message);
|
||||
this.comHash = "Newest";
|
||||
this.comHashLong = null;
|
||||
}
|
||||
|
||||
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
||||
|
||||
const loader = new CommandLoader(commands, this);
|
||||
const dir = path.join(__dirname, "..", "..", "commands");
|
||||
logger.commands("Started loading commands.");
|
||||
loader.loadFromDir(dir)
|
||||
.then(() => logger.commands("Commands loaded."))
|
||||
.catch(e => logger.error("Failed to load commands:", e));
|
||||
|
||||
logger.commands("Loading Modules.");
|
||||
this.loadedModules = new Map();
|
||||
try {
|
||||
this.modules = JSON.parse(fs.readFileSync("./storage/modules.json"));
|
||||
} catch (e) {
|
||||
const reason = e.code === "ENOENT"
|
||||
? "storage/modules.json not found."
|
||||
: `storage/modules.json is malformed JSON: ${e.message}`;
|
||||
console.error(`[Startup] WARN: ${reason} — starting with no modules.`);
|
||||
this.modules = [];
|
||||
}
|
||||
Promise.allSettled(this.modules.map(async m => {
|
||||
if (!m.enabled) return;
|
||||
try {
|
||||
const exported = await import(m.index);
|
||||
const ModClass = exported.default;
|
||||
this.loadedModules.set(m.name, { instance: new ModClass(this), c: ModClass });
|
||||
} catch (e) {
|
||||
logger.error(`[Module] Failed to load "${m.name}":`, e.message);
|
||||
}
|
||||
}))
|
||||
.then(results => {
|
||||
const succeeded = results.filter(r => r.status === "fulfilled").length;
|
||||
const failed = results.length - succeeded;
|
||||
logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`);
|
||||
});
|
||||
|
||||
// Fluxer.js 3.0 sharding (opt-in, root `shard.mjs`): a child forked by a
|
||||
// ShardingManager attaches the child-side ShardClientUtil BEFORE login —
|
||||
// it applies FLUXER_SHARD_IDS/FLUXER_SHARD_COUNT to the client options
|
||||
// and routes IDENTIFYs through the parent's shared per-IP budget — then
|
||||
// reports readiness so the supervisor's spawn() promise resolves.
|
||||
const startLogin = async () => {
|
||||
if (ShardingUtils.isShardedProcess()) {
|
||||
try {
|
||||
const { attachShardClientUtil } = await import("@fluxerjs/sharding");
|
||||
this.shardUtil = attachShardClientUtil(client);
|
||||
logger.player(
|
||||
`[Startup] Sharding child attached — ${ShardingUtils.describeSharding(client)}.`
|
||||
);
|
||||
} catch (e) {
|
||||
// Fatal: without the shard slice this child would identify as shard 0
|
||||
// like every other child and thrash the gateway sessions.
|
||||
logger.error(
|
||||
"[Startup] FATAL: running under a ShardingManager but the sharding attach failed:",
|
||||
e?.message
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
await client.login(config.token);
|
||||
if (this.shardUtil) {
|
||||
try { this.shardUtil.notifyReady(); }
|
||||
catch (e) { logger.warn("[Startup] Sharding ready report failed:", e?.message); }
|
||||
}
|
||||
};
|
||||
startLogin().catch(e => {
|
||||
logger.error("[Startup] Login failed:", e?.message ?? e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings-ready handler: initialise the logger and normalise stay_247
|
||||
* values (single channel per guild, cleaned IDs).
|
||||
* @private
|
||||
*/
|
||||
_onSettingsReady() {
|
||||
initLogger(this.config);
|
||||
logger.settings("[settings] Loaded from DB.");
|
||||
for (const [guildId, serverSettings] of this.settingsMgr.guilds) {
|
||||
const val = serverSettings.get("stay_247");
|
||||
if (!val || val === "none") continue;
|
||||
const rawArr = Array.isArray(val) ? val : [val];
|
||||
const cleaned = rawArr
|
||||
.map(id => cleanId(id))
|
||||
.filter(id => id.length >= 15 && id.length <= 22);
|
||||
|
||||
if (cleaned.length > 1) {
|
||||
// Only 1 channel per guild supported. Keep first, drop the rest.
|
||||
serverSettings.set("stay_247", cleaned.slice(0, 1));
|
||||
logger.settings(
|
||||
`[settings] Trimmed stay_247 for guild ${guildId}: had ${cleaned.length} channels, kept first 1.`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val);
|
||||
if (needsSave || !Array.isArray(val)) {
|
||||
const newVal = cleaned.length > 0 ? cleaned : "none";
|
||||
serverSettings.set("stay_247", newVal);
|
||||
logger.settings(
|
||||
`[settings] Cleaned stay_247 for guild ${guildId}: ${JSON.stringify(val)} → ${JSON.stringify(newVal)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Periodic alone-check: for every active player, when no humans remain in
|
||||
* the channel, either arm the inactivity timer (music still queued) or
|
||||
* emit autoleave.
|
||||
* @private
|
||||
*/
|
||||
_runAloneCheck() {
|
||||
if (this.players.playerMap.size === 0) return;
|
||||
|
||||
for (const [mapKey, player] of this.players.playerMap) {
|
||||
let channelId;
|
||||
try {
|
||||
if (player._destroyed || player._isJoining) continue;
|
||||
|
||||
const guildId = player._guildId;
|
||||
if (!guildId) continue;
|
||||
|
||||
channelId = player._channelId ?? mapKey;
|
||||
const cleanChanId = cleanId(channelId);
|
||||
if (!cleanChanId) continue;
|
||||
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
|
||||
if (player._is247Enabled()) continue;
|
||||
|
||||
if (!player.connection) continue;
|
||||
|
||||
let hasHuman = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanChanId);
|
||||
|
||||
if (!hasHuman) {
|
||||
try {
|
||||
const guild = this.client?.guilds?.get?.(cleanGuildId);
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.values(voiceStates);
|
||||
for (const state of entries) {
|
||||
const stateChannel = cleanId(state?.channelId ?? state?.channel_id);
|
||||
if (stateChannel === cleanChanId) {
|
||||
const stateUserId = state?.userId ?? state?.user_id ?? state?.id;
|
||||
const member = guild?.members?.get?.(stateUserId);
|
||||
const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false;
|
||||
if (!isBot) {
|
||||
hasHuman = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[AloneCheck] Voice state check error:", e?.message); }
|
||||
}
|
||||
|
||||
if (!hasHuman) {
|
||||
try {
|
||||
const room = player.connection?.room;
|
||||
if (room?.isConnected && room.remoteParticipants && room.remoteParticipants.size > 0) {
|
||||
hasHuman = true;
|
||||
}
|
||||
} catch(e) { logger.warn("[AloneCheck] LiveKit check error:", e?.message); }
|
||||
}
|
||||
|
||||
if (!hasHuman && !player._paused) {
|
||||
if (player.queue?.getCurrent() || !player.queue?.isEmpty()) {
|
||||
player._startInactivityTimer?.();
|
||||
} else {
|
||||
player._stopInactivityTimer?.();
|
||||
player.emit("autoleave");
|
||||
}
|
||||
} else if (hasHuman) {
|
||||
player._stopInactivityTimer?.();
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[AloneCheck] Error checking channel", channelId, e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach proactive error handlers to WebSocket sockets/shards to prevent
|
||||
* unhandled crashes from WebSocket transport errors. Re-armed periodically.
|
||||
* @private
|
||||
*/
|
||||
_attachWsErrorHandlers() {
|
||||
try {
|
||||
const wsManager = this.client?.ws;
|
||||
if (!wsManager) return;
|
||||
|
||||
let attachedNew = false;
|
||||
|
||||
const logWsError = (label, err) => {
|
||||
const now = Date.now();
|
||||
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
|
||||
_wsErrorCooldown.lastLogged = now;
|
||||
logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`);
|
||||
};
|
||||
|
||||
const attachToSocket = (wsObj, label) => {
|
||||
if (!wsObj) return;
|
||||
if (wsObj._fluxerErrorHandled) return;
|
||||
wsObj._fluxerErrorHandled = true;
|
||||
attachedNew = true;
|
||||
|
||||
if (typeof wsObj.on === "function") {
|
||||
wsObj.on("error", (err) => logWsError(label, err));
|
||||
}
|
||||
if (typeof wsObj.addEventListener === "function") {
|
||||
wsObj.addEventListener("error", (event) => {
|
||||
if (typeof event.preventDefault === "function") event.preventDefault();
|
||||
const err = event?.error ?? event?.message ?? event;
|
||||
logWsError(label, err);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const attachToShard = (shard, id) => {
|
||||
if (!shard) return;
|
||||
if (shard._fluxerErrorHandled) return;
|
||||
shard._fluxerErrorHandled = true;
|
||||
attachedNew = true;
|
||||
shard.on("error", (err) => logWsError(`Shard ${id}`, err));
|
||||
if (shard.ws) attachToSocket(shard.ws, `Shard ${id} socket`);
|
||||
};
|
||||
|
||||
// Fluxer 3.0: the ws manager exposes shards via getShards() (2.2 used a
|
||||
// `shards` Map property) and a sharded child owns several of them —
|
||||
// attach to every shard connected in this process, not just shard 0.
|
||||
for (const [id, shard] of ShardingUtils.getLocalShards(this.client)) {
|
||||
attachToShard(shard, id);
|
||||
}
|
||||
|
||||
if (wsManager.ws) {
|
||||
attachToSocket(wsManager.ws, "Gateway");
|
||||
}
|
||||
|
||||
if (typeof wsManager.on === "function" && !wsManager._fluxerErrorHandled) {
|
||||
wsManager._fluxerErrorHandled = true;
|
||||
attachedNew = true;
|
||||
wsManager.on("error", ({ shardId, error }) => {
|
||||
logWsError(`WSManager (shard ${shardId})`, error);
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof wsManager.on === "function" && !wsManager._shardCreateHandled) {
|
||||
wsManager._shardCreateHandled = true;
|
||||
attachedNew = true;
|
||||
wsManager.on("shardCreate", (shard) => {
|
||||
attachToShard(shard, shard.id ?? "?");
|
||||
});
|
||||
}
|
||||
|
||||
if (attachedNew) {
|
||||
logger.player("[WS] Proactive error handlers attached to gateway sockets.");
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[WS] Failed to attach WS error handlers:", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attach channel/voice operations (spawn, leave, shared servers, helpers).
|
||||
applyMixins(Remix, BotVoiceMixin);
|
||||
|
||||
export { Remix };
|
||||
export default Remix;
|
||||
@@ -0,0 +1,511 @@
|
||||
/**
|
||||
* @module src/core/BotVoiceMixin
|
||||
* @description Channel & voice operations for the {@link Remix} bot class:
|
||||
* voice-channel resolution (checkVoiceChannels), 24/7 player spawning with
|
||||
* announcements, programmatic channel leave, shared-server listing, and
|
||||
* small translation/settings/pagination helpers.
|
||||
*
|
||||
* These methods are applied onto the Remix class prototype via
|
||||
* {@link applyMixins} — `this` is a Remix instance.
|
||||
*/
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { getGlobalColor, PageBuilder } from "../ui/index.mjs";
|
||||
import { cleanId } from "../utils/Utils.mjs";
|
||||
import { remove247ChannelMode } from "../utils/Helpers247.mjs";
|
||||
import { logger } from "./Logger.mjs";
|
||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Voice/channel mixin — applied to Remix.
|
||||
*/
|
||||
const BotVoiceMixin = {
|
||||
/**
|
||||
* Resolve the user's voice channel for a command invocation. Tries, in
|
||||
* order: the voice-state cache, the VoiceManager, guild voice states, a
|
||||
* cache scan, REST member fetch, and a raw REST member lookup.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} message - Message wrapper.
|
||||
* @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>}
|
||||
*/
|
||||
async _checkVoiceChannelsImpl(message) {
|
||||
const userId = message?.author?.id ?? message?.message?.author?.id;
|
||||
const guildId =
|
||||
message?.channel?.guildId ??
|
||||
message?.channel?.guild?.id ??
|
||||
message?.channel?.server_id ??
|
||||
message?.channel?.serverId ??
|
||||
message?.message?.guildId ??
|
||||
message?.message?.guild?.id ??
|
||||
message?.message?.channel?.guildId ??
|
||||
message?.message?.channel?.guild?.id ??
|
||||
message?.message?.channel?.server_id ??
|
||||
message?.message?.channel?.serverId;
|
||||
|
||||
const _empty = { channelId: null, alreadyInVoice: false, hasHumans: false };
|
||||
|
||||
if (!userId || !guildId) {
|
||||
logger.voice(`[checkVC] BAIL — missing userId or guildId`);
|
||||
return _empty;
|
||||
}
|
||||
|
||||
const cleanGuild = cleanId(guildId);
|
||||
|
||||
const makeResult = (channelId) => {
|
||||
const cId = cleanId(channelId);
|
||||
return {
|
||||
channelId: cId,
|
||||
alreadyInVoice: this.players.playerMap.has(cId),
|
||||
hasHumans: this.voiceCache.hasHumansInChannel(cleanGuild, cId),
|
||||
};
|
||||
};
|
||||
|
||||
const seedCache = (channelId) => {
|
||||
if (!this.voiceCache.hasHumanUser(userId, cleanGuild)) {
|
||||
this.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false });
|
||||
}
|
||||
};
|
||||
|
||||
logger.voice(`[checkVC] userId=${userId} guildId=${guildId} cleanGuild=${cleanGuild}`);
|
||||
|
||||
const observed = this.voiceCache.getUserLocation(cleanGuild, userId);
|
||||
if (observed && observed.channelId) {
|
||||
logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`);
|
||||
return makeResult(observed.channelId);
|
||||
}
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(this.client);
|
||||
const channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? vm?.getVoiceChannelId?.(cleanGuild, userId);
|
||||
logger.voice(`[checkVC] vm.getVoiceChannelId → ${channelId}`);
|
||||
if (channelId) {
|
||||
seedCache(channelId);
|
||||
return makeResult(channelId);
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] vm error: ${e.message}`); }
|
||||
|
||||
try {
|
||||
const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild);
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.values(voiceStates);
|
||||
for (const state of entries) {
|
||||
const sid = state?.userId ?? state?.user_id ?? state?.id;
|
||||
const sch = state?.channelId ?? state?.channel_id;
|
||||
if ((sid === userId || sid === cleanId(userId)) && sch) {
|
||||
logger.voice(`[checkVC] HIT guild.voice_states → ${sch}`);
|
||||
seedCache(sch);
|
||||
return makeResult(sch);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); }
|
||||
|
||||
try {
|
||||
const loc = this.voiceCache.getHumanUser(userId, cleanGuild);
|
||||
if (loc && loc.channelId) {
|
||||
logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`);
|
||||
return makeResult(loc.channelId);
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] scan error: ${e.message}`); }
|
||||
|
||||
try {
|
||||
const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild);
|
||||
if (guild && typeof guild.fetchMember === "function") {
|
||||
logger.voice(`[checkVC] Trying REST fetchMember fallback for user ${userId}`);
|
||||
const member = await guild.fetchMember(userId);
|
||||
const voiceState = member?.voice ?? member?.voiceState ?? null;
|
||||
const restChannelId = voiceState?.channelId ?? voiceState?.channel_id ?? null;
|
||||
if (restChannelId) {
|
||||
logger.voice(`[checkVC] HIT REST member.voice → ${restChannelId}`);
|
||||
seedCache(restChannelId);
|
||||
return makeResult(restChannelId);
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] REST fallback error: ${e.message}`); }
|
||||
|
||||
try {
|
||||
const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild);
|
||||
if (guild && typeof this.client.rest?.get === "function") {
|
||||
logger.voice(`[checkVC] Trying raw REST /guilds/${cleanGuild}/members/${userId}`);
|
||||
const memberData = await this.client.rest.get(`/guilds/${cleanGuild}/members/${userId}`);
|
||||
const restChannelId = memberData?.voice_state?.channel_id ?? memberData?.channel_id ?? null;
|
||||
if (restChannelId) {
|
||||
logger.voice(`[checkVC] HIT raw REST → ${restChannelId}`);
|
||||
seedCache(restChannelId);
|
||||
return makeResult(restChannelId);
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] raw REST error: ${e.message}`); }
|
||||
|
||||
logger.voice(`[checkVC] MISS — returning empty`);
|
||||
return _empty;
|
||||
},
|
||||
|
||||
/**
|
||||
* Mark a channel leave as intentional (user-initiated) to prevent the 24/7
|
||||
* auto-rejoin system from rejoining.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {string} channelId - The channel ID.
|
||||
* @param {number|null} [ttlMs=null] - TTL in ms (default: config.timers.intentionalLeaveTTL or 10s).
|
||||
*/
|
||||
markIntentionalLeave(channelId, ttlMs = null) {
|
||||
const cleanChId = cleanId(channelId);
|
||||
if (!cleanChId) return;
|
||||
if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000;
|
||||
const existing = this.intentionalLeaves.get(cleanChId);
|
||||
if (existing) clearTimeout(existing);
|
||||
this.intentionalLeaves.set(cleanChId, setTimeout(() => {
|
||||
this.intentionalLeaves.delete(cleanChId);
|
||||
}, ttlMs));
|
||||
},
|
||||
|
||||
/**
|
||||
* Spawn a new Player for a channel. Used by 24/7 boot recovery and
|
||||
* enable247. Guards against duplicate players, missing channels, and
|
||||
* pending joins.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The target voice channel ID.
|
||||
* @returns {Promise<import('../music/player/Player.mjs').Player>}
|
||||
* @throws {Error} If channel not found, not a voice channel, or join fails.
|
||||
*/
|
||||
async _spawnPlayer(guildId, channelId) {
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
const cleanChannelId = cleanId(channelId);
|
||||
|
||||
if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId");
|
||||
|
||||
const existing = this.players.playerMap.get(cleanChannelId)
|
||||
?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId);
|
||||
if (existing) return existing;
|
||||
|
||||
if (!this.lavalink) throw new Error("Audio node not ready yet — try again in a moment");
|
||||
|
||||
const channel = this.client?.channels?.get?.(cleanChannelId);
|
||||
if (!channel) throw new Error("Channel not found");
|
||||
if (channel.type !== 2) throw new Error("Not a voice channel");
|
||||
|
||||
if (this.players._pendingJoins?.has?.(cleanChannelId)) {
|
||||
throw new Error("Join already in progress for this channel");
|
||||
}
|
||||
|
||||
const Player = (await import("../music/player/index.mjs")).default;
|
||||
|
||||
const player = new Player(this.config.token, {
|
||||
client: this.client,
|
||||
config: this.config,
|
||||
lavalink: this.lavalink ?? null,
|
||||
settingsMgr: this.settingsMgr ?? this.settings ?? null,
|
||||
getPrefix: (guildId) => this.handler.getPrefix(guildId),
|
||||
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||
voiceCache: this.voiceCache ?? null,
|
||||
locale: this.locale ?? null,
|
||||
trackOptions: this.trackOptions ?? null,
|
||||
});
|
||||
|
||||
player._home247Channel = cleanChannelId;
|
||||
|
||||
this.players.setupEvents(player, {
|
||||
channelId: cleanChannelId,
|
||||
guildId: cleanGuildId,
|
||||
});
|
||||
|
||||
player.on("autoleave", () => {
|
||||
const mode = player._get247Mode();
|
||||
if (mode === "on") {
|
||||
logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 channel ${cleanChannelId} (guild ${cleanGuildId})`);
|
||||
return;
|
||||
}
|
||||
if (player._hasHumansInChannel()) {
|
||||
logger.inactivity(`[_spawnPlayer] autoleave suppressed — humans in channel ${cleanChannelId}`);
|
||||
return;
|
||||
}
|
||||
if (player.queue?.getCurrent() || !player.queue?.isEmpty()) {
|
||||
logger.inactivity(`[_spawnPlayer] autoleave suppressed — queue has songs in channel ${cleanChannelId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const activeChId = cleanId(player._channelId ?? cleanChannelId) || cleanChannelId;
|
||||
const homeChId = cleanId(player._home247Channel ?? activeChId) || activeChId;
|
||||
this.players.playerMap.delete(activeChId);
|
||||
this.players._unindexPlayer?.(cleanGuildId, activeChId);
|
||||
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId);
|
||||
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChannelId); }
|
||||
if (activeChId !== cleanChannelId) this.players.playerMap.delete(cleanChannelId);
|
||||
if (homeChId !== activeChId) this.players.playerMap.delete(homeChId);
|
||||
player.destroy();
|
||||
});
|
||||
|
||||
player.on("message", async (m) => {
|
||||
try {
|
||||
const serverSettings = this.settingsMgr?.getServer?.(cleanGuildId);
|
||||
const raw = serverSettings?.get?.("songAnnouncements");
|
||||
const disabled = raw === false || raw === 0 ||
|
||||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
|
||||
if (disabled) return;
|
||||
|
||||
const chMgr = this.client?.channels ?? null;
|
||||
const canPostById = (c) => !!c?.id && !!chMgr && typeof chMgr.send === "function";
|
||||
const asSendable = (c) => {
|
||||
if (!c || typeof c === "string" || typeof c.send === "function") return c;
|
||||
if (!canPostById(c)) return c;
|
||||
const target = { id: c.id, type: c.type };
|
||||
target.isTextBased = () => true;
|
||||
target.send = (options) => chMgr.send(c.id, options);
|
||||
return target;
|
||||
};
|
||||
const usable = (c) => !!c && typeof c === "object" &&
|
||||
(typeof c.send === "function" || canPostById(c));
|
||||
|
||||
const _tc = player.textChannel;
|
||||
let ch = (_tc && typeof _tc === "object" && _tc.channel && typeof _tc.channel === "object")
|
||||
? _tc.channel
|
||||
: _tc;
|
||||
if (!usable(ch)) {
|
||||
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
|
||||
if (savedAnnChId) {
|
||||
ch = this.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
|
||||
}
|
||||
}
|
||||
if (!usable(ch)) {
|
||||
const guild = this.client?.guilds?.get?.(cleanGuildId);
|
||||
if (guild?.systemChannelId) {
|
||||
ch = guild.channels?.get?.(guild.systemChannelId) ?? null;
|
||||
}
|
||||
}
|
||||
if (!usable(ch)) {
|
||||
const guild = this.client?.guilds?.get?.(cleanGuildId);
|
||||
if (guild?.channels) {
|
||||
for (const c of (guild.channels.values?.() ?? [])) {
|
||||
if (c.isTextBased?.() || c.type === 0 || c.type === "GUILD_TEXT") {
|
||||
ch = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!usable(ch)) return;
|
||||
|
||||
ch = asSendable(ch);
|
||||
if (!player.textChannel) player.textChannel = ch;
|
||||
|
||||
const payload = typeof m === "object" && Array.isArray(m.embeds)
|
||||
? { ...m, allowedMentions: { parse: [] } }
|
||||
: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)], allowedMentions: { parse: [] } };
|
||||
ch.send(payload).catch(err => {
|
||||
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||
logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`);
|
||||
} else {
|
||||
logger.warn(`[_spawnPlayer] Failed to send announcement in channel ${ch.id}:`, err?.message ?? err);
|
||||
}
|
||||
});
|
||||
} catch(e) {
|
||||
logger.warn("[Player] Song announcement error:", e?.message);
|
||||
}
|
||||
});
|
||||
|
||||
if (this.players._pendingJoins) {
|
||||
this.players._pendingJoins.add(cleanChannelId);
|
||||
}
|
||||
|
||||
try {
|
||||
await player.join(cleanChannelId);
|
||||
|
||||
this.players.playerMap.set(cleanChannelId, player);
|
||||
this.players._indexPlayer(cleanGuildId, cleanChannelId);
|
||||
if (this.players._pendingJoins) {
|
||||
this.players._pendingJoins.delete(cleanChannelId);
|
||||
}
|
||||
|
||||
const savedVol = this.settingsMgr?.getServer?.(cleanGuildId)?.get?.("volume");
|
||||
if (savedVol !== undefined && savedVol !== null) {
|
||||
const vol = Number(savedVol);
|
||||
if (!isNaN(vol)) player.setVolume(vol / 100);
|
||||
}
|
||||
|
||||
logger.player(`[_spawnPlayer] Spawned player for channel ${cleanChannelId} in guild ${cleanGuildId}`);
|
||||
return player;
|
||||
} catch (err) {
|
||||
if (this.players._pendingJoins) {
|
||||
this.players._pendingJoins.delete(cleanChannelId);
|
||||
}
|
||||
this.players.playerMap.delete(cleanChannelId);
|
||||
try { player.destroy(); } catch(e) { logger.warn("[_spawnPlayer] Cleanup destroy error:", e?.message); }
|
||||
logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Leave a voice channel programmatically. Removes 24/7 if active, destroys
|
||||
* the player, and optionally sends a confirmation message.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {string} channelId - The channel ID to leave.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {object} [message=null] - Optional message for reply confirmation.
|
||||
* @param {boolean} [force=false] - Whether to force-leave regardless of 24/7 status.
|
||||
* @returns {Promise<boolean>} True on success.
|
||||
*/
|
||||
async leaveChannel(channelId, guildId, message, force = false) {
|
||||
const cleanChId = cleanId(channelId);
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
const set = this.settingsMgr.getServer(cleanGuildId);
|
||||
const raw = set?.get("stay_247");
|
||||
|
||||
const channels = (!raw || raw === "none")
|
||||
? new Set()
|
||||
: Array.isArray(raw)
|
||||
? new Set(raw.map(id => cleanId(id)).filter(Boolean))
|
||||
: new Set([cleanId(raw)]);
|
||||
|
||||
if (channels.has(cleanChId)) {
|
||||
channels.delete(cleanChId);
|
||||
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
|
||||
remove247ChannelMode(set, cleanChId, channels);
|
||||
}
|
||||
|
||||
this.markIntentionalLeave(cleanChId);
|
||||
|
||||
const player = this.players.playerMap.get(cleanChId);
|
||||
if (player) {
|
||||
this.players.playerMap.delete(cleanChId);
|
||||
this.players._unindexPlayer(player._guildId, cleanChId);
|
||||
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChId);
|
||||
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChId); }
|
||||
await player.leave().catch(() => {});
|
||||
player.destroy();
|
||||
}
|
||||
|
||||
if (message) {
|
||||
const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId;
|
||||
message.replyEmbed(this.locale.translate(guildIdForLocale, "responses._common.successfullyLeft"));
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the server settings for the guild associated with a message.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} message - The incoming message wrapper.
|
||||
* @returns {object} The ServerSettings for the guild, or a fallback.
|
||||
*/
|
||||
getSettings(message) {
|
||||
const guildId = message?.channel?.channel?.guildId ?? message?.guildId ?? null;
|
||||
return this.settingsMgr.getServer(guildId);
|
||||
},
|
||||
|
||||
/**
|
||||
* Shorthand to translate a locale key for the guild of a given message.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} message - The message wrapper (used to resolve guild ID).
|
||||
* @param {string} key - The locale key.
|
||||
* @param {object} [data={}] - Interpolation data.
|
||||
* @returns {string} The localised string.
|
||||
*/
|
||||
t(message, key, data = {}) {
|
||||
const guildId = message?.channel?.channel?.guildId
|
||||
?? message?.message?.guildId
|
||||
?? message?.guildId
|
||||
?? null;
|
||||
return this.locale.translate(guildId, key, data);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get or create a player for the given message context.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} message - The message wrapper.
|
||||
* @param {boolean} promptJoin - Whether to prompt the user to join a voice channel.
|
||||
* @param {boolean} verifyUser - Whether to verify the user is in a voice channel.
|
||||
* @param {boolean} shouldJoin - Whether to auto-join the voice channel.
|
||||
* @returns {Promise<object>} The Player instance.
|
||||
*/
|
||||
getPlayer(message, promptJoin, verifyUser, shouldJoin) {
|
||||
return this.players.getPlayer(message, promptJoin, verifyUser, shouldJoin);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all servers the bot and the given user share (i.e. the user is a
|
||||
* member). Used by the dashboard to determine which servers a user can
|
||||
* manage.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} user - The Fluxer user.
|
||||
* @returns {Promise<Array<object>>} Array of server summaries with channels.
|
||||
*/
|
||||
async getSharedServers(user) {
|
||||
if (!user) return [];
|
||||
|
||||
const shared = [];
|
||||
|
||||
for (const guild of this.client.guilds?.values?.() ?? []) {
|
||||
let isMember = false;
|
||||
|
||||
if (guild.members?.has?.(user.id)) {
|
||||
isMember = true;
|
||||
}
|
||||
|
||||
if (!isMember) {
|
||||
const cleanGuildId = cleanId(guild.id);
|
||||
const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id);
|
||||
if (userLoc) isMember = true;
|
||||
}
|
||||
|
||||
if (!isMember) {
|
||||
try {
|
||||
const member = await guild.members.fetch(user.id).catch(() => null);
|
||||
if (member) isMember = true;
|
||||
} catch (e) { logger.warn(`[getSharedServers] Member fetch error for ${user.id}:`, e?.message); }
|
||||
}
|
||||
|
||||
if (!isMember) continue;
|
||||
|
||||
const guildChannels = guild.channels
|
||||
? [...guild.channels.values()]
|
||||
: [];
|
||||
const allChannels = guildChannels
|
||||
.map(c => Dashboard.convertChannel(c))
|
||||
.filter(c => !c.isCategory);
|
||||
const channelIds = guildChannels.map(c => c.id);
|
||||
|
||||
shared.push({
|
||||
name: guild.name,
|
||||
id: guild.id,
|
||||
icon: guild.icon
|
||||
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
|
||||
: null,
|
||||
description: guild.description ?? null,
|
||||
ownerId: guild.ownerId ?? null,
|
||||
channels: allChannels,
|
||||
channelIds: channelIds,
|
||||
voiceChannels: allChannels.filter(c => c.isVoice),
|
||||
});
|
||||
}
|
||||
|
||||
return shared;
|
||||
},
|
||||
|
||||
/**
|
||||
* Create and attach a paginated message to the given message.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {string} form - The form/locale key for the page title.
|
||||
* @param {string} content - The full content to paginate.
|
||||
* @param {object} msg - The message wrapper.
|
||||
* @param {number} linesPerPage - Maximum lines per page.
|
||||
*/
|
||||
pagination(form, content, msg, linesPerPage) {
|
||||
this.messages.initPagination(
|
||||
new PageBuilder(content).setForm(form).setMaxLines(linesPerPage),
|
||||
msg
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export default BotVoiceMixin;
|
||||
export { BotVoiceMixin };
|
||||
@@ -0,0 +1,210 @@
|
||||
/** @module src/core/Locale */
|
||||
|
||||
import { readFileSync, readdirSync, existsSync } from "fs";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { logger } from "./Logger.mjs";
|
||||
|
||||
/** @private */
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
/** @private */
|
||||
const LOCALES_DIR = path.resolve(__dirname, "../../storage/locales/bot");
|
||||
|
||||
/**
|
||||
* Locale/i18n manager that loads JSON locale files from disk and provides
|
||||
* dot-notation key lookups with `{{placeholder}}` and `$prefix` substitution.
|
||||
* @class
|
||||
*/
|
||||
export class Locale {
|
||||
/**
|
||||
* @param {string} [defaultPrefix="%"] - Fallback prefix used when no prefix
|
||||
* resolver is registered and the settings manager yields no prefix.
|
||||
*/
|
||||
constructor(defaultPrefix = "%") {
|
||||
/** @private */ this.locales = new Map();
|
||||
/** @private */ this._resolved = new Map();
|
||||
/** @type {string} */ this.defaultLocale = "en";
|
||||
/** @private */ this.settingsMgr = null;
|
||||
/** @private */ this._getPrefixFn = null;
|
||||
/** @private */ this._defaultPrefix = defaultPrefix;
|
||||
/** @private */ this._maxResolvedCache = 5000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind a settings manager so the locale resolver can look up per-guild locale preferences.
|
||||
* @param {object} settingsMgr - Settings manager exposing `guilds.get(guildId)`.
|
||||
*/
|
||||
bind(settingsMgr) {
|
||||
this.settingsMgr = settingsMgr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all `.json` locale files from the locales directory.
|
||||
* Clears any previously loaded data and the resolved-cache.
|
||||
*/
|
||||
load() {
|
||||
this.locales.clear();
|
||||
this._resolved.clear();
|
||||
|
||||
if (!existsSync(LOCALES_DIR)) {
|
||||
logger.warn("[Locale] Locales directory not found:", LOCALES_DIR);
|
||||
return;
|
||||
}
|
||||
|
||||
let files;
|
||||
try {
|
||||
files = readdirSync(LOCALES_DIR).filter(f => f.endsWith(".json"));
|
||||
} catch (e) {
|
||||
logger.warn("[Locale] Failed to read locales directory:", e.message);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const filePath = path.join(LOCALES_DIR, file);
|
||||
const code = file.replace(".json", "");
|
||||
try {
|
||||
const data = JSON.parse(readFileSync(filePath, "utf8"));
|
||||
this.locales.set(code, data);
|
||||
} catch (e) {
|
||||
logger.warn("[Locale] Failed to load " + file + ":", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("[Locale] Loaded " + this.locales.size + " locale(s): " + [...this.locales.keys()].join(", "));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the set of loaded locale codes.
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
availableLocales() {
|
||||
return new Set(this.locales.keys());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the locale data object for a guild, using per-guild settings or falling
|
||||
* back to the default locale. Results are cached with an LRU-style cap.
|
||||
* @private
|
||||
* @param {string} guildId
|
||||
* @returns {object} The locale data object.
|
||||
*/
|
||||
_getLocaleData(guildId) {
|
||||
if (!guildId) return this.locales.get(this.defaultLocale) ?? {};
|
||||
|
||||
const cached = this._resolved.get(guildId);
|
||||
if (cached) return cached;
|
||||
|
||||
let code = this.defaultLocale;
|
||||
try {
|
||||
const serverSettings = this.settingsMgr?.guilds?.get?.(guildId);
|
||||
if (serverSettings) {
|
||||
const setting = serverSettings.get("locale");
|
||||
if (setting && this.locales.has(setting)) {
|
||||
code = setting;
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[Locale] Error:", e?.message); }
|
||||
|
||||
const data = this.locales.get(code) ?? this.locales.get(this.defaultLocale) ?? {};
|
||||
this._resolved.set(guildId, data);
|
||||
|
||||
while (this._resolved.size > this._maxResolvedCache) {
|
||||
const oldestKey = this._resolved.keys().next().value;
|
||||
this._resolved.delete(oldestKey);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate the resolved-cache for a specific guild or all guilds.
|
||||
* @param {string} [guildId] - Omit to clear the entire cache.
|
||||
*/
|
||||
invalidateCache(guildId) {
|
||||
if (guildId) {
|
||||
this._resolved.delete(guildId);
|
||||
} else {
|
||||
this._resolved.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a custom prefix resolver function.
|
||||
* @param {function(string): string} fn - Receives `guildId`, returns the prefix string.
|
||||
*/
|
||||
setPrefixResolver(fn) {
|
||||
this._getPrefixFn = fn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the command prefix for a guild.
|
||||
* @private
|
||||
* @param {string} guildId
|
||||
* @returns {string}
|
||||
*/
|
||||
_getPrefix(guildId) {
|
||||
if (this._getPrefixFn) return this._getPrefixFn(guildId);
|
||||
try {
|
||||
const serverSettings = this.settingsMgr?.getServer?.(guildId);
|
||||
if (serverSettings) {
|
||||
const prefix = serverSettings.get("prefix");
|
||||
if (prefix) return prefix;
|
||||
}
|
||||
} catch(e) { logger.warn("[Locale] Error:", e?.message); }
|
||||
return this._defaultPrefix || "!";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a dot-notation key against a nested object.
|
||||
* @private
|
||||
* @param {object} obj
|
||||
* @param {string} key - e.g. "commands.play.description"
|
||||
* @returns {*}
|
||||
*/
|
||||
_resolve(obj, key) {
|
||||
const parts = key.split(".");
|
||||
let current = obj;
|
||||
for (const part of parts) {
|
||||
if (current == null || typeof current !== "object") return undefined;
|
||||
current = current[part];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a locale key for a guild, applying `{{placeholder}}` replacements
|
||||
* and `$prefix` substitution. Falls back to the default locale, then the raw key.
|
||||
* @param {string} guildId
|
||||
* @param {string} key - Dot-notation locale key.
|
||||
* @param {Object<string, *>} [replacements={}] - Placeholder values to substitute.
|
||||
* @returns {string} The translated (or fallback) string.
|
||||
*/
|
||||
translate(guildId, key, replacements = {}) {
|
||||
const localeData = this._getLocaleData(guildId);
|
||||
|
||||
let value = this._resolve(localeData, key);
|
||||
|
||||
if (value === undefined) {
|
||||
value = this._resolve(this.locales.get(this.defaultLocale) ?? {}, key);
|
||||
}
|
||||
|
||||
if (value === undefined) return key;
|
||||
if (typeof value !== "string") return key;
|
||||
|
||||
for (const [placeholder, val] of Object.entries(replacements)) {
|
||||
const escaped = placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const replacement = String(val ?? "");
|
||||
value = value.replace(
|
||||
new RegExp(`\\{\\{${escaped}\\}\\}`, "g"),
|
||||
() => replacement
|
||||
);
|
||||
}
|
||||
|
||||
if (value.includes("$prefix")) {
|
||||
const prefix = this._getPrefix(guildId);
|
||||
value = value.replace(/\$prefix/gi, prefix);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
/** @module src/core/Logger */
|
||||
|
||||
/** @private */
|
||||
let _config = null;
|
||||
|
||||
/**
|
||||
* Initialize the logger with a configuration object.
|
||||
* @param {object} [config] - Application configuration object.
|
||||
* @param {object} [config.logging] - Logging-specific configuration.
|
||||
*/
|
||||
export function initLogger(config) {
|
||||
_config = config?.logging ?? {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a given log category is enabled.
|
||||
* @private
|
||||
* @param {string} category - The log category name (e.g. "player", "voice").
|
||||
* @returns {boolean} `true` if the category is enabled (or no config is loaded).
|
||||
*/
|
||||
function isEnabled(category) {
|
||||
if (!_config) return true;
|
||||
if (_config.enabled === false) return false;
|
||||
return _config[category] !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an ISO-8601 timestamp string truncated to seconds.
|
||||
* @private
|
||||
* @returns {string} Timestamp in `YYYY-MM-DD HH:MM:SS` format.
|
||||
*/
|
||||
function ts() {
|
||||
return new Date().toISOString().replace("T", " ").slice(0, 19);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cooldown state for WebSocket error logging to avoid spam.
|
||||
* @type {{ lastLogged: number, COOLDOWN_MS: number }}
|
||||
*/
|
||||
export const _wsErrorCooldown = { lastLogged: 0, COOLDOWN_MS: 15_000 };
|
||||
|
||||
/**
|
||||
* Log-storm suppression for identical repeated `error`/`warn` lines.
|
||||
* The first occurrence is always emitted; identical repeats within a 60s
|
||||
* window are counted silently, and once per window a single pulse line with
|
||||
* the repeat count is emitted instead. Bounds worst-case volume of any hot
|
||||
* retry loop to one line per minute instead of millions.
|
||||
* @private
|
||||
* @type {Map<string, {n: number, start: number}>}
|
||||
*/
|
||||
const _stormGuard = new Map();
|
||||
const STORM_WINDOW_MS = 60_000;
|
||||
const STORM_MAX_KEYS = 128;
|
||||
|
||||
/**
|
||||
* Decide whether an error/warn line should be emitted, and with what suffix.
|
||||
* @private
|
||||
* @param {string} level - Log level ("error" | "warn").
|
||||
* @param {string} tag - Caller tag (e.g. "[Redis/Main]").
|
||||
* @param {Array<*>} args - Message arguments.
|
||||
* @returns {{emit: boolean, suffix: string}} Whether to emit, and the pulse suffix.
|
||||
*/
|
||||
function _stormGate(level, tag, args) {
|
||||
const key = level + "|" + tag + "|" + args.map(a => (typeof a === "string" ? a : String(a))).join(" ");
|
||||
const now = Date.now();
|
||||
const st = _stormGuard.get(key);
|
||||
if (st === undefined) {
|
||||
if (_stormGuard.size >= STORM_MAX_KEYS) {
|
||||
// Evict the oldest key to bound memory.
|
||||
_stormGuard.delete(_stormGuard.keys().next().value);
|
||||
}
|
||||
_stormGuard.set(key, { n: 0, start: now });
|
||||
return { emit: true, suffix: "" };
|
||||
}
|
||||
st.n++;
|
||||
if (now - st.start >= STORM_WINDOW_MS) {
|
||||
const n = st.n;
|
||||
st.n = 0;
|
||||
st.start = now;
|
||||
return { emit: true, suffix: `── identical line suppressed ${n}x in the last 60s` };
|
||||
}
|
||||
return { emit: false, suffix: "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the log-storm suppression state (used by tests).
|
||||
* @returns {void}
|
||||
*/
|
||||
export function _resetStormGuard() {
|
||||
_stormGuard.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Structured logger exposing category-gated log methods.
|
||||
* @namespace logger
|
||||
*/
|
||||
export const logger = {
|
||||
/**
|
||||
* Log an error message (always emitted regardless of config).
|
||||
* @param {string} tag - A tag identifying the source (e.g. "[Player]").
|
||||
* @param {...*} args - Additional values to log.
|
||||
*/
|
||||
error(tag, ...args) {
|
||||
const g = _stormGate("error", tag, args);
|
||||
if (!g.emit) return;
|
||||
console.error(`[${ts()}] ${tag}`, ...args, ...(g.suffix ? [g.suffix] : []));
|
||||
},
|
||||
/**
|
||||
* Log a warning message. Honours `logging.warn` override when logging is disabled.
|
||||
* @param {string} tag - A tag identifying the source.
|
||||
* @param {...*} args - Additional values to log.
|
||||
*/
|
||||
warn(tag, ...args) {
|
||||
if (_config?.enabled === false && _config?.warn !== true) return;
|
||||
const g = _stormGate("warn", tag, args);
|
||||
if (!g.emit) return;
|
||||
console.warn(`[${ts()}] ${tag}`, ...args, ...(g.suffix ? [g.suffix] : []));
|
||||
},
|
||||
/**
|
||||
* Log an info message. Suppressed when `logging.enabled === false`.
|
||||
* @param {string} tag - A tag identifying the source.
|
||||
* @param {...*} args - Additional values to log.
|
||||
*/
|
||||
info(tag, ...args) {
|
||||
if (_config?.enabled === false) return;
|
||||
console.log(`[${ts()}] ${tag}`, ...args);
|
||||
},
|
||||
|
||||
/**
|
||||
* Category-gated player log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated inactivity log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated voice 24/7 log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
voice247(...args) { if (isEnabled("voice247")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated voice-state log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
voiceState(...args) { if (isEnabled("voiceState")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated media-player log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
mediaplayer(...args) { if (isEnabled("mediaplayer")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated commands log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
commands(...args) { if (isEnabled("commands")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated guild log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
guild(...args) { if (isEnabled("guild")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated recovery log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
recovery(...args) { if (isEnabled("recovery")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated settings log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
settings(...args) { if (isEnabled("settings")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated lavalink log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
lavalink(...args) { if (isEnabled("lavalink")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated alone-check log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
aloneCheck(...args) { if (isEnabled("aloneCheck")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated voice log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
voice(...args) { if (isEnabled("voice")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated dashboard log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
dashboard(...args) { if (isEnabled("dashboard")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated redis log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
redis(...args) { if (isEnabled("redis")) console.log(`[${ts()}]`, ...args); },
|
||||
};
|
||||
Reference in new issue
Block a user