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:
NoLogicAlan committed 2026-09-09 02:04:33 +03:00
1 parent 0f085a6ae4
commit 253d11cd57
150 files changed
+19935 -16894

No files matched your search

+197 -68
View File
@@ -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/<name>/ 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/<name>.mjs` (same path the loader, `%reload` and help system
reference) and move their implementation into `commands/<name>/` — 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 <code>`.
@@ -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
&copy; 2026 Remix. Code licensed under the <a href="LICENSE">MIT License</a>.<br>
<em>The Remix name, logo, and branding are proprietary and may not be reused.</em>
</p>