From 253d11cd5734ec9d87cc61e14d4f610bc4e7afe2 Mon Sep 17 00:00:00 2001
From: NoLogicAlan
Date: Wed, 9 Sep 2026 02:04:33 +0300
Subject: [PATCH] =?UTF-8?q?Remix=20=E2=80=94=20the=20complete=20rewrite?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
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).
---
.gitignore | 15 +-
README.md | 265 +-
commands/autoplay.mjs | 6 +-
commands/clear.mjs | 4 +-
commands/debug.mjs | 623 +---
commands/debug/consts.mjs | 10 +
commands/debug/gateway.mjs | 134 +
commands/debug/rejoin.mjs | 259 ++
commands/debug/voiceDiagnostic.mjs | 236 ++
commands/eval.mjs | 10 +-
commands/filter.mjs | 10 +-
commands/forceleave.mjs | 4 +-
commands/invite.mjs | 4 +-
commands/join.mjs | 4 +-
commands/lastfm.mjs | 2542 +----------------
commands/lastfm/account.mjs | 245 ++
commands/lastfm/discovery.mjs | 372 +++
commands/lastfm/help.mjs | 99 +
commands/lastfm/index.mjs | 16 +
commands/lastfm/info.mjs | 505 ++++
commands/lastfm/listening.mjs | 358 +++
commands/lastfm/playback.mjs | 326 +++
commands/lastfm/shared.mjs | 80 +
commands/lastfm/tags.mjs | 337 +++
commands/lastfm/whoknows.mjs | 525 ++++
commands/leave.mjs | 8 +-
commands/list.mjs | 4 +-
commands/loop.mjs | 4 +-
commands/lyrics.mjs | 10 +-
commands/move.mjs | 2 +-
commands/np.mjs | 4 +-
commands/pause.mjs | 4 +-
commands/play.mjs | 12 +-
commands/player.mjs | 291 +-
commands/player/consts.mjs | 38 +
commands/player/embed.mjs | 96 +
commands/player/index.mjs | 10 +
commands/player/lyrics.mjs | 166 ++
commands/playnext.mjs | 6 +-
commands/radio.mjs | 8 +-
commands/reload.mjs | 4 +-
commands/remove.mjs | 2 +-
commands/resume.mjs | 4 +-
commands/search.mjs | 10 +-
commands/seek.mjs | 8 +-
commands/servers.mjs | 8 +-
commands/settings.mjs | 463 +--
commands/settings/channels247.mjs | 198 ++
commands/settings/setters.mjs | 136 +
commands/settings/utils.mjs | 146 +
commands/shuffle.mjs | 4 +-
commands/skip.mjs | 4 +-
commands/stats.mjs | 50 +-
commands/support.mjs | 4 +-
commands/test.mjs | 6 +-
commands/thumbnail.mjs | 4 +-
commands/trackopt.mjs | 10 +-
commands/volume.mjs | 6 +-
commands/volumedefault.mjs | 6 +-
commands/vote.mjs | 12 +-
config_example.json | 10 +-
docker/Dockerfile | 2 +-
docker/docker-entrypoint.sh | 4 +
index.mjs | 1037 +------
package-lock.json | 1741 -----------
package.json | 9 +-
settings/README.md | 4 +-
settings/Settings.mjs | 2 +-
settings/migrate.mjs | 4 +-
shard.mjs | 157 +
src/CommandHandler.mjs | 927 ------
src/FluxerAudioBridge.mjs | 879 ------
src/GatewayHandler.mjs | 1473 ----------
src/LastFmManager.mjs | 2324 ---------------
src/MessageHandler.mjs | 1164 --------
src/Player.mjs | 2105 --------------
src/commands/CommandBuilder.mjs | 166 ++
src/commands/CommandHandler.mjs | 569 ++++
src/commands/CommandLoader.mjs | 123 +
src/commands/HelpHandler.mjs | 203 ++
src/commands/Option.mjs | 279 ++
src/commands/PrefixManager.mjs | 35 +
src/commands/index.mjs | 14 +
src/constants/VoiceStateResolver.mjs | 8 +-
src/core/Bot.mjs | 588 ++++
src/core/BotVoiceMixin.mjs | 511 ++++
src/core/Locale.mjs | 210 ++
src/core/Logger.mjs | 199 ++
src/dashboard/Dashboard.mjs | 668 +----
src/dashboard/RedisHandler.mjs | 134 +-
src/dashboard/RpcHandlersMixin.mjs | 362 +++
src/dashboard/Serializers.mjs | 300 ++
src/dashboard/index.mjs | 6 +
src/db/DatabaseManager.mjs | 82 +
src/{ => db}/Settings.mjs | 4 +-
src/{ => music}/LavalinkManager.mjs | 71 +-
src/music/PlayerEventsMixin.mjs | 298 ++
.../PlayerLifecycleMixin.mjs} | 530 +---
src/music/PlayerManager.mjs | 229 ++
src/music/audio/FluxerAudioBridge.mjs | 419 +++
src/music/audio/HttpStreams.mjs | 185 ++
src/music/audio/StreamPipeline.mjs | 326 +++
src/music/audio/Tuna.mjs | 107 +
src/music/audio/WebMOpusMuxer.mjs | 220 ++
src/music/audio/index.mjs | 9 +
src/music/player/DisplayMixin.mjs | 292 ++
src/music/player/PlaybackMixin.mjs | 631 ++++
src/music/player/Player.mjs | 993 +++++++
src/music/player/Queue.mjs | 168 ++
src/music/player/SearchMixin.mjs | 484 ++++
src/music/player/index.mjs | 9 +
src/{ => music}/probe.mjs | 4 +-
src/music/providers.mjs | 122 +
src/{ => services}/FluxerListManager.mjs | 6 +-
src/{ => services}/TrackOptionsManager.mjs | 4 +-
src/services/lastfm/LastFmManager.mjs | 287 ++
src/services/lastfm/ScrobblingMixin.mjs | 98 +
src/services/lastfm/ServerStatsMixin.mjs | 460 +++
src/services/lastfm/TrackQueriesMixin.mjs | 795 ++++++
src/services/lastfm/UserQueriesMixin.mjs | 593 ++++
src/services/lastfm/UserStoreMixin.mjs | 121 +
src/services/lastfm/constants.mjs | 55 +
src/services/lastfm/index.mjs | 10 +
src/services/lastfm/urlUtils.mjs | 56 +
src/ui/Embeds.mjs | 50 +
src/ui/HelpCommand.mjs | 254 ++
src/ui/MessageHandler.mjs | 583 ++++
src/ui/Paginators.mjs | 394 +++
src/ui/Permissions.mjs | 27 +
src/ui/Wrappers.mjs | 191 ++
src/ui/index.mjs | 15 +
src/utils/API.mjs | 100 +
src/utils/Helpers247.mjs | 39 +
src/utils/ShardingUtils.mjs | 140 +
src/utils/UI.mjs | 37 +
src/{ => utils}/Utils.mjs | 6 +-
src/utils/mixins.mjs | 33 +
src/voice/VoiceStateCache.mjs | 589 ++++
src/voice/VoiceStateResolver.mjs | 138 +
src/voice/gateway/GatewayHandler.mjs | 602 ++++
src/voice/gateway/GuildSync.mjs | 391 +++
src/voice/gateway/RejoinManager.mjs | 169 ++
src/voice/gateway/VoiceStateRouting.mjs | 435 +++
src/voice/gateway/index.mjs | 8 +
storage/locales/bot/ar-SA.json | 1 +
storage/locales/bot/ckb.json | 1 +
storage/locales/bot/de-DE.json | 1 +
storage/locales/bot/en.json | 1 +
storage/locales/bot/pt-BR.json | 1 +
storage/locales/bot/tr.json | 1 +
150 files changed, 19935 insertions(+), 16894 deletions(-)
create mode 100644 commands/debug/consts.mjs
create mode 100644 commands/debug/gateway.mjs
create mode 100644 commands/debug/rejoin.mjs
create mode 100644 commands/debug/voiceDiagnostic.mjs
create mode 100644 commands/lastfm/account.mjs
create mode 100644 commands/lastfm/discovery.mjs
create mode 100644 commands/lastfm/help.mjs
create mode 100644 commands/lastfm/index.mjs
create mode 100644 commands/lastfm/info.mjs
create mode 100644 commands/lastfm/listening.mjs
create mode 100644 commands/lastfm/playback.mjs
create mode 100644 commands/lastfm/shared.mjs
create mode 100644 commands/lastfm/tags.mjs
create mode 100644 commands/lastfm/whoknows.mjs
create mode 100644 commands/player/consts.mjs
create mode 100644 commands/player/embed.mjs
create mode 100644 commands/player/index.mjs
create mode 100644 commands/player/lyrics.mjs
create mode 100644 commands/settings/channels247.mjs
create mode 100644 commands/settings/setters.mjs
create mode 100644 commands/settings/utils.mjs
delete mode 100644 package-lock.json
create mode 100644 shard.mjs
delete mode 100644 src/CommandHandler.mjs
delete mode 100644 src/FluxerAudioBridge.mjs
delete mode 100644 src/GatewayHandler.mjs
delete mode 100644 src/LastFmManager.mjs
delete mode 100644 src/MessageHandler.mjs
delete mode 100644 src/Player.mjs
create mode 100644 src/commands/CommandBuilder.mjs
create mode 100644 src/commands/CommandHandler.mjs
create mode 100644 src/commands/CommandLoader.mjs
create mode 100644 src/commands/HelpHandler.mjs
create mode 100644 src/commands/Option.mjs
create mode 100644 src/commands/PrefixManager.mjs
create mode 100644 src/commands/index.mjs
create mode 100644 src/core/Bot.mjs
create mode 100644 src/core/BotVoiceMixin.mjs
create mode 100644 src/core/Locale.mjs
create mode 100644 src/core/Logger.mjs
create mode 100644 src/dashboard/RpcHandlersMixin.mjs
create mode 100644 src/dashboard/Serializers.mjs
create mode 100644 src/dashboard/index.mjs
create mode 100644 src/db/DatabaseManager.mjs
rename src/{ => db}/Settings.mjs (99%)
rename src/{ => music}/LavalinkManager.mjs (90%)
create mode 100644 src/music/PlayerEventsMixin.mjs
rename src/{PlayerManager.mjs => music/PlayerLifecycleMixin.mjs} (54%)
create mode 100644 src/music/PlayerManager.mjs
create mode 100644 src/music/audio/FluxerAudioBridge.mjs
create mode 100644 src/music/audio/HttpStreams.mjs
create mode 100644 src/music/audio/StreamPipeline.mjs
create mode 100644 src/music/audio/Tuna.mjs
create mode 100644 src/music/audio/WebMOpusMuxer.mjs
create mode 100644 src/music/audio/index.mjs
create mode 100644 src/music/player/DisplayMixin.mjs
create mode 100644 src/music/player/PlaybackMixin.mjs
create mode 100644 src/music/player/Player.mjs
create mode 100644 src/music/player/Queue.mjs
create mode 100644 src/music/player/SearchMixin.mjs
create mode 100644 src/music/player/index.mjs
rename src/{ => music}/probe.mjs (93%)
create mode 100644 src/music/providers.mjs
rename src/{ => services}/FluxerListManager.mjs (96%)
rename src/{ => services}/TrackOptionsManager.mjs (98%)
create mode 100644 src/services/lastfm/LastFmManager.mjs
create mode 100644 src/services/lastfm/ScrobblingMixin.mjs
create mode 100644 src/services/lastfm/ServerStatsMixin.mjs
create mode 100644 src/services/lastfm/TrackQueriesMixin.mjs
create mode 100644 src/services/lastfm/UserQueriesMixin.mjs
create mode 100644 src/services/lastfm/UserStoreMixin.mjs
create mode 100644 src/services/lastfm/constants.mjs
create mode 100644 src/services/lastfm/index.mjs
create mode 100644 src/services/lastfm/urlUtils.mjs
create mode 100644 src/ui/Embeds.mjs
create mode 100644 src/ui/HelpCommand.mjs
create mode 100644 src/ui/MessageHandler.mjs
create mode 100644 src/ui/Paginators.mjs
create mode 100644 src/ui/Permissions.mjs
create mode 100644 src/ui/Wrappers.mjs
create mode 100644 src/ui/index.mjs
create mode 100644 src/utils/API.mjs
create mode 100644 src/utils/Helpers247.mjs
create mode 100644 src/utils/ShardingUtils.mjs
create mode 100644 src/utils/UI.mjs
rename src/{ => utils}/Utils.mjs (98%)
create mode 100644 src/utils/mixins.mjs
create mode 100644 src/voice/VoiceStateCache.mjs
create mode 100644 src/voice/VoiceStateResolver.mjs
create mode 100644 src/voice/gateway/GatewayHandler.mjs
create mode 100644 src/voice/gateway/GuildSync.mjs
create mode 100644 src/voice/gateway/RejoinManager.mjs
create mode 100644 src/voice/gateway/VoiceStateRouting.mjs
create mode 100644 src/voice/gateway/index.mjs
diff --git a/.gitignore b/.gitignore
index 9929f2f..3e0efe9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,9 @@
-node_modules/
-storage/data
config.json
-settings.json
-remix-settings.json
-test_data/
-*.code-workspace
-.idea/
+.env
+storage/stats-cache.json
+storage/locales/user/
+*.log
+logs/
+.DS_Store
+Thumbs.db
+.idea
\ No newline at end of file
diff --git a/README.md b/README.md
index 1ce0f91..167712e 100644
--- a/README.md
+++ b/README.md
@@ -42,6 +42,7 @@
- [Dashboard Setup (Optional)](#-dashboard-setup-optional)
- [Configuration Reference](#-configuration-reference)
- [Project Architecture](#-project-architecture)
+- [The Layered Codebase](#-the-layered-codebase)
- [Localization](#-localization)
- [Scripts](#-npm-scripts)
- [Credits](#-credits--license)
@@ -54,6 +55,37 @@ Remix is a free and open-source music bot for [Fluxer](https://fluxer.app), buil
We believe music features shouldn't be locked behind paywalls — **all commands on Remix are 100% free and always will be.**
+### Fluxer.js 3.0
+
+Remix runs on **`@fluxerjs/core` / `@fluxerjs/util` / `@fluxerjs/voice` 3.0.0** plus **`@fluxerjs/sharding` 3.0.0** (see the [changelog](https://fluxer.js.org/changelog/)). The v3 DX overhaul required only five code-level changes in this codebase — everything else (event names, gateway opcodes, permission flags, the voice/LiveKit API, `EmbedBuilder`, message `reply`/`edit`/`react`, the raw `VOICE_STATE_UPDATE` / `VoiceStatesSync` payloads this bot tracks) is unchanged between 2.2 and 3.0:
+
+1. `package.json` — the three `@fluxerjs/*` ranges moved from `^2.2.0` to `^3.0.0` (a `^2.2.0` range will not install 3.0).
+2. `src/core/Bot.mjs` — the `Client` `presence` option now uses the normalized v3 shape (`customStatus`/`emojiName`/`emojiId`) instead of the 2.2 wire format (`custom_status`); the deprecated no-op `suppressIntentWarning` option was dropped.
+3. `src/voice/gateway/GatewayHandler.mjs` — the presence-rotation sender wraps its `client.ws` access in a try/catch, because 3.0 exposes `client.ws` as a getter that throws when the gateway is not connected (2.2 exposed a plain optional). The rotation payload itself stays in wire format because it sends opcode 3 straight to the shard.
+4. `src/ui/MessageHandler.mjs` — `joinChannel()` checks `channel.isGuild?.()` first (the new ChannelType-based guard) and keeps the legacy `"guildId" in channel` check as a fallback for stub objects.
+5. `src/utils/ShardingUtils.mjs` (new) — 3.0 removed the WebSocketManager's `shards` Map property in favour of `getShards()`/`getShard()` methods, which had silently disabled the bot's raw-socket listeners (they no-op'd behind their existing guards). All five readers — Bot.mjs's WS error handlers, GatewayHandler's raw listener and presence sender, LavalinkManager's payload routing and raw listener — now go through version-agnostic helpers that also make them shard-aware (see below).
+
+Two 3.0 library-level notes that need no code change here: the WS manager no longer emits `shardCreate` (the bot's 5-second handler re-arm loop covers re-attachment), and `Guild.description` was removed from the core structures (the dashboard serializer already null-guards it, so server descriptions simply render empty). Passing `intents` or `suppressIntentWarning` inside `config["fluxer.js"]` is still accepted — both are documented deprecated no-ops in 3.0.
+
+### Sharding (optional)
+
+`@fluxerjs/sharding` 3.0.0 (beta) is wired in as an **opt-in** layer — the default single-process boot (`npm start` / `node index.mjs`) is byte-for-byte unchanged, and none of the sharding code paths activate unless the process was actually forked by the manager (it sets `FLUXER_SHARD_IDS` *and* provides an IPC channel; manually exporting the variables does nothing).
+
+- **Supervisor:** `node shard.mjs` (or `npm run shard`) forks one child per shard slice, each running the ordinary `index.mjs` boot. The manager owns the shared per-IP IDENTIFY budget so children can never collectively exceed the gateway limit, respawns dead children, and exposes `broadcastEval` / `fetchClientValues` / `respawnAll`.
+- **Child side:** `src/core/Bot.mjs` attaches the library's `ShardClientUtil` before `login()` (it applies the shard slice to the client options) and calls `notifyReady()` after login so the supervisor's spawn promise resolves. A failed attach under a manager is fatal by design — without its slice the child would identify as shard 0 like every other child and thrash the gateway sessions.
+- **Guild→shard routing:** opcode-4 voice payloads from LavalinkManager now target `shardIdForGuildId(guildId)` instead of hardcoded shard 0, presence updates fan out to every gateway shard in the process, and raw-socket listeners attach to *all* local shard sockets. Unsharded, every one of these degrades to exactly the previous shard-0 behavior.
+
+Configuration (config.json, all optional — defaults shown):
+
+```json
+"sharding": { "totalShards": 1, "shardsPerProcess": 1, "respawn": true,
+ "spawnTimeout": 30000, "spawnDelay": 5000 }
+```
+
+`FLUXER_TOTAL_SHARDS` / `FLUXER_SHARDS_PER_PROCESS` env vars override the config (useful in Docker, where you switch the container command to `node shard.mjs`). Prefer an explicit `totalShards` — Fluxer's `/gateway/bot` always reports `shards: 1`, so there is no reliable `"auto"`.
+
+Beta caveats worth knowing: DMs and guild-less events only reach shard 0 (library limitation); each child opens its own MySQL/Redis/Lavalink connections and its own dashboard RPC subscription, so the dashboard is currently single-process-first — guilds on other shards won't be reachable from it, and concurrent `storage/stats.json` writes across children can race. The stock `node index.mjs` deployment has none of these issues.
+
---
## How Audio Playback Works
@@ -67,7 +99,7 @@ Understanding the pipeline helps when debugging or contributing:
├─ /v4/loadstream → magic-byte sniffing:
│ • WebM (1A45DFA3) → passthrough to LiveKit
│ • OggS → OggDemuxer → WebMOpusMuxer (remux, no re-encode)
- │ • raw PCM → OpusEncoder (opusscript / @discordjs/opus)
+ │ • raw PCM → OpusEncoder (opusscript)
│ → WebMOpusMuxer → LiveKit
└─ conn.play() → @fluxerjs/voice LiveKit connection (bot publishes audio
as a LiveKit participant)
@@ -393,79 +425,175 @@ Key configuration options in `config.json`:
```
fluxer/
-├── index.mjs # Entry point — Remix class, boot sequence, alone-check,
-│ # presence rotation, error handling, graceful shutdown
+├── index.mjs # Entry point — creates the Remix instance, process-level
+│ # error guards, and signal-based graceful shutdown
+├── shard.mjs # OPTIONAL sharding supervisor (@fluxerjs/sharding) — forks
+│ # one child process per shard slice, each running index.mjs
├── config_example.json # Configuration template
├── package.json
-├── commands/ # 37 command modules (one file per command)
-│ ├── play.mjs # Play a track or playlist (Last.fm categories, providers)
-│ ├── player.mjs # Interactive emoji control panel with live progress
-│ ├── settings.mjs # Per-guild settings management (+ prefix/247 shortcuts)
-│ ├── lyrics.mjs # Synced lyrics from NodeLink
-│ ├── filter.mjs # Audio filter controls
-│ ├── radio.mjs # Radio station management
-│ ├── debug.mjs # Voice connection debugger (owner only)
-│ ├── lastfm.mjs # Last.fm linking, scrobbling, profiles, leaderboards
-│ ├── trackopt.mjs # Per-track start/end time options (set/get/remove/list)
-│ └── ... # All other commands
-├── src/
-│ ├── CommandHandler.mjs # Command framework — builder, options, requirements,
-│ │ # cooldowns, prefix manager, loader
-│ ├── MessageHandler.mjs # Replies/embeds, reaction observers, pagination, help
-│ ├── PlayerManager.mjs # Player lifecycle, VC resolution & permission checks,
-│ │ # dashboard broadcasts, Last.fm scrobble wiring
-│ ├── Player.mjs # Core per-channel player — queue, playback, filters,
-│ │ # search sessions, autoplay, error circuit breaker
-│ ├── FluxerAudioBridge.mjs # Audio engine — NodeLink REST streams → sniff/remux/
-│ │ # encode → LiveKit publishing
-│ ├── LavalinkManager.mjs # lavalink-client wrapper (NodeLink mode) — search,
-│ │ # voice payload caching, node readiness
-│ ├── GatewayHandler.mjs # Raw WS events, voice-state routing, guild lifecycle,
-│ │ # 24/7 rejoin & rejoin retries
-│ ├── LastFmManager.mjs # Last.fm API client — auth, scrobbling, user data,
-│ │ # MySQL persistence (lastfm_users / lastfm_stats)
-│ ├── FluxerListManager.mjs # FluxerList voters API client (5-min TTL cache)
-│ ├── TrackOptionsManager.mjs # Per-user per-track start/end times (MySQL + LRU cache)
-│ ├── Settings.mjs # RemoteSettingsManager — MySQL-backed per-guild settings
-│ │ # with debounced JSON_SET writes
-│ ├── Utils.mjs # Shared utilities (IDs, durations, markdown, progress bar)
-│ ├── probe.mjs # ffprobe wrapper for audio stream info (radio metadata)
-│ ├── constants/
-│ │ ├── Logger.mjs # Structured logger with per-category control
-│ │ ├── Locale.mjs # i18n translation engine
-│ │ ├── Helpers247.mjs # 24/7 mode helpers
-│ │ ├── UI.mjs # Emoji + UI constants
-│ │ ├── providers.mjs # 45+ audio source provider definitions
-│ │ ├── VoiceStateCache.mjs # Dual LRU voice-state caches (humans / bots)
-│ │ ├── VoiceStateResolver.mjs # Voice-state normalization + humans-in-channel check
-│ │ └── audio/
-│ │ └── WebMOpusMuxer.mjs # Streaming EBML/Matroska muxer (Opus → WebM for LiveKit)
-│ └── dashboard/
-│ ├── Dashboard.mjs # Dashboard backend — Redis RPC, player/user serializers,
-│ │ # remote-control actions with authorization checks
-│ ├── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers
-│ └── RedisHandler.mjs # Redis pub/sub RPC transport with reconnect handling
-├── settings/
-│ ├── Settings.mjs # Re-export of src/Settings.mjs classes
-│ ├── migrate.mjs # One-shot settings table clone/repair tool
-│ ├── runnables.mjs # Setting validators (prefix, pfp, stay_247)
-│ └── README.md # Settings system documentation
+├── commands/ # 37 command entry files (one per command); the three
+│ │ # largest (lastfm, settings, debug) are split into action-family
+│ │ # modules inside commands// subdirectories
+│ ├── lastfm/ # lastfm action families (account, playback, listening,
+│ │ # whoknows, info, tags, discovery, help, shared)
+│ ├── settings/ # settings helpers (utils, channels247, setters)
+│ └── debug/ # debug helpers (consts, gateway, rejoin, voiceDiagnostic)
+├── settings/ # Settings system entry points (re-export, migrate, validators)
+├── storage/ # Runtime data: defaults, modules.json, locales
├── docker/ # Docker self-hosting (Dockerfile, compose, entrypoint,
│ # config templates, .env.example)
-└── storage/
- ├── defaults.json # Default per-guild settings template
- ├── modules.json # Plugin module registry (empty by default)
- ├── stats.json # Static counters
- └── locales/bot/ # Translation files
- ├── en.json
- ├── ar-SA.json
- ├── de-DE.json
- ├── ckb.json
- └── pt-BR.json
+└── src/
+ ├── core/ # Bot composition
+ │ ├── Bot.mjs # Remix class — boot sequence, service wiring, alone-check,
+ │ │ # presence rotation, WebSocket error guards
+ │ ├── BotVoiceMixin.mjs # Voice-channel resolution, 24/7 player spawning with
+ │ │ # announcements, programmatic leave, shared servers
+ │ ├── Logger.mjs # Structured logger with per-category control
+ │ └── Locale.mjs # i18n translation engine
+ ├── commands/ # Command framework layer
+ │ ├── index.mjs # Public surface (re-exports)
+ │ ├── CommandBuilder.mjs # Fluent builder + permission requirements
+ │ ├── Option.mjs # Typed options + flags with validation
+ │ ├── CommandHandler.mjs # Dispatcher: parsing, cooldowns, permission checks
+ │ ├── CommandLoader.mjs # Dynamic command loading + run-handler binding
+ │ ├── HelpHandler.mjs # Text help generation (usage/aliases/options)
+ │ └── PrefixManager.mjs # Per-guild prefix resolution
+ ├── ui/ # Message/embed layer
+ │ ├── index.mjs # Public surface (re-exports)
+ │ ├── MessageHandler.mjs # Reply/send/edit embeds, reaction + message observers,
+ │ │ # permission checks, pagination entry
+ │ ├── Wrappers.mjs # Message & Channel wrappers
+ │ ├── Paginators.mjs # PageBuilder, RichPaginator (tabbed), QueuePaginator
+ │ ├── HelpCommand.mjs # Rich tabbed help command (Home/Music/Utilities/Support)
+ │ ├── Permissions.mjs # Required/critical/optional bot permission catalog
+ │ └── Embeds.mjs # Global embed color + message-shape helpers
+ ├── voice/ # Gateway & voice-state layer
+ │ ├── VoiceStateCache.mjs # Dual LRU voice-state caches (humans / bots)
+ │ ├── VoiceStateResolver.mjs # Voice-state normalization + humans-in-channel check
+ │ └── gateway/
+ │ ├── index.mjs # Public surface
+ │ ├── GatewayHandler.mjs # Raw WS dispatch, presence rotation, boot recovery
+ │ ├── VoiceStateRouting.mjs # Voice-state update handling, inactivity triggers
+ │ ├── GuildSync.mjs # Guild seeding (cache + REST), guild delete
+ │ └── RejoinManager.mjs # 24/7 rejoin scheduling with retries
+ ├── music/ # Player + audio engine layer
+ │ ├── PlayerManager.mjs # Player lifecycle & registry, getPlayer/initPlayer
+ │ ├── PlayerEventsMixin.mjs # Per-player event wiring, scrobbles, broadcasts
+ │ ├── PlayerLifecycleMixin.mjs# Voice checks, prompts, joins, leaves
+ │ ├── LavalinkManager.mjs # lavalink-client wrapper (NodeLink mode)
+ │ ├── probe.mjs # ffprobe wrapper for radio stream metadata
+ │ ├── providers.mjs # 45+ audio source provider definitions
+ │ ├── player/
+ │ │ ├── index.mjs # Public surface (default export: Player)
+ │ │ ├── Player.mjs # Core state machine: join/leave/destroy, controls, 24/7
+ │ │ ├── Queue.mjs # Queue data structure with loop modes + events
+ │ │ ├── PlaybackMixin.mjs # playNext pipeline, track-end timers, lyrics
+ │ │ ├── SearchMixin.mjs # Lavalink search, fallbacks, radio/external builders
+ │ │ └── DisplayMixin.mjs # Now-playing, queue listing, announcements
+ │ └── audio/
+ │ ├── index.mjs # Public surface
+ │ ├── FluxerAudioBridge.mjs # NodeLink streams → LiveKit publishing core
+ │ ├── StreamPipeline.mjs # Magic-byte sniffing, remux, Opus encode
+ │ ├── HttpStreams.mjs # Redirect-following HTTP JSON/stream helpers
+ │ └── WebMOpusMuxer.mjs # Streaming EBML/Matroska muxer (Opus → WebM)
+ ├── services/ # Integrations
+ │ ├── FluxerListManager.mjs # FluxerList voters API client (TTL cache)
+ │ ├── TrackOptionsManager.mjs # Per-user per-track start/end times (MySQL + LRU)
+ │ └── lastfm/
+ │ ├── index.mjs # Public surface
+ │ ├── LastFmManager.mjs # Base: config, MySQL pool, shared helpers
+ │ ├── UserStoreMixin.mjs # Linking, sessions, scrobble opt-ins
+ │ ├── ScrobblingMixin.mjs # Scrobble + now-playing
+ │ ├── TrackQueriesMixin.mjs # Track/artist/album/tag/geo/chart queries
+ │ ├── UserQueriesMixin.mjs # User tops, charts, playlists, play categories
+ │ ├── ServerStatsMixin.mjs # Whoknows, crowns, leaderboards, affinity
+ │ ├── constants.mjs # Signed API-call plumbing
+ │ └── urlUtils.mjs # lastfm:// URL parsing
+ ├── db/ # Persistence
+ │ ├── Settings.mjs # SettingsManager / ServerSettings / RemoteSettingsManager
+ │ │ # (MySQL-backed, debounced JSON_SET writes)
+ │ └── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers
+ ├── utils/ # Cross-layer primitives (leaf layer)
+ │ ├── mixins.mjs # applyMixins — god-class splitting helper
+ │ ├── ShardingUtils.mjs # Shard-aware gateway helpers (2.2/3.0 compatible,
+ │ │ # guild→shard routing, local shard enumeration)
+ │ ├── Utils.mjs # Formatting, validation, ID cleaning
+ │ ├── API.mjs # REST call helpers (status/error wrapping)
+ │ ├── UI.mjs # Shared UI constants (colors)
+ │ └── Helpers247.mjs # 24/7 channel-mode helpers
+ └── dashboard/ # Dashboard backend
+ ├── index.mjs # Public surface
+ ├── Dashboard.mjs # Redis RPC routing, player/user broadcasts
+ ├── RpcHandlersMixin.mjs# Request handlers + authorization checks
+ ├── Serializers.mjs # Channel/user/player/command serializers (statics)
+ └── RedisHandler.mjs # Redis pub/sub RPC transport with reconnect handling
```
---
+## The Layered Codebase
+
+The rewrite organises the codebase into strict layers with one-way dependencies
+(no layer reaches *down* past another):
+
+```
+index.mjs
+ └── core/ ──────────────► composition root: wires every layer together
+ ├── commands/ ─────► command framework (parsing, cooldowns, help)
+ │ └── ui/ ─────► message/embed primitives used by the framework
+ ├── ui/ ──── message wrappers, paginators, permissions
+ ├── voice/ ──── gateway events, voice-state caches, 24/7 rejoin
+ ├── music/ ──── players, queue, audio engine, Lavalink client
+ ├── services/ ──── Last.fm, FluxerList, track options
+ ├── db/ ──── MySQL settings + dashboard database pool
+ └── dashboard/ ──── Redis-RPC backend
+```
+
+**God classes were eliminated.** The five largest modules (Player, PlayerManager,
+GatewayHandler, FluxerAudioBridge, LastFmManager, Dashboard) are each split into a
+small base class plus **concern mixins** — one file per responsibility, applied onto
+the class at load time via `src/utils/mixins.mjs` (`applyMixins`). All methods keep
+the same names, so callers (including your own command files and modules) are
+unaffected.
+
+**Big commands are grouped the same way.** The three commands that outgrew a
+single file (`lastfm` 2.5k lines, `settings` 705, `debug` 669) keep their entry
+file at `commands/.mjs` (same path the loader, `%reload` and help system
+reference) and move their implementation into `commands//` — one module per
+action family, dispatched by the entry's `run()` via per-module action sets:
+
+```js
+// commands/lastfm.mjs (entry) — dispatch
+if (ACCOUNT_ACTIONS.has(action))
+ return runAccountActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action);
+```
+
+The loader only reads top-level `*.mjs` files, so the subdirectories are invisible
+to command discovery; case bodies and helpers were moved verbatim (verified by
+per-command runtime parity harnesses under `scripts/`), and every entry file keeps
+its original exports (`playLastFmCategory` is still importable from
+`commands/lastfm.mjs`). `commands/player.mjs` intentionally stays single-file: it
+is one cohesive interactive UI flow (a single 500-line `run()` closure) with no
+seams that could be split without rewriting behavior.
+
+**Public surfaces are barrels.** Each layer folder has an `index.mjs` that
+re-exports its public API, so imports stay short and implementation files can move
+without touching consumers:
+
+```js
+import { CommandBuilder } from "../src/commands/index.mjs";
+import { Message, getGlobalColor } from "../src/ui/index.mjs";
+import Player from "../src/music/player/index.mjs";
+import { LastFmManager } from "../src/services/lastfm/index.mjs";
+```
+
+**Compatibility is drop-in:** `config.json` keys, the MySQL schema, the Redis RPC
+protocol, command names/aliases, locale files, and the Docker entrypoint
+(`node index.mjs` at the repository root) are all unchanged from the previous
+single-layer layout.
+
+---
+
## Localization
Remix supports multiple languages out of the box. The locale system loads JSON translation files from `storage/locales/bot/` and serves the appropriate language based on each guild's `locale` setting.
@@ -479,6 +607,7 @@ Currently supported languages:
| `de-DE` | German |
| `ckb` | Kurdish (Sorani) |
| `pt-BR` | Brazilian Portuguese |
+| `tr` | Turkish |
To add a new language, place a JSON file in `storage/locales/bot/` following the same key structure as `en.json`, then set the locale per guild with `%settings set locale `.
@@ -488,7 +617,8 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the
| Script | Command | Description |
| :--- | :--- | :--- |
-| `npm start` | `node index.mjs` | Start the bot |
+| `npm start` | `node index.mjs` | Start the bot (single process — default) |
+| `npm run shard` | `node shard.mjs` | Start under the sharding supervisor (optional) |
| `npm run dev` | `node --inspect index.mjs --trace-warnings` | Start with Node.js inspector |
| `npm run migrate` | `node settings/migrate.mjs` | Clone/repair the remote settings table |
@@ -512,4 +642,3 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the
© 2026 Remix. Code licensed under the MIT License.
The Remix name, logo, and branding are proprietary and may not be reused.
-
diff --git a/commands/autoplay.mjs b/commands/autoplay.mjs
index b2cd1e9..4f383c9 100644
--- a/commands/autoplay.mjs
+++ b/commands/autoplay.mjs
@@ -3,10 +3,10 @@
* @description Toggle autoplay mode — keeps the music going forever:
*/
-import { CommandBuilder } from "../src/CommandHandler.mjs";
+import { CommandBuilder } from "../src/commands/index.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
-import { getGlobalColor } from "../src/MessageHandler.mjs";
-import { logger } from "../src/constants/Logger.mjs";
+import { getGlobalColor } from "../src/ui/index.mjs";
+import { logger } from "../src/core/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the autoplay command. */
export const command = new CommandBuilder()
diff --git a/commands/clear.mjs b/commands/clear.mjs
index a41870d..45a8766 100644
--- a/commands/clear.mjs
+++ b/commands/clear.mjs
@@ -3,9 +3,9 @@
* @description Remove all songs from the playback queue.
*/
-import { CommandBuilder } from "../src/CommandHandler.mjs";
+import { CommandBuilder } from "../src/commands/index.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
-import { getGlobalColor } from "../src/MessageHandler.mjs";
+import { getGlobalColor } from "../src/ui/index.mjs";
/**
* @type {CommandBuilder}
diff --git a/commands/debug.mjs b/commands/debug.mjs
index d53fa79..3897410 100644
--- a/commands/debug.mjs
+++ b/commands/debug.mjs
@@ -1,340 +1,16 @@
/**
* @module commands/debug
- * @description Owner-only debug command for voice diagnostics, ghost connection detection, and forced rejoin.
+ * @description Owner-only debug command for voice diagnostics, ghost connection
+ * detection, and forced rejoin. The implementations live in commands/debug/
+ * (gateway, rejoin, voiceDiagnostic); the builder and run() dispatch stay here.
*/
-import { CommandBuilder } from "../src/CommandHandler.mjs";
+import { CommandBuilder } from "../src/commands/index.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
-import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs";
-import { logger } from "../src/constants/Logger.mjs";
-import { getVoiceManager } from "@fluxerjs/voice";
-import { ERROR_COLOR, WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
-
-const REJOIN_DELAY_MS = 2_000;
-const INTENTIONAL_LEAVE_TTL = 30_000;
-const MAX_DESC = 4096;
-
-/**
- * Get a human-readable label for a voice room's connection state.
- * @private
- * @param {object|null} room - The voice room object.
- * @returns {string} Connection state label.
- */
-function roomStateLabel(room) {
- if (!room) return "none";
- const cs = room.connectionState;
- if (cs === 0 || cs === "CONN_DISCONNECTED") return "disconnected(0)";
- if (cs === 1 || cs === "CONN_CONNECTED") return "connected(1)";
- if (cs === 2) return room.isConnected ? "connected(2)" : "reconnecting(2)";
- if (cs === "CONN_RECONNECTING") return "reconnecting";
- if (cs === 3) return "reconnecting(3)";
- if (cs === 4) return "signal_reconnecting(4)";
- if (typeof cs === "string") return cs;
- return String(cs);
-}
-
-/**
- * Check if a player has a ghost connection (appears in voice but WebSocket is dead).
- * @private
- * @param {object} player - The player instance.
- * @returns {boolean} True if the player has a ghost connection.
- */
-function isGhostConnection(player) {
- const conn = player.connection;
- if (!conn) return false;
- if (player._destroyed || player.leaving || player._isJoining) return false;
-
- const room = conn.room;
- if (!room) {
- return !conn._destroyed;
- }
-
- if (!room.isConnected) return true;
-
- const cs = room.connectionState;
- if (cs === 0 || cs === "CONN_DISCONNECTED") return true;
- if (cs === "CONN_RECONNECTING" || cs === 3 || cs === 4) return true;
-
- return false;
-}
-
-/**
- * Get the bot's voice channel state from the Discord gateway cache.
- * @private
- * @param {object} client - The Discord client instance.
- * @param {string} guildId - The guild ID to check.
- * @returns {{ userId: string, channelId: string }|null} Bot's voice state or null.
- */
-function getBotGatewayVoiceState(client, guildId) {
- const botId = client.user?.id;
- if (!botId || !guildId) return null;
-
- try {
- const vm = getVoiceManager(client);
- if (vm?.voiceStates) {
- const cleanGuild = cleanId(guildId);
- const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
- if (guildVoiceMap && typeof guildVoiceMap.get === "function") {
- const channelId = guildVoiceMap.get(botId);
- if (channelId) return { userId: botId, channelId: cleanId(channelId) };
- }
- }
- } catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (VoiceManager):", e?.message); }
-
- try {
- const cleanGuild = cleanId(guildId);
- const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
- const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
- if (!voiceStates) return null;
-
- const entries = Array.isArray(voiceStates)
- ? voiceStates
- : typeof voiceStates.values === "function"
- ? [...voiceStates.values()]
- : Object.entries(voiceStates).map(([uid, val]) => {
- if (typeof val === "string") return { user_id: uid, channel_id: val };
- const obj = typeof val === "object" && val !== null ? val : {};
- return { user_id: uid, channel_id: obj.channelId ?? obj.channel_id ?? null, ...obj };
- });
-
- for (const state of entries) {
- const uid = state?.user_id ?? state?.userId ?? state?.id;
- if (uid === botId) {
- const chId = state?.channel_id ?? state?.channelId ?? null;
- if (chId) return { userId: botId, channelId: cleanId(chId) };
- }
- }
- } catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (guild cache):", e?.message); }
-
- return null;
-}
-
-/**
- * Check if the gateway voice state is stale (mismatches the player's channel).
- * @private
- * @param {object} client - The Discord client instance.
- * @param {object} player - The player instance.
- * @returns {boolean} True if the gateway presence is stale.
- */
-function isStaleGatewayPresence(client, player) {
- const guildId = player._guildId ?? player._resolveGuildId?.();
- if (!guildId) return false;
-
- const gatewayState = getBotGatewayVoiceState(client, guildId);
- if (!gatewayState) return false;
-
- const playerChannel = cleanId(player._channelId ?? player._home247Channel);
- const gatewayChannel = gatewayState.channelId;
-
- return !playerChannel || playerChannel !== gatewayChannel;
-}
-
-/**
- * Build a human-readable label for a player (guild name / #channel name).
- * @private
- * @param {object} client - The Discord client instance.
- * @param {string} channelId - The voice channel ID.
- * @param {object} player - The player instance.
- * @returns {string} Formatted label string.
- */
-function buildPlayerLabel(client, channelId, player) {
- const channel = client.channels.get(channelId);
- const gId = player._guildId ?? channel?.guildId;
- const guild = gId ? client.guilds.get(cleanId(gId)) : null;
- return `${guild?.name ?? "unknown"} / #${channel?.name ?? channelId}`;
-}
-
-/**
- * Force a player to leave and rejoin, restoring queue and playback state.
- * @private
- * @async
- * @param {object} ctx - The bot (Remix) instance context.
- * @param {object} player - The player to rejoin.
- * @returns {Promise