no comment still working on it

This commit is contained in:
NoLogicAlan committed 2026-08-28 23:51:20 +03:00
1 parent cea0014e18
commit e11fca151c
87 files changed
+5576 -10048

No files matched your search

-10
View File
@@ -3,16 +3,6 @@ storage/data
config.json
settings.json
remix-settings.json
cmdUsage.md
bot.js
bin/
test_data/
*.code-workspace
*old.js
.ytcache/
.yt_auth.json
yt_auth.json
visitor_data.json
.moonlink/
storage/recovery.json
.idea/
+140 -138
View File
@@ -18,10 +18,10 @@
<p align="center">
<img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License">
<img src="https://img.shields.io/badge/Node.js-%3E%3D22.0.0-339933.svg" alt="Node.js">
<img src="https://img.shields.io/badge/Node.js-%3E%3D22.13.0-339933.svg" alt="Node.js">
<img src="https://img.shields.io/badge/ESM-Modules-yellow.svg" alt="ESM">
<img src="https://img.shields.io/badge/Audio-moonlink.js-orange.svg" alt="moonlink.js">
<img src="https://img.shields.io/badge/Voice-revoice.js-9b59b6.svg" alt="revoice.js">
<img src="https://img.shields.io/badge/Audio-lavalink--client%20%2B%20NodeLink-orange.svg" alt="lavalink-client">
<img src="https://img.shields.io/badge/Voice-%40fluxerjs%2Fvoice%20(LiveKit)-9b59b6.svg" alt="@fluxerjs/voice">
<img src="https://img.shields.io/badge/Database-MySQL-4479A1.svg" alt="MySQL">
<img src="https://img.shields.io/badge/Maintained%3F-Yes-green.svg" alt="Maintained">
</p>
@@ -31,6 +31,7 @@
## Table of Contents
- [About The Project](#-about-the-project)
- [How Audio Playback Works](#-how-audio-playback-works)
- [Features](#-features)
- [Getting Started (Users)](#-getting-started-users)
- [Commands](#-commands)
@@ -49,32 +50,59 @@
## About The Project
Remix is a free and open-source music bot for [Fluxer](https://fluxer.app), built with [`@fluxerjs/core`](https://github.com/fluxerjs/core) and powered by [`moonlink.js`](https://github.com/ShadowLp174/moonlink.js) for seamless, high-quality audio streaming. It uses [`revoice.js`](https://www.npmjs.com/package/revoice.js) for LiveKit voice connections and audio playback, and [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) for native voice channel integration alongside the Moonlink Lavalink proxy.
Remix is a free and open-source music bot for [Fluxer](https://fluxer.app), built with [`@fluxerjs/core`](https://github.com/fluxerjs/core) for the Fluxer API and [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) for LiveKit voice connections. Track search and streaming are handled by [`lavalink-client`](https://www.npmjs.com/package/lavalink-client) talking to a [NodeLink](https://github.com/PerformanC/NodeLink) audio node (Lavalink-compatible), and the bot publishes Opus audio to LiveKit as a participant — with a custom WebM/Opus pipeline (zero-re-encode passthrough and remux where possible).
We believe music features shouldn't be locked behind paywalls — **all commands on Remix are 100% free and always will be.**
---
## How Audio Playback Works
Understanding the pipeline helps when debugging or contributing:
```
%play → LavalinkManager.search() ──► NodeLink (track resolution only)
→ Player queue → FluxerAudioBridge.play(voiceConnection, track)
├─ /v4/trackstream → direct WebM/Opus passthrough (no re-encode)
├─ /v4/loadstream → magic-byte sniffing:
│ • WebM (1A45DFA3) → passthrough to LiveKit
│ • OggS → OggDemuxer → WebMOpusMuxer (remux, no re-encode)
│ • raw PCM → OpusEncoder (opusscript / @discordjs/opus)
│ → WebMOpusMuxer → LiveKit
└─ conn.play() → @fluxerjs/voice LiveKit connection (bot publishes audio
as a LiveKit participant)
```
A few things worth knowing:
- **No Lavalink players are created.** NodeLink is used for search and its REST stream/lyrics endpoints (`/v4/loadstream`, `/v4/trackstream`, `/v4/loadlyrics`); playback itself is pure LiveKit publishing.
- **Seek / pause / resume** work by stopping the current stream and re-requesting it at an offset from NodeLink.
- **Filters** (bassboost, nightcore, etc.) are applied server-side by NodeLink, so they take effect on the next track that starts.
- **Volume** is applied client-side by the LiveKit connection (1–200).
- Radio metadata (StreamTitle) is read with **ffprobe** (`ffprobe-static`).
---
## Features
- **High-quality audio playback** via moonlink.js (Lavalink proxy), revoice.js (LiveKit voice + MediaPlayer), and `@fluxerjs/voice`
- **Multi-source search** — YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and direct URL support
- **24/7 mode** — keep the bot in a voice channel permanently, with auto-recovery on restart
- **Session recovery** — active players and queues survive bot restarts and crash recovery
- **Interactive emoji player** — reaction-based control panel with play, pause, skip, volume, shuffle, and more
- **Lyrics** — fetch synced lyrics via NodeLink
- **High-quality audio playback** — NodeLink streaming with a zero-re-encode WebM/Opus pipeline, published over LiveKit
- **Multi-source search** — YouTube, YT Music, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bandcamp and 40+ more provider prefixes, plus direct URLs
- **24/7 mode** — keep the bot in a voice channel permanently, with staggered auto-rejoin on boot and rejoin retries on connection loss
- **Interactive emoji player** — reaction-based control panel with live progress, lyrics viewer, and a filter submenu
- **Lyrics** — synced lyrics via NodeLink
- **Radio stations** — built-in support for custom radio streams with keyword-based search
- **Last.fm integration** — auto-scrobble songs, play loved/top/recent tracks, love/unlove tracks, view top artists, and view your Last.fm profile
- **Last.fm integration** — account linking, scrobbling, now-playing, play loved/top/recent/albums, whoknows, crowns, compare, leaderboards, and profiles
- **Autoplay** — automatically play similar tracks when the queue ends (powered by Last.fm)
- **Seek** — jump to a specific position in the current track
- **Track options** — set custom start/end times per track (like old iTunes), great for album compilations and hidden tracks
- **Track options** — set custom start/end times per track, great for album compilations and hidden tracks
- **Queue move** — reorder tracks by moving them to a different position
- **Server settings** — per-guild configuration for prefix, volume, locale, 24/7 channels, and more
- **Web dashboard** — optional browser-based control panel with Redis-backed sessions and Fluxer OAuth2 login
- **Multi-language support** — available in English, Arabic, German, Kurdish (Sorani), and Brazilian Portuguese
- **Audio filters** — bassboost, speed, nightcore and more (applied server-side by NodeLink)
- **Server settings** — per-guild configuration (prefix, volume, locale, 24/7 channels, …) stored in MySQL
- **Dashboard backend** — optional Redis-RPC backend that an external web frontend uses to monitor players and control playback remotely
- **Multi-language support** — English, Arabic, German, Kurdish (Sorani), and Brazilian Portuguese
- **Configurable logging** — granular control over which log categories appear in the console
- **Graceful shutdown** — saves active session state on SIGINT/SIGTERM for seamless reboot recovery
- **Module system** — pluggable module architecture for extending bot functionality
- **Graceful shutdown** — destroys players and closes MySQL/Redis/NodeLink sessions cleanly on SIGINT/SIGTERM/SIGUSR2
- **Module system** — pluggable module architecture for extending bot functionality (`storage/modules.json`)
---
@@ -132,14 +160,13 @@ Below is the complete list of Remix's commands. The default prefix is `%`.
| `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` |
| `support` | Get an invite to the support server | `%support` | `server` |
| `lastfm` | Link Last.fm, toggle scrobbling, view profile, love/unlove tracks, top artists, play tracks, leaderboard | `%lastfm link` / `%lastfm love` / `%lastfm artists` / `%lastfm lb` | `lf`, `lfm` |
| `vote` | Check FluxerList voters for the bot | `%vote` | |
| `reload` | Reload commands or modules at runtime (owner) | `%reload` | |
| `servers` | List servers the bot is in (owner) | `%servers` | |
| `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | |
| `debug` | Debug voice connections and player state (owner) | `%debug voice` | |
| `test` | Show voice channel user counts (owner) | `%test` | |
---
## Self-Hosting The Bot
If you prefer to host Remix yourself, please note: **You must make it clear that your bot is an instance of Remix.** Change the bot's name and give credit in the bot's profile (e.g., *"Powered by [Remix](https://github.com/remix-bot/fluxer)"*).
@@ -152,13 +179,13 @@ The fastest way to self-host Remix is with Docker. Everything — the bot, MySQL
```bash
git clone https://github.com/remix-bot/fluxer.git
cd fluxer/docker
cp .env.example .env
cp config_example.json config.json
cp .env.example .env # optional — compose has working defaults
```
2. **Edit `.env`** — set your bot token and MySQL passwords.
2. **Edit `config.json`** — fill in your bot token, MySQL credentials (defaults match the compose MySQL service), NodeLink details (defaults match the compose NodeLink service), and your owner IDs. Spotify/Deezer/Apple Music credentials are configured on the **NodeLink side** (`nodelink.config.json`), not in the bot config.
3. **Edit `config.json`** — fill in your bot token, Fluxer OAuth2 credentials (if using the dashboard), and any other settings. The Docker config already points MySQL/Redis/NodeLink at the correct service hostnames.
3. **Edit `.env`** (optional) — MySQL passwords, host port mappings (`WEB_PORT`, `NODELINK_PORT`), and timezone.
4. **Start everything:**
```bash
@@ -170,30 +197,30 @@ The fastest way to self-host Remix is with Docker. Everything — the bot, MySQL
docker compose logs -f bot
```
That's it. The bot will start, connect to MySQL (auto-creates the settings table), connect to NodeLink, and log in to Fluxer.
That's it. The bot will start, connect to MySQL (Last.fm and track-options tables are auto-created), connect to NodeLink, and log in to Fluxer.
#### Docker file structure
```
docker/
├── Dockerfile # Multi-stage build (Node 22 + FFmpeg + tini)
├── docker-entrypoint.sh # Config validation on first boot
├── Dockerfile # Multi-stage build (Node 22 + tini, non-root user, healthcheck)
├── docker-entrypoint.sh # Writes config.json from CONFIG_JSON env var on first boot
├── docker-compose.yml # bot + MySQL + Redis + NodeLink
├── .env.example # Compose env template (MySQL creds, ports, TZ)
├── config_example.json # Docker-friendly config template
├── .env.example # Secrets template
├── nodelink.config.json # NodeLink audio node config
├── config.json # You create this (gitignored)
└── .env # You create this (gitignored)
├── .env # You create this (gitignored)
└── nodelink.config.json # NodeLink audio node config
```
#### Docker services
| Service | Container | Port | Purpose |
| :--- | :--- | :--- | :--- |
| `bot` | remix-bot | 8080 → 80 | The Remix bot + web dashboard |
| `mysql` | remix-mysql | — | Per-guild settings storage |
| `redis` | remix-redis | — | Dashboard sessions + pub/sub (optional) |
| `nodelink` | remix-nodelink | 3000 | Lavalink-compatible audio node |
| `bot` | remix-bot | `${WEB_PORT:-8080}` → 80 | The Remix bot (+ optional dashboard backend) |
| `mysql` | remix-mysql | — | Settings, Last.fm users, and track options storage |
| `redis` | remix-redis | — | Dashboard RPC pub/sub (optional) |
| `nodelink` | remix-nodelink | `${NODELINK_PORT:-3000}` | Lavalink-compatible audio node |
#### Useful Docker commands
@@ -234,11 +261,10 @@ The entrypoint will write it to `/app/config.json` on first boot if no config fi
#### Prerequisites
- **Node.js** >= 22.0.0 (required by moonlink.js v5)
- **Node.js** >= 22.13.0
- **MySQL** 8.0+ with JSON column support
- **[NodeLink](https://github.com/PerformanC/NodeLink)** instance (Lavalink proxy for audio)
- **FFmpeg** (installed automatically via `ffmpeg-static`)
- **Redis** (optional, required for the web dashboard)
- **[NodeLink](https://github.com/PerformanC/NodeLink)** instance (Lavalink-compatible audio node)
- **Redis** (optional — required only for the dashboard backend)
### Installation
@@ -262,8 +288,7 @@ The entrypoint will write it to `/app/config.json` on first boot if no config fi
- `mysql` — your MySQL connection details (host, port, user, password, database)
- `prefix` — the command prefix (default: `%`)
- `nodelink` — your NodeLink instance connection details
- `spotify` — (optional) Spotify API credentials for Spotify track support
- `geniusToken` — *(deprecated, unused)* was previously for lyrics; lyrics are now fetched via NodeLink
- `lastfm` — (optional) Last.fm API credentials for scrobbling/autoplay features
- `owners` — array of Fluxer user IDs with owner-only command access
4. **Set up the database:** *(See [Database Setup](#-database-setup) below)*
@@ -280,7 +305,7 @@ The entrypoint will write it to `/app/config.json` on first boot if no config fi
### Database Setup
Remix requires a MySQL database to store per-guild settings.
Remix requires a MySQL database to store per-guild settings and user data.
1. Create a dedicated database for Remix:
```sql
@@ -298,7 +323,7 @@ Remix requires a MySQL database to store per-guild settings.
}
```
3. Create the required table:
3. Create the required `settings` table:
```sql
CREATE TABLE `settings` (
`id` varchar(70) NOT NULL,
@@ -306,58 +331,39 @@ Remix requires a MySQL database to store per-guild settings.
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
```
4. Create the track options table (for the `%trackopt` command):
```sql
CREATE TABLE IF NOT EXISTS `track_options` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`user_id` VARCHAR(32) NOT NULL,
`track_identifier` VARCHAR(512) NOT NULL,
`track_title` VARCHAR(512) NOT NULL DEFAULT '',
`start_ms` INT UNSIGNED NOT NULL DEFAULT 0,
`end_ms` INT UNSIGNED NOT NULL DEFAULT 0,
`bot_id` VARCHAR(32) NOT NULL DEFAULT '',
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY `uq_user_track_bot` (`user_id`, `track_identifier`, `bot_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
This table is auto-created on startup if it doesn't exist, so manual creation is optional.
4. Everything else is **auto-created on startup** if missing:
- `track_options` — per-user per-track start/end times (`%trackopt`)
- `lastfm_users` — Last.fm session keys and scrobble opt-ins
- `lastfm_stats` — stored scrobble/link counts
5. *(Optional)* If migrating from the legacy settings system, run:
5. *(Optional)* If you need to clone or repair the settings table across bot IDs, run:
```bash
npm run migrate
```
### Dashboard Setup (Optional)
Remix includes a web dashboard for controlling the bot through a browser interface.
Remix ships the **backend half** of a web dashboard: a Redis-RPC service that an external frontend project talks to. There is no HTTP server or web UI in this repository.
1. Enable the dashboard in `config.json`:
1. Enable it in `config.json`:
```json
"dashboard": {
"enabled": true,
"redis": { "url": "redis://localhost:6379" },
"fluxer": {
"id": "your-fluxer-oauth2-app-id",
"secret": "your-fluxer-oauth2-client-secret",
"redirectUri": "https://your-backend.com/auth/fluxer"
}
"redis": { "url": "redis://localhost:6379" }
}
```
2. Create a Fluxer OAuth2 application at Settings > application.
2. How it works:
- The bot listens on Redis pub/sub channels (`request` / `response` / `info`) and answers JSON-RPC style requests with an `id` for correlation.
- Supported requests: `fetchPlayers`, `user`, `sharedServers`, `server`, `allServers`, `commands`, and `function` (remote actions: `join`, `pausePlayback`, `resumePlayback`, `skip`, `volume`, `addToQueue`, `voiceState`, `leave`, `testConnection`).
- Player updates are broadcast (debounced) on per-bot/per-player Redis channels so the frontend can render live state.
- **Login flow:** the external frontend writes login codes into the MySQL `login_codes` table; the bot verifies them with bcrypt hashes and marks them verified. Player control additionally requires the user to be in the same voice channel (owners are exempt).
3. For HTTPS support, configure SSL in `config.json`:
```json
"ssl": {
"private": "/etc/letsencrypt/live/your.domain/privkey.pem",
"cert": "/etc/letsencrypt/live/your.domain/fullchain.pem",
"useSSL": true,
"httpPort": 80
}
```
3. **Security note:** the RPC channel has **no shared secret** — anything that can publish to your Redis can invoke the remote actions. Keep Redis network-isolated (as the Docker setup does) and don't expose it publicly.
### Configuration Reference
---
## Configuration Reference
Key configuration options in `config.json`:
@@ -367,28 +373,19 @@ Key configuration options in `config.json`:
| `prefix` | string | `%` | Default command prefix |
| `embedColor` | string | `0xe9196c` | Hex color for embed messages |
| `owners` | string[] | `[]` | User IDs with owner privileges |
| `playerAFKTimeout` | number | `60000` | Inactivity timeout in ms before bot leaves |
| `playerAFKTimeout` | number | `60000` | Inactivity timeout in ms before the player panel session ends |
| `customStatsFooter` | string | — | Custom text shown in the `%stats` embed footer |
| `webPort` | number | `80` | Port for the web dashboard |
| `helpCatalog` | bool | `true` | Enable categorized help command |
| `helpPagination` | bool | `true` | Enable paginated help output |
| `presenceInterval` | number | `30000` | Interval in ms for rotating bot presence status |
| `presenceContents` | array | `[]` | Presence status messages to cycle through (strings or objects with `text`/`emoji_name`/`emoji_id`/`activity`) |
| `mysql` | object | — | **Required.** MySQL connection settings |
| `nodelink` | object | — | NodeLink connection (`host`, `port`, `password`, `requestTimeout`) |
| `spotify` | object | — | Spotify API credentials (`clientId`, `clientSecret`) |
| `geniusToken` | string | — | *(Deprecated, unused)* Previously for lyrics; lyrics are now fetched via NodeLink |
| `lastfm` | object | — | Last.fm integration (`apiKey`, `apiSecret`, `scrobbleThreshold`, `scrobbleMinMs`) |
| `dashboard` | object | — | Dashboard config: `enabled`, `redis`, `fluxer` (OAuth2) |
| `dashboardUrl` | string | — | URL the dashboard is accessible from |
| `sessionSecret` | string | — | Secret for Express.js session middleware |
| `logging` | object | — | Per-category log toggle (`enabled` + 12 sub-categories, see config example) |
| `timers` | object | — | Timing values for inactivity, recovery, rejoin, etc. (14 sub-keys) |
| `cache` | object | — | Guild and member cache (`guilds.enabled`, `guilds.max`, `members.enabled`, `members.max`) |
| `fluxerlist` | object | — | FluxerList integration (`apiKey`, `serverId`, `botId`, `serverSlug`, `botSlug`) |
| `dashboard` | object | — | Dashboard backend: `enabled`, `redis.url` |
| `radio` | array | `[]` | Custom radio station definitions |
| `ssl` | object | — | SSL certificate paths (`private`, `cert`), `useSSL`, `httpPort` |
| `presenceInterval` | number | — | Interval in ms for rotating bot presence status |
| `presenceContents` | string[] | `[]` | Presence status messages to cycle through |
| `logging` | object | — | Per-category log toggles: `enabled`, `warn`, and 14 categories (`player`, `inactivity`, `aloneCheck`, `voiceState`, `voice247`, `voice`, `mediaplayer`, `commands`, `guild`, `recovery`, `settings`, `lavalink`, `dashboard`, `redis`) |
| `timers` | object | — | Timing values in ms: `inactivityTimeout`, `aloneCheckInterval`, `aloneCheckDebounce`, `rejoin247Delay`, `leave247RejoinDelay`, `playerUpdateInterval`, `searchSessionTimeout`, `playerSessionTimeout`, `intentionalLeaveTTL` |
| `fluxer.js` | object | — | Fluxer.js REST options (`timeout`, `retries`) |
| `fluxer-api` | object | — | Fluxer API endpoint configuration |
---
@@ -396,63 +393,69 @@ Key configuration options in `config.json`:
```
fluxer/
├── index.mjs # Entry point — Remix class, boot sequence, error handling
├── index.mjs # Entry point — Remix class, boot sequence, alone-check,
│ # presence rotation, error handling, graceful shutdown
├── config_example.json # Configuration template
├── package.json
├── commands/ # Command modules (one file per command)
│ ├── play.mjs # Play a track or playlist
├── 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, volume, etc.)
│ ├── 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, paginated)
│ ├── stats.mjs # Bot stats with live player count
│ ├── lastfm.mjs # Last.fm account linking, scrobbling, and profile
│ ├── 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 loader, prefix manager, registry
│ ├── MessageHandler.mjs # Message parsing, embed builder, pagination, help
│ ├── PlayerManager.mjs # Spawns and manages per-channel Player instances
│ ├── Player.mjs # Core player — queue, playback, filters, events
│ ├── MoonlinkManager.mjs # Moonlink.js (Lavalink) node session manager
│ ├── Settings.mjs # RemoteSettingsManager + ServerSettings export
│ ├── GatewayHandler.mjs # Raw WS events, voice-state tracking, presence rotation
│ ├── RecoveryManager.mjs # Session persistence, crash recovery, 24/7 auto-join
│ ├── LastFmManager.mjs # Last.fm API client — auth, scrobbling, user data, stored scrobble stats
│ ├── TrackOptionsManager.mjs # Per-user track start/end time preferences (auto-seek, auto-skip)
│ ├── Utils.mjs # Shared utilities
│ ├── worker.mjs # Background task worker
│ ├── probe.mjs # FFprobe wrapper for audio stream info
│ ├── 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 helper utilities
│ │ ├── providers.mjs # Audio source provider definitions
│ │ ├── 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/
│ │ ├── StreamMerger.mjs # Audio stream merging utilities
│ │ └── Tuna.mjs # Audio filter/effect processing
│ │ └── WebMOpusMuxer.mjs # Streaming EBML/Matroska muxer (Opus → WebM for LiveKit)
│ └── dashboard/
│ ├── Dashboard.mjs # Web dashboard server (Express + WebSocket)
│ ├── DatabaseManager.mjs # Dashboard database query manager
│ └── RedisHandler.mjs # Redis session and pub/sub handler
│ ├── 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 # Abstract SettingsManager base class
│ ├── migrate.mjs # Legacy-to-remote settings migration script
│ ├── runnables.mjs # Runnable task definitions
│ ├── 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
├── docker/ # Docker self-hosting (Dockerfile, compose, configs)
│ ├── Dockerfile # Multi-stage build (Node 22 + FFmpeg + tini)
│ ├── docker-entrypoint.sh # Config validation on first boot
│ ├── docker-compose.yml # bot + MySQL + Redis + NodeLink
│ ├── config_example.json # Docker-friendly config template
│ ├── .env.example # Secrets template
│ └── nodelink.config.json # NodeLink audio node config
├── docker/ # Docker self-hosting (Dockerfile, compose, entrypoint,
│ # config templates, .env.example)
└── storage/
├── defaults.json # Default per-guild settings template
├── modules.json # Plugin module registry
├── stats.json # Runtime statistics
├── modules.json # Plugin module registry (empty by default)
├── stats.json # Static counters
└── locales/bot/ # Translation files
├── en.json
├── ar-SA.json
@@ -487,9 +490,7 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the
| :--- | :--- | :--- |
| `npm start` | `node index.mjs` | Start the bot |
| `npm run dev` | `node --inspect index.mjs --trace-warnings` | Start with Node.js inspector |
| `npm run commands` | `node index.mjs usage` | Generate command usage documentation |
| `npm run defaultsSync` | `node index.mjs sreload` | Sync default settings to all guilds |
| `npm run migrate` | `node settings/migrate.mjs` | Run the legacy settings migration |
| `npm run migrate` | `node settings/migrate.mjs` | Clone/repair the remote settings table |
---
@@ -502,12 +503,13 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the
**Powered by:**
- [`@fluxerjs/core`](https://github.com/fluxerjs/core) — Fluxer API client
- [`revoice.js`](https://www.npmjs.com/package/revoice.js) — LiveKit voice connection and MediaPlayer
- [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) — Native voice channel integration
- [`moonlink.js`](https://github.com/Ecliptia/moonlink.js) — Lavalink proxy
- [`NodeLink`](https://github.com/PerformanC/NodeLink) — Audio node manager
- [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) — LiveKit voice connections and playback
- [`lavalink-client`](https://www.npmjs.com/package/lavalink-client) — Lavalink/NodeLink client (search + streaming)
- [`NodeLink`](https://github.com/PerformanC/NodeLink) — Lavalink-compatible audio node
- [`prism-media`](https://github.com/discordjs/prism-media) — Opus encoding and stream demuxing
<p align="center">
&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>
+8 -4
View File
@@ -1,6 +1,6 @@
/**
* @file autoplay command — Toggle autoplay to automatically play similar tracks when the queue ends
* @module commands/autoplay
* @description Toggle autoplay mode — automatically play similar tracks when the queue ends.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -8,6 +8,7 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the autoplay command. */
export const command = new CommandBuilder()
.setName("autoplay")
.setDescription("Toggle autoplay — automatically play similar tracks when the queue ends.", "commands.autoplay")
@@ -15,9 +16,12 @@ export const command = new CommandBuilder()
.addAliases("ap");
/**
* Execute the autoplay command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the autoplay command.
* Toggles autoplay on the player. When enabled, registers a queueEnd listener
* that fetches similar tracks (via Last.fm or YouTube) and adds them to the queue.
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data (unused, no options required).
* @returns {Promise<void>}
*/
export async function run(msg, data) {
+9 -4
View File
@@ -1,12 +1,16 @@
/**
* @file clear command — Remove all songs from the queue
* @module commands/clear
* @description Remove all songs from the playback queue.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the clear command.
*/
export const command = new CommandBuilder()
.setName("clear")
.setDescription("Remove all songs from the queue.", "commands.clear")
@@ -14,9 +18,10 @@ export const command = new CommandBuilder()
.setCategory("music");
/**
* Execute the clear command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the clear command.
* Clears the entire queue and sends a confirmation embed.
*
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(msg) {
+68 -55
View File
@@ -1,6 +1,6 @@
/**
* @file debug command — Owner-only debug utilities for voice connections, ghost detection, and forced rejoins
* @module commands/debug
* @description Owner-only debug command for voice diagnostics, ghost connection detection, and forced rejoin.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -15,9 +15,10 @@ const INTENTIONAL_LEAVE_TTL = 30_000;
const MAX_DESC = 4096;
/**
* Return a human-readable label for a voice room's connection state.
* @param {object} room - The voice room instance
* @returns {string}
* 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";
@@ -33,10 +34,10 @@ function roomStateLabel(room) {
}
/**
* Detect whether a player has a "ghost" connection — the player object exists
* but the underlying voice room is disconnected, reconnecting, or absent.
* @param {import("../src/Player.mjs").default} player
* @returns {boolean}
* 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;
@@ -58,10 +59,11 @@ function isGhostConnection(player) {
}
/**
* Retrieve the bot's voice state from the gateway cache for a given guild.
* @param {object} client - The Fluxer client instance
* @param {string} guildId - The guild ID to look up
* @returns {{ userId: string, channelId: string } | null}
* 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;
@@ -108,10 +110,11 @@ function getBotGatewayVoiceState(client, guildId) {
}
/**
* Check whether the gateway voice state is stale compared to the player's expected channel.
* @param {object} client - The Fluxer client instance
* @param {import("../src/Player.mjs").default} player
* @returns {boolean}
* 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?.();
@@ -127,11 +130,12 @@ function isStaleGatewayPresence(client, player) {
}
/**
* Build a human-readable label for a player's guild/channel.
* @param {object} client - The Fluxer client
* @param {string} channelId - The channel ID
* @param {import("../src/Player.mjs").default} player
* @returns {string}
* 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);
@@ -141,10 +145,12 @@ function buildPlayerLabel(client, channelId, player) {
}
/**
* Destroy a player's stale connection and respawn a fresh player, restoring queue, loop, filters, and playback.
* @param {object} ctx - The bot context (this)
* @param {import("../src/Player.mjs").default} player
* @returns {Promise<{ success: boolean, reason?: string, channelId?: string, roomConnected?: boolean, roomState?: string, resumedPlayback?: boolean }>}
* 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<object>} Result object with success status, room state, and details.
*/
async function forceRejoinPlayer(ctx, player) {
const channelId = player._channelId ?? player._home247Channel;
@@ -166,7 +172,6 @@ async function forceRejoinPlayer(ctx, player) {
try {
ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL);
ctx.revoice?.markIntentionalDisconnect(cleanChannelId);
ctx.players.playerMap.delete(cleanChannelId);
ctx.players._unindexPlayer?.(cleanGuildId, cleanChannelId);
@@ -188,13 +193,8 @@ async function forceRejoinPlayer(ctx, player) {
ctx.players._pendingJoins?.delete?.(cleanChannelId);
const revoiceConn = ctx.revoice?.connections?.get(cleanChannelId);
if (revoiceConn) {
try { await ctx.revoice._destroyStaleConnection(cleanChannelId, revoiceConn); } catch (e) { logger.warn("[Debug] revoice stale destroy:", e?.message); }
} else if (player.connection) {
if (player.connection) {
try { player.connection.removeAllListeners(); } catch (e) { logger.warn("[Debug] connection listener removal:", e?.message); }
try { ctx.revoice?._leaveGateway?.(cleanChannelId, cleanGuildId); } catch (e) { logger.warn("[Debug] gateway leave:", e?.message); }
try { ctx.revoice?.deleteConnection?.(cleanChannelId); } catch (e) { logger.warn("[Debug] revoice delete:", e?.message); }
try { await player.connection.disconnect(); } catch (e) { logger.warn("[Debug] connection disconnect:", e?.message); }
}
@@ -247,12 +247,14 @@ async function forceRejoinPlayer(ctx, player) {
}
/**
* Process a batch of players for rejoin, with progress updates.
* @param {object} ctx - The bot context (this)
* @param {Array<[string, import("../src/Player.mjs").default]>} entries - [channelId, player] pairs
* @param {import("../src/MessageHandler.mjs").Message} statusMsg - The status message to edit with progress
* @param {string} title - The embed title
* @returns {Promise<Array>} Results array
* Process a batch of players for force-rejoin, updating a status message with progress.
* @private
* @async
* @param {object} ctx - The bot (Remix) instance context.
* @param {Array} entries - Array of [channelId, player] tuples.
* @param {object} statusMsg - The message to update with progress.
* @param {string} title - The title for the progress display.
* @returns {Promise<object[]>} Array of rejoin results.
*/
async function processRejoinBatch(ctx, entries, statusMsg, title) {
const results = [];
@@ -286,11 +288,12 @@ async function processRejoinBatch(ctx, entries, statusMsg, title) {
}
/**
* Build the final results embed after a batch rejoin.
* @param {Array} results - Results from processRejoinBatch
* @param {string} title - The embed title
* @param {string} noun - "ghost connection(s)" or "24/7 channel(s)"
* @returns {{embeds: [EmbedBuilder]}}
* Build the final embed summarizing rejoin results.
* @private
* @param {object[]} results - Array of rejoin result objects.
* @param {string} title - The title for the embed.
* @param {string} noun - The noun describing the rejoin targets.
* @returns {object} Message payload with embed.
*/
function buildRejoinResultEmbed(results, title, noun) {
const resultLines = [
@@ -324,6 +327,10 @@ function buildRejoinResultEmbed(results, title, noun) {
return { embeds: [new EmbedBuilder().setColor(finalColor).setTitle(`Debug — ${title}`).setDescription(resultLines.join("\n").slice(0, MAX_DESC))] };
}
/**
* @type {CommandBuilder}
* @description Command definition for the debug command (owner-only).
*/
export const command = new CommandBuilder()
.setName("debug")
.setDescription("A debug command for various purposes.")
@@ -336,9 +343,11 @@ export const command = new CommandBuilder()
.setRequired(true));
/**
* Execute the debug command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the debug command.
* Routes to the appropriate debug subcommand based on the target option.
*
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the target option.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
@@ -369,13 +378,15 @@ export async function run(msg, data) {
}
/**
* Run a batch rejoin for players matching a filter.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {string} key - The debug key for log labels
* @param {string} title - The display title
* @param {string} noun - What we're rejoining (for result text)
* @param {(player: import("../src/Player.mjs").default) => boolean} filter - Player filter
* @param {boolean} showHintIfEmpty - Show a hint when no matches found
* Run a batch rejoin operation on matching players.
* @private
* @async
* @param {object} msg - The command message wrapper.
* @param {string} key - Identifier key for the rejoin type.
* @param {string} title - Display title for the operation.
* @param {string} noun - Noun describing the targets.
* @param {Function} filter - Function to filter which players to rejoin.
* @param {boolean} [showHintIfEmpty=false] - Whether to show a hint if no matches found.
* @returns {Promise<void>}
*/
async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = false) {
@@ -426,8 +437,10 @@ async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = f
}
/**
* Run the full voice diagnostic with paginated output.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* Run a full voice diagnostic, displaying player states and ghost connections.
* @private
* @async
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>}
*/
async function runVoiceDiagnostic(msg) {
+57 -27
View File
@@ -1,6 +1,6 @@
/**
* @file eval command — Owner-only JavaScript code evaluation with sensitive-data redaction
* @module commands/eval
* @description Owner-only command to evaluate arbitrary JavaScript code and display the result.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,10 +10,7 @@ import { logger } from "../src/constants/Logger.mjs";
import { inspect } from "node:util";
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
/**
* Matches any key that *contains* one of these strings (case-insensitive).
*/
/** @private @type {string[]} Property name substrings that indicate sensitive/secret data. */
const RESTRICTED = [
"token",
"config",
@@ -24,21 +21,23 @@ const RESTRICTED = [
"secret",
"authorization",
"mysql",
"nodelink",
"lavalink",
"_nl",
"credential",
"apikey",
"webhook",
];
/** @private @type {number} Maximum recursion depth when scanning for sensitive keys. */
const SCAN_DEPTH = 6;
/**
* Check whether an object contains sensitive keys at any nesting level.
* @param {object} obj - The object to scan
* @param {number} [level=0] - Current recursion depth
* @param {WeakSet} [visited=new WeakSet()] - Visited object tracker
* @returns {boolean}
* @private
* Recursively check whether an object contains keys matching RESTRICTED substrings.
* @param {*} obj - The object to scan.
* @param {number} [level=0] - Current recursion depth.
* @param {WeakSet} [visited=new WeakSet()] - Already-visited objects to prevent cycles.
* @returns {boolean} True if any sensitive key is found.
*/
function hasSensitive(obj, level = 0, visited = new WeakSet()) {
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return false;
@@ -52,11 +51,12 @@ function hasSensitive(obj, level = 0, visited = new WeakSet()) {
}
/**
* Recursively redact sensitive keys from an object, replacing values with "[REDACTED]".
* @param {object} obj - The object to scrub
* @param {number} [level=0] - Current recursion depth
* @param {WeakSet} [visited=new WeakSet()] - Visited object tracker
* @returns {object} The scrubbed object (or the original if no changes were needed)
* @private
* Recursively redact sensitive keys in an object, replacing values with "[REDACTED]".
* @param {*} obj - The object to clean.
* @param {number} [level=0] - Current recursion depth.
* @param {WeakSet} [visited=new WeakSet()] - Already-visited objects to prevent cycles.
* @returns {*} The cleaned object (original reference if no modifications, new object otherwise).
*/
function removeSensitive(obj, level = 0, visited = new WeakSet()) {
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return obj;
@@ -85,9 +85,12 @@ function removeSensitive(obj, level = 0, visited = new WeakSet()) {
}
/**
* Await a value if it is a Promise, then redact sensitive data and format for display.
* @param {*} value - The value to clean and format
* @returns {Promise<string>} Formatted, safe string representation
* @private
* @async
* Sanitize a value for safe display: await promises, redact sensitive keys,
* inspect with node:util, and escape Discord markup characters.
* @param {*} value - The raw eval result.
* @returns {Promise<string>} The sanitized output string.
*/
async function clean(value) {
if (value instanceof Promise) value = await value;
@@ -111,9 +114,11 @@ async function clean(value) {
}
/**
* Determine whether a code string is a single expression (no semicolons, blocks, or declarations).
* @param {string} code - The code to inspect
* @returns {boolean}
* @private
* Determine whether a code string is a single expression (vs. statements).
* Used to decide whether to wrap in a return statement.
* @param {string} code - The code to analyze.
* @returns {boolean} True if the code appears to be a single expression.
*/
function isSingleExpression(code) {
const trimmed = code.trim();
@@ -137,8 +142,12 @@ function isSingleExpression(code) {
}
/**
* Executes the code and returns the raw data instead of a formatted string,
* so we can paginate it inside Embeds later.
* @private
* @async
* Execute a JavaScript expression/statement in a sandboxed async context.
* @param {string} expression - The code to evaluate.
* @param {object} context - The `this` context for the eval.
* @returns {Promise<{output: string, isError: boolean, type: string, elapsed: number}>} Eval result.
*/
async function runEval(expression, context) {
const start = Date.now();
@@ -163,6 +172,7 @@ async function runEval(expression, context) {
return { output, isError, type, elapsed };
}
/** @type {CommandBuilder} @description Command definition for the eval command (owner-only). */
export const command = new CommandBuilder()
.setName("eval")
.setDescription("Evaluates JavaScript code (Owner Only).")
@@ -175,9 +185,12 @@ export const command = new CommandBuilder()
);
/**
* Execute the eval command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the eval command.
* Evaluates the provided JavaScript expression, sanitizes the output,
* and displays it in a paginated embed with reaction navigation.
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the expression option.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
@@ -204,6 +217,13 @@ export async function run(msg, data) {
const totalPages = chunks.length;
let currentPage = 0;
/**
* @private
* Build the embed payload for a specific page of the eval output.
* @param {number} pageIdx - Zero-based page index.
* @param {boolean} [expired=false] - Whether the reaction controls have expired.
* @returns {object} Embed payload for message reply/edit.
*/
const buildPageContent = (pageIdx, expired = false) => {
const title = isError
? this.t(msg, "responses.eval.resultTitleError")
@@ -239,6 +259,11 @@ export async function run(msg, data) {
await replyMsg.message.react(emoji).catch(() => {});
}
/**
* @private
* Remove all navigation reactions from the eval reply message.
* @returns {Promise<void>}
*/
const clearReactions = async () => {
try {
await replyMsg.message.removeAllReactions();
@@ -251,6 +276,11 @@ export async function run(msg, data) {
}
};
/**
* @private
* Reset the emoji removal timeout timer for the eval session.
* @returns {void}
*/
const resetTimer = () => {
clearTimeout(emojiTimeout);
emojiTimeout = setTimeout(async () => {
+21 -15
View File
@@ -1,6 +1,6 @@
/**
* @file filter command — Interactive audio filter picker with emoji-based toggling
* @module commands/filter
* @description Interactive audio filter picker with emoji-based selection and pagination.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -173,10 +173,10 @@ const PAGE_SIZE = 9;
const SESSION_MS = 60_000;
/**
* Merge multiple active filter payloads into a single Lavalink filters object.
* Categories that overlap are overwritten by the last filter in the list.
* The special "off" key is skipped — it carries an empty payload and is handled
* by clearing activeKeys before this function is called.
* Merge filter payloads for multiple active filter keys into one combined payload.
* @private
* @param {string[]} keys - Array of active filter keys.
* @returns {object} Merged Lavalink filter payload.
*/
function mergeFilterPayloads(keys) {
const merged = {};
@@ -191,6 +191,10 @@ function mergeFilterPayloads(keys) {
return merged;
}
/**
* @type {CommandBuilder}
* @description Command definition for the filter command.
*/
export const command = new CommandBuilder()
.setName("filter")
.setDescription(
@@ -201,13 +205,14 @@ export const command = new CommandBuilder()
.addAliases("filters", "fx", "effect");
/**
* Build the embed for a single page of the filter picker.
* @param {Function} t - Translation function
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {number} page - Current page index (0-based)
* @param {string[]} activeKeys - Currently active filter keys
* @param {object} [current] - The currently playing track
* @returns {import("@fluxerjs/core").EmbedBuilder}
* Build an embed for a page of the filter picker.
* @private
* @param {Function} t - Translation function.
* @param {object} msg - The command message wrapper.
* @param {number} page - Current page index (0-based).
* @param {string[]} activeKeys - Array of currently active filter keys.
* @param {object|null} current - The currently playing track, or null.
* @returns {EmbedBuilder} The constructed embed.
*/
function buildPageEmbed(t, msg, page, activeKeys, current) {
const totalPages = Math.ceil(FILTERS.length / PAGE_SIZE);
@@ -253,9 +258,10 @@ function buildPageEmbed(t, msg, page, activeKeys, current) {
}
/**
* Execute the filter command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the filter command.
* Opens an interactive filter picker with emoji reactions.
*
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(msg) {
+10 -4
View File
@@ -1,11 +1,15 @@
/**
* @file forceleave command — Force the bot to leave a voice channel (requires ManageChannels)
* @module commands/forceleave
* @description Force the bot to leave a voice channel (requires ManageChannels permission).
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { cleanId } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the forceleave command.
*/
export const command = new CommandBuilder()
.setName("forceleave")
.addAliases("fl")
@@ -20,9 +24,11 @@ export const command = new CommandBuilder()
/**
* Execute the forceleave command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the forceleave command.
* Validates the target channel and forces the bot to leave.
*
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the channelId option.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
+9 -4
View File
@@ -1,12 +1,16 @@
/**
* @file invite command — Get the bot invite link and support server invite
* @module commands/invite
* @description Display the bot invite link and support server information.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the invite command.
*/
export const command = new CommandBuilder()
.setName("invite")
.setDescription("Get the invite link for Remix and the support server.", "commands.invite")
@@ -14,9 +18,10 @@ export const command = new CommandBuilder()
.setCategory("util");
/**
* Execute the invite command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the invite command.
* Sends an embed with the bot invite link and support server info.
*
* @param {object} message - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(message) {
+42 -161
View File
@@ -1,141 +1,19 @@
/**
* @file join command — Make the bot join a voice channel and initialise a player
* @module commands/join
* @description Makes the bot join a voice channel. Supports explicit channel argument
* (mention, ID, or name) or auto-detects the user’s current voice channel.
* All player spawning goes through PlayerManager.initPlayer() for consistent
* 24/7 handling, event binding, and permission checks.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs";
import { logger } from "../src/constants/Logger.mjs";
import Player from "../src/Player.mjs";
/**
* Join a voice channel, create a Player, and register event listeners.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {string} cid - The voice channel ID to join
* @param {Function} [cb] - Callback invoked with the player on success
* @param {Function} [ecb] - Callback invoked on error
* @returns {Promise<void>}
* @type {CommandBuilder}
* @description Command definition for the join command.
*/
export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
const cleanChannelId = cleanId(cid);
if (!this.client.channels.has(cleanChannelId)) {
ecb();
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(this.t(message, "responses.join.channelNotFound", { channel: cid }));
return message.reply({ embeds: [embed] });
}
const existing = this.players.playerMap.get(cleanChannelId)
?? [...this.players.playerMap.values()].find((player) => cleanId(player?._channelId) === cleanChannelId);
if (existing) {
cb(existing);
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(this.t(message, "responses.join.alreadyJoined", { channel: cid }));
return message.reply({ embeds: [embed] });
}
if (!this.moonlink) {
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(this.t(message, "responses.join.audioNodeConnecting"));
ecb();
return message.reply({ embeds: [embed] });
}
const p = new Player(this.config.token, {
client: this.client,
config: this.config,
nodelink: this.config.nodelink,
moonlink: this.moonlink ?? null,
revoice: this.revoice ?? null,
messageChannel: message.channel,
settingsMgr: this.settingsMgr ?? this.settings ?? null,
observedVoiceUsers: this.observedVoiceUsers ?? null,
});
p.on("autoleave", () => {
const activeChannelId = cleanId(p._channelId ?? cid) || cid;
const homeChannelId = cleanId(p._home247Channel ?? activeChannelId) || activeChannelId;
const guildId = getMessageGuildId(message);
const is247 = (() => {
try {
const raw = this.settingsMgr?.getServer?.(guildId)?.get?.("stay_247");
return raw && raw !== "none";
} catch (_) { return false; }
})();
const mode247 = (() => {
if (!is247) return "off";
try {
const set = this.settingsMgr?.getServer?.(guildId);
const modes = set?.get?.("stay_247_modes");
const matchCh = homeChannelId || activeChannelId;
if (modes && typeof modes === "object" && !Array.isArray(modes) && modes[matchCh]) {
return modes[matchCh];
}
return set?.get?.("stay_247_mode") ?? "off";
} catch (_) { return "off"; }
})();
this.players.playerMap.delete(activeChannelId);
if (activeChannelId !== cid) this.players.playerMap.delete(cid);
if (homeChannelId !== activeChannelId) this.players.playerMap.delete(homeChannelId);
p.destroy();
if (is247 && (mode247 === "on" || mode247 === "auto")) {
const rejoinDelay = this.config?.timers?.rejoin247Delay ?? 3_000;
const prefix = this.handler.getPrefix(guildId);
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(this.t(message, "responses.join.autoLeaveInactive247", { channel: activeChannelId, prefix }));
message.channel.send({ embeds: [embed] }).catch(() => {});
setTimeout(async () => {
try {
if (typeof this._spawnPlayer === "function") {
await this._spawnPlayer(guildId, homeChannelId);
}
} catch (e) {
logger.warn(`[join/autoleave] 24/7 auto-rejoin failed for ${homeChannelId}: ${e.message}`);
}
}, rejoinDelay);
} else {
const embed2 = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(this.t(message, "responses.join.autoLeaveInactive", { channel: activeChannelId }));
message.channel.send({ embeds: [embed2] }).catch(() => {});
}
});
p.on("message", m => {
const guildId = getMessageGuildId(message);
const raw = this.settingsMgr?.getServer?.(guildId)?.get("songAnnouncements");
const disabled = raw === false || raw === 0 ||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return;
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(m);
message.channel.send({ embeds: [embed] }).catch(() => {});
});
this.players._pendingJoins.add(cleanChannelId);
const joiningEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joining"));
const statusMsg = await message.reply({ embeds: [joiningEmbed] });
try {
await p.join(cleanChannelId);
this.players.playerMap.set(cleanChannelId, p);
this.players._pendingJoins.delete(cleanChannelId);
const okEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joined", { channel: cid }));
await statusMsg.edit({ embeds: [okEmbed] });
cb(p);
} catch (e) {
this.players._pendingJoins.delete(cleanChannelId);
this.players.playerMap.delete(cleanChannelId);
p.destroy();
const errEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joinFailed", { error: e.message }));
await statusMsg.edit({ embeds: [errEmbed] });
ecb(e);
}
}
export const command = new CommandBuilder()
.setName("join")
.setDescription("Make the bot join your voice channel, or specify one.", "commands.join")
@@ -148,48 +26,56 @@ export const command = new CommandBuilder()
);
/**
* Execute the join command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @returns {Promise<void>}
* Resolve a user-provided channel string to a channel ID.
* Supports <#ID> mentions, raw numeric IDs, and channel name matching.
*
* @param {string} rawArg - The raw argument string from the command.
* @param {object} ctx - The bot context (Remix instance).
* @returns {string|null} The resolved channel ID, or null if not found.
*/
function resolveChannelId(rawArg, ctx) {
if (!rawArg) return null;
const mentionMatch = rawArg.match(/^<(#|&)?(\d+)>$/);
const idMatch = rawArg.match(/^(\d{15,})$/);
if (mentionMatch) return mentionMatch[2];
if (idMatch) return idMatch[1];
// Try name-based lookup
const guildId = cleanId(getMessageGuildId(ctx._currentMessage));
if (!guildId) return null;
const allChannels = [...(ctx.client?.channels?.values?.() ?? [])];
const match = allChannels.find(c => {
const cServerId = cleanId(c.guildId ?? c.guild?.id ?? c.server_id ?? c.serverId);
return c.type === 2 && cServerId === guildId && c.name?.toLowerCase() === rawArg.toLowerCase();
});
return match?.id ?? null;
}
/**
* Run handler for the join command.
* Resolves the target voice channel and delegates to PlayerManager.initPlayer().
*
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing option values.
* @returns {Promise<Player|null>} The spawned player, or null on failure.
*/
export async function run(message, data) {
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
if (rawArg) {
const mentionMatch = rawArg.match(/^<#(\d+)>$/);
const idMatch = rawArg.match(/^(\d{15,})$/);
let resolvedId = null;
if (mentionMatch) {
resolvedId = mentionMatch[1];
} else if (idMatch) {
resolvedId = idMatch[1];
} else {
const guildId = cleanId(getMessageGuildId(message));
const allChannels = [
...(this.client?.channels?.values?.() ?? [])
];
const match = allChannels.find(c => {
const cServerId = cleanId(c.guildId ?? c.guild?.id ?? c.server_id ?? c.serverId);
const isVoice = c.type === 2;
return isVoice && cServerId === guildId &&
(c.name?.toLowerCase() === rawArg.toLowerCase());
});
if (match) resolvedId = match.id;
}
const resolvedId = resolveChannelId(rawArg, this);
if (!resolvedId) {
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(this.t(message, "responses.join.voiceChannelNotFound"));
return message.reply({ embeds: [embed] });
}
return this.players.initPlayer(message, resolvedId);
}
// No argument — auto-detect the user’s current voice channel
const { channelId: cid } = await this.players.checkVoiceChannels(message);
if (!cid) {
const prefix = this.handler.getPrefix(getMessageGuildId(message));
const embed = new EmbedBuilder().setColor(getGlobalColor())
@@ -199,8 +85,3 @@ export async function run(message, data) {
return this.players.initPlayer(message, cid);
}
export const exportDef = {
name: "joinChannel",
object: joinChannel
};
+91 -31
View File
@@ -1,6 +1,7 @@
/**
* @file lastfm command — Link Last.fm accounts, scrobble, view profiles, leaderboards, and more
* @module commands/lastfm
* @description Last.fm integration command supporting account linking, scrobbling,
* profile viewing, leaderboards, whoknows, and playlist playback.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -14,6 +15,10 @@ import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"];
/**
* @type {CommandBuilder}
* @description Command definition for the lastfm command.
*/
export const command = new CommandBuilder()
.setName("lastfm")
.setDescription("Link your Last.fm account, toggle scrobbling, or view your profile.", "commands.lastfm")
@@ -49,6 +54,13 @@ export const command = new CommandBuilder()
.setRequired(false)
);
/**
* Return an embed indicating Last.fm is not configured.
* @private
* @param {object} ctx - The bot (Remix) instance context.
* @param {object} msg - The command message wrapper.
* @returns {{ embeds: EmbedBuilder[] }} Error embed payload.
*/
function notConfigured(ctx, msg) {
return {
embeds: [new EmbedBuilder()
@@ -57,6 +69,14 @@ function notConfigured(ctx, msg) {
};
}
/**
* Return an embed indicating the user has not linked their Last.fm account.
* @private
* @param {object} ctx - The bot (Remix) instance context.
* @param {object} msg - The command message wrapper.
* @param {string} prefix - The guild's command prefix.
* @returns {{ embeds: EmbedBuilder[] }} Error embed payload.
*/
function notLinked(ctx, msg, prefix) {
return {
embeds: [new EmbedBuilder()
@@ -67,6 +87,12 @@ function notLinked(ctx, msg, prefix) {
const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums", "artists"];
/**
* Build a Last.fm track metadata object from a track.
* @private
* @param {object} track - The track object with artist, name, and url.
* @returns {{ source: string, artist: string, name: string, url: string }} Track metadata.
*/
function buildLastFmTrackMeta(track) {
return {
source: "lastfm",
@@ -76,6 +102,15 @@ function buildLastFmTrackMeta(track) {
};
}
/**
* Resolve a Last.fm track to playable audio via a search provider.
* @private
* @async
* @param {object} player - The player instance.
* @param {object} track - The Last.fm track with query and metadata.
* @param {string} [resolveProvider="yt"] - The provider to resolve with.
* @returns {Promise<object[]|null>} Array of resolved track data, or null on failure.
*/
async function resolveLastFmTrack(player, track, resolveProvider = "yt") {
const data = await player.workerJob("generalQuery", {
query: track.query,
@@ -90,9 +125,10 @@ async function resolveLastFmTrack(player, track, resolveProvider = "yt") {
}
/**
* Extract current track info from the player for Last.fm lookups.
* @param {object} player
* @returns {{ artist: string|null, name: string|null, album: string|null, track: object|null } | null}
* Extract Last.fm-relevant info from the player's current track.
* @private
* @param {object} player - The player instance.
* @returns {{ artist: string|null, name: string|null, album: string|null, track: object|null }} Extracted track info.
*/
function extractCurrentTrack(player) {
const track = player?.queue?.getCurrent();
@@ -104,9 +140,11 @@ function extractCurrentTrack(player) {
}
/**
* Get all human member IDs from a guild for whoknows lookups.
* @param {object} guild
* @returns {Promise<Array<string>>}
* Get all non-bot user IDs in a guild.
* @private
* @async
* @param {object} guild - The Discord guild object.
* @returns {Promise<string[]>} Array of user ID strings.
*/
async function getGuildLinkedUsers(guild) {
const memberIds = [];
@@ -124,10 +162,11 @@ async function getGuildLinkedUsers(guild) {
}
/**
* Parse a period string from token option or message content.
* @param {object} data
* @param {object} msg
* @returns {string} A valid period string
* Extract a valid time period from command data or message content.
* @private
* @param {object} data - Parsed command data.
* @param {object} msg - The command message wrapper.
* @returns {string} The period string, defaults to "overall".
*/
function extractPeriod(data, msg) {
let raw = data.get("token")?.value;
@@ -144,18 +183,15 @@ function extractPeriod(data, msg) {
}
/**
* Resolve a Last.fm category (loved/top/recent/playlist) into playable tracks.
* Shared between `%lastfm play <cat>` and `%play lastfm:<cat>`.
*
* @param {object} ctx - The command `this` context (has .lastfm, .getPlayer, .handler, .t)
* @param {import("../src/MessageHandler.mjs").Message} msg - The message object
* @param {string} userId - The Discord user ID
* @param {string} category - "loved", "top", "recent", or "playlist"
* @param {object} [options]
* @param {string} [options.period] - Period for top tracks
* @param {number} [options.limit] - Max tracks
* @param {string|number} [options.playlistId] - Playlist number or URL (for category="playlist")
* @param {string} [options.resolveProvider] - Provider to search on when resolving tracks (e.g. "td" for Tidal, "sp" for Spotify). Default: "yt"
* Fetch and play tracks from a Last.fm category (loved, top, recent, albums, artists, playlist).
* @async
* @param {object} ctx - The bot (Remix) instance context.
* @param {object} msg - The command message wrapper.
* @param {string} userId - The Discord user ID.
* @param {string} category - The Last.fm category to play.
* @param {object} [options={}] - Additional options.
* @param {string} [options.resolveProvider="yt"] - Provider to resolve tracks with.
* @param {string} [options.playlistId] - Playlist number for playlist category.
* @returns {Promise<void>}
*/
export async function playLastFmCategory(ctx, msg, userId, category, options = {}) {
@@ -267,8 +303,11 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
}
/**
* Parse "playlist N" from message text after "play" keyword.
* @returns {{ category: string, playlistId?: string|number }}
* Parse play subcommand arguments for category and provider.
* @private
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data.
* @returns {{ category: string, resolveProvider?: string, playlistId?: string, showAllCategories?: boolean, invalidCategory?: string }} Parsed args.
*/
function parsePlayArgs(msg, data) {
let raw = data.get("token")?.value;
@@ -337,9 +376,11 @@ function parsePlayArgs(msg, data) {
}
/**
* Execute the lastfm command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the lastfm command.
* Routes to the appropriate subcommand based on the action option.
*
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing action, user, and token options.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
@@ -2458,6 +2499,16 @@ export async function run(msg, data) {
}
}
/**
* Build an embed listing tracks with optional playcount.
* @private
* @param {string} username - The Last.fm username.
* @param {string} title - The list title.
* @param {object[]} tracks - Array of track objects with name, artist, url, and optional playcount.
* @param {boolean} [showPlaycount=false] - Whether to show play counts.
* @param {string} [prefix="%"] - The command prefix for the footer hint.
* @returns {EmbedBuilder} The constructed embed.
*/
function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") {
const lines = tracks.map((t, i) => {
const num = String(i + 1).padStart(2, " ");
@@ -2477,6 +2528,14 @@ function buildTrackList(username, title, tracks, showPlaycount = false, prefix =
.setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` });
}
/**
* Build a scrobble leaderboard embed for a given page.
* @private
* @param {object} lb - Leaderboard data with entries and perPage.
* @param {number} pageIdx - The page index (0-based).
* @param {string} prefix - The command prefix for the footer hint.
* @returns {EmbedBuilder} The constructed embed.
*/
function buildLeaderboardEmbed(lb, pageIdx, prefix) {
const MEDALS = ["🥇", "🥈", "🥉"];
const startRank = pageIdx * lb.perPage;
@@ -2499,9 +2558,10 @@ function buildLeaderboardEmbed(lb, pageIdx, prefix) {
}
/**
* Format seconds into mm:ss or h:mm:ss.
* @param {number} seconds
* @returns {string}
* Format seconds into a human-readable duration string (h:mm:ss or m:ss).
* @private
* @param {number} seconds - Duration in seconds.
* @returns {string} Formatted duration, or empty string if invalid.
*/
function formatDuration(seconds) {
if (!seconds || seconds <= 0) return "";
+29 -31
View File
@@ -1,13 +1,14 @@
/**
* @file leave.mjs — Leave the current voice channel and stop playback
* @module commands.leave
* @module commands/leave
* @description Make the bot leave a voice channel, with 24/7 cleanup and player destruction.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { logger } from "../src/constants/Logger.mjs";
import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs";
import { get247ChannelMode } from "../src/constants/Helpers247.mjs";
/** @type {CommandBuilder} @description Command definition for the leave/stop command. */
export const command = new CommandBuilder()
.setName("leave")
.setDescription("Make the bot leave a voice channel", "commands.leave")
@@ -20,6 +21,13 @@ export const command = new CommandBuilder()
);
/**
* Resolve the guild ID from a player, its map key, or the channel object.
* @param {Player} player - The player instance.
* @param {string} mapKey - The key under which the player is stored in playerMap.
* @param {import('@fluxerjs/core').Client} client - The Discord/Fluxer client.
* @returns {string} Cleaned guild ID, or empty string if unresolvable.
*/
function resolvePlayerGuildId(player, mapKey, client) {
const direct = cleanId(player?._guildId);
if (direct) return direct;
@@ -30,9 +38,11 @@ function resolvePlayerGuildId(player, mapKey, client) {
}
/**
* Execute the leave command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the leave/stop command.
* Finds the target player, removes 24/7 if enabled, destroys the player,
* and sends a confirmation message.
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing option values.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
@@ -67,7 +77,7 @@ export async function run(msg, data) {
}
const channelList = guildPlayers.map(([mapKey, p]) => {
const id = cleanId(p._channelId ?? mapKey);
return id ? `<#${id}>` : "`unknown`";
return id ? `<#${id}>` : "\`unknown\`";
});
return msg.reply(
this.t(msg, "responses.leave.specifyChannel", {
@@ -89,7 +99,7 @@ export async function run(msg, data) {
}
const channelList = guildPlayers.map(([mapKey, p]) => {
const id = cleanId(p._channelId ?? mapKey);
return id ? `<#${id}>` : "`unknown`";
return id ? `<#${id}>` : "\`unknown\`";
});
return msg.reply(
this.t(msg, "responses.leave.noPlayerInChannel", {
@@ -104,6 +114,8 @@ export async function run(msg, data) {
const activeChannelId = cleanId(player._channelId) || targetChannelId;
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
// If this channel has 24/7 enabled, remove it from the saved list first.
// This prevents the disconnect handler from scheduling an auto-rejoin loop.
const set = this.getSettings(msg);
const raw = set?.get("stay_247");
const ch247 = (!raw || raw === "none")
@@ -112,15 +124,15 @@ export async function run(msg, data) {
? new Set(raw.map(id => cleanId(id)).filter(Boolean))
: new Set([cleanId(raw)]);
const is247 = ch247.has(activeChannelId) || ch247.has(homeChannelId);
const was247 = ch247.has(activeChannelId) || ch247.has(homeChannelId);
if (is247) {
const matchChannel = ch247.has(homeChannelId) ? homeChannelId
: ch247.has(activeChannelId) ? activeChannelId
: null;
const mode = matchChannel ? get247ChannelMode(set, matchChannel) : "off";
const prefix = this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id);
if (was247) {
const target = ch247.has(activeChannelId) ? activeChannelId : homeChannelId;
ch247.delete(target);
set.set("stay_247", ch247.size > 0 ? [...ch247] : "none");
}
// Mark as intentional leave so the disconnect handler doesn't also try to rejoin
this.markIntentionalLeave(activeChannelId);
this.players.playerMap.delete(activeChannelId);
this.players._unindexPlayer(player._guildId, activeChannelId);
@@ -136,20 +148,6 @@ export async function run(msg, data) {
await player.leave().catch(() => {});
player.destroy();
if (mode === "auto") {
msg.reply(this.t(msg, "responses.leave.leftRejoin247", { channel: targetChannelId, prefix }));
const rejoinDelay = this.config?.timers?.leave247RejoinDelay ?? 5000;
setTimeout(() => {
if (this._spawnPlayer) {
this._spawnPlayer(guildId, homeChannelId).catch(e =>
logger.warn("[leave] 247 rejoin failed for", homeChannelId, e.message)
);
}
}, rejoinDelay);
} else {
msg.reply(this.t(msg, "responses.leave.left247On", { prefix }));
}
} else {
await this.leaveChannel(activeChannelId, guildId, msg);
}
const label247 = was247 ? " 24/7 disabled." : "";
msg.reply(this.t(msg, "responses.leave.left") + label247);
}
+11 -5
View File
@@ -1,6 +1,6 @@
/**
* @file list.mjs — Display the current song queue with pagination
* @module commands.list
* @module commands/list
* @description List the songs in the queue of the current voice channel with pagination.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,6 +10,10 @@ import { EmbedBuilder } from "@fluxerjs/core";
const PAGE_SIZE = 10;
const SESSION_MS = 30 * 1000;
/**
* @type {CommandBuilder}
* @description Command definition for the list (queue) command.
*/
export const command = new CommandBuilder()
.setName("list")
.setDescription("List the songs in the queue of your current voice channel.", "commands.list")
@@ -22,9 +26,11 @@ export const command = new CommandBuilder()
);
/**
* Execute the list command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the list command.
* Displays the current queue with pagination, showing now-playing info and track list.
*
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing the page option.
* @returns {Promise<void>}
*/
export async function run(message, data) {
+8 -5
View File
@@ -1,12 +1,13 @@
/**
* @file loop.mjs — Toggle loop mode for the queue or current track
* @module commands.loop
* @module commands/loop
* @description Toggle looping of the current song or the entire queue.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the loop command. */
export const command = new CommandBuilder()
.setName("loop")
.setDescription("Toggle the looping of your queue/song.", "commands.loop")
@@ -18,9 +19,11 @@ export const command = new CommandBuilder()
.setRequired(true));
/**
* Execute the loop command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the loop command.
* Toggles loop mode for the queue or the current song.
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing the loop type option.
* @returns {Promise<void>}
*/
export async function run(message, data) {
+27 -4
View File
@@ -1,6 +1,6 @@
/**
* @file lyrics.mjs — Fetch and display lyrics for the current or specified song
* @module commands.lyrics
* @module commands/lyrics
* @description Display synced or unsynced lyrics for the currently playing track from NodeLink.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,18 +10,24 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { Utils } from "../src/Utils.mjs";
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
/** @type {CommandBuilder} @description Command definition for the lyrics command. */
export const command = new CommandBuilder()
.setName("lyrics")
.setDescription("Display synced lyrics from NodeLink", "commands.lyrics")
.addAliases("lyric", "ly")
.setCategory("music");
/** @private @type {string[]} Loading animation frames. */
const LOADING_FRAMES = ["◐", "◓", "◑", "◒"];
/** @private @type {number} Session timeout in milliseconds (3 minutes). */
const SESSION_MS = 180_000;
/**
* Execute the lyrics command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @async
* Run handler for the lyrics command.
* Fetches lyrics for the currently playing track and displays them with
* paginated embeds and reaction-based navigation.
* @param {object} message - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(message) {
@@ -126,6 +132,13 @@ export async function run(message) {
let currentPage = 0;
let emojiRemoveTimeout;
/**
* @private
* Build the embed payload for a specific lyrics page.
* @param {number} pageIdx - Zero-based page index.
* @param {boolean} [expired=false] - Whether navigation controls have expired.
* @returns {object} Embed payload for message reply/edit.
*/
const buildContent = (pageIdx, expired = false) => {
const headerLine = `by *${artist}*${syncIndicator} • Page ${pageIdx + 1}/${totalPages}`;
const descBody = pages[pageIdx];
@@ -150,6 +163,11 @@ export async function run(message) {
await msg.message.react(emoji).catch(() => {});
}
/**
* @private
* Remove all navigation reactions from the lyrics message.
* @returns {Promise<void>}
*/
const clearReactions = async () => {
try {
await msg.message.removeAllReactions();
@@ -160,6 +178,11 @@ export async function run(message) {
}
};
/**
* @private
* Reset the emoji removal timeout timer for the lyrics session.
* @returns {void}
*/
const resetEmojiTimer = () => {
clearTimeout(emojiRemoveTimeout);
emojiRemoveTimeout = setTimeout(async () => {
+8 -5
View File
@@ -1,10 +1,11 @@
/**
* @file move.mjs — Move a track from one position to another in the queue
* @module commands.move
* @module commands/move
* @description Move a track from one position to another in the queue.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the move command. */
export const command = new CommandBuilder()
.setName("move")
.setDescription("Move a track from one position to another in the queue.", "commands.move")
@@ -22,9 +23,11 @@ export const command = new CommandBuilder()
);
/**
* Execute the move command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the move command.
* Moves a track in the queue from one position to another.
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing from/to positions.
* @returns {Promise<void>}
*/
export async function run(message, data) {
+9 -5
View File
@@ -1,20 +1,24 @@
/**
* @file np.mjs — Show now-playing information for the current track
* @module commands.np
* @module commands/np
* @description Display the currently playing track name and URL.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the np (now playing) command. */
export const command = new CommandBuilder()
.setName("np")
.setDescription("Request the name and url of the currently playing song.", "commands.np")
.addAliases("current", "nowplaying");
.addAliases("current", "nowplaying")
.setCategory("music");
/**
* Execute the np command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @async
* Run handler for the np command.
* Fetches and displays the now-playing status with track title and thumbnail.
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(msg) {
+7 -4
View File
@@ -1,20 +1,23 @@
/**
* @file pause.mjs — Pause the current playback
* @module commands.pause
* @module commands/pause
* @description Pause the currently playing track.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the pause command. */
export const command = new CommandBuilder()
.setName("pause")
.setDescription("Pause the playback in your voice channel", "commands.pause")
.setCategory("music");
/**
* Execute the pause command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @async
* Run handler for the pause command.
* Pauses playback in the user's voice channel.
* @param {object} message - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(message) {
+23 -8
View File
@@ -1,6 +1,7 @@
/**
* @file play.mjs — Play a song, playlist, or Last.fm URL — the main music command with provider selection
* @module commands.play
* @module commands/play
* @description Play a song or playlist from a URL or search query.
* Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and Last.fm integration.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -15,9 +16,10 @@ import { ERROR_COLOR } from "../src/constants/UI.mjs";
const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
/**
* Parse a lastfm query like "td:top", "sp:loved", "playlist 1", or just "top".
* Returns { category, resolveProvider } where resolveProvider is the
* search provider to use for resolving tracks (e.g. "td" for Tidal).
* Parse a Last.fm sub-provider string (e.g. "lf:loved", "sp:top").
* @private
* @param {string} query - The raw query string to parse.
* @returns {{ category: string, resolveProvider: string|null, invalidCategory?: string }} Parsed components.
*/
function parseLastFmSubProvider(query) {
const value = query.trim();
@@ -61,6 +63,13 @@ function parseLastFmSubProvider(query) {
}
/**
* Parse a Last.fm track query into artist and name components.
* Supports "title by artist" and "artist - title" formats.
* @private
* @param {string} raw - The raw query string.
* @returns {{ artist: string, name: string, source: string }|null} Parsed track info or null.
*/
function parseLastFmTrackQuery(raw) {
const value = String(raw ?? "").trim();
if (!value) return null;
@@ -86,6 +95,10 @@ function parseLastFmTrackQuery(raw) {
return null;
}
/**
* @type {CommandBuilder}
* @description Command definition for the play command.
*/
export const command = new CommandBuilder()
.setName("play")
.setId("play")
@@ -125,9 +138,11 @@ export const command = new CommandBuilder()
.addAlias("p");
/**
* Execute the play command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the play command.
* Handles URL detection, Last.fm integration, provider selection, and track searching.
*
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing query and provider options.
* @returns {Promise<void>}
*/
export async function run(message, data) {
+53 -5
View File
@@ -1,6 +1,7 @@
/**
* @file player.mjs — Interactive player control panel with playback buttons and now-playing display
* @module commands.player
* @module commands/player
* @description Create an interactive player control panel with live progress, reaction controls,
* and embedded lyrics viewer.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,11 +11,13 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the player command. */
export const command = new CommandBuilder()
.setName("player")
.setDescription("Create an interactive player control panel with live progress", "commands.player")
.setCategory("music");
/** @private @type {Object.<string, string>} Emoji indicators for player states. */
const STATES = {
playing: "🎵",
paused: "⏸️",
@@ -22,6 +25,7 @@ const STATES = {
loading: "⏳"
};
/** @private @type {Object.<string, {emoji: string, action: string, desc: string}>} Available control button definitions. */
const CONTROLS = {
prev: { emoji: "⏮️", action: "previous", desc: "Previous" },
play: { emoji: "▶️", action: "resume", desc: "Play" },
@@ -37,6 +41,7 @@ const CONTROLS = {
close: { emoji: "❌", action: "close", desc: "Close" }
};
/** @private @type {Object.<string, string>} Progress bar character set. */
const PROGRESS = {
filled: "▰",
empty: "▱",
@@ -47,8 +52,11 @@ const PROGRESS = {
/**
* Execute the player command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @async
* Run handler for the player command.
* Creates an interactive embed panel with playback controls, progress bar,
* volume display, and an embedded lyrics viewer.
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(msg) {
@@ -65,6 +73,12 @@ export async function run(msg) {
const allControls = controlsLayout.flat();
const controlEmojis = allControls.map(c => c.emoji);
/**
* @private
* Build the player panel embed with current state, progress, volume, and loop info.
* @param {object} [state={}] - Optional state override with a message field.
* @returns {EmbedBuilder} The constructed embed builder.
*/
const buildEmbed = (state = {}) => {
const current = player.queue.getCurrent();
const isPlaying = !player.paused && current;
@@ -162,6 +176,11 @@ export async function run(msg) {
let lyricsUnobserve = null;
let lyricsEmojiTimeout = null;
/**
* @private
* Remove all control reactions from the player panel message.
* @returns {Promise<void>}
*/
const clearReactions = async () => {
try {
await message.message.removeAllReactions();
@@ -174,6 +193,11 @@ export async function run(msg) {
}
};
/**
* @private
* Reset the emoji removal timeout for the player panel controls.
* @returns {void}
*/
const resetEmojiTimer = () => {
clearTimeout(emojiRemoveTimeout);
emojiRemoveTimeout = setTimeout(async () => {
@@ -184,6 +208,12 @@ export async function run(msg) {
}, EMOJI_REMOVE_TIMEOUT);
};
/**
* @private
* Remove navigation reactions from a lyrics message.
* @param {object} lyricsMsg - The wrapped lyrics message with a .message property.
* @returns {Promise<void>}
*/
const clearLyricsReactions = async (lyricsMsg) => {
if (!lyricsMsg?.message) return;
try {
@@ -197,6 +227,12 @@ export async function run(msg) {
}
};
/**
* @private
* Rebuild and edit the player panel embed with updated state.
* @param {object} [extra={}] - Additional state data to merge (e.g. status message).
* @returns {void}
*/
const refresh = (extra = {}) => {
const embed = buildEmbed(extra);
message.edit({ embeds: [embed] }).catch(() => {});
@@ -205,6 +241,14 @@ export async function run(msg) {
let _sessionClosed = false;
/**
* @private
* @async
* Tear down the entire player session: clear timers, remove listeners,
* clean up reactions, and edit the embed to show the closed state.
* @param {string} [reason="timeout"] - The reason for closing ("timeout", "user", "disconnected").
* @returns {Promise<void>}
*/
const closeSession = async (reason = "timeout") => {
if (_sessionClosed) return;
_sessionClosed = true;
@@ -245,6 +289,11 @@ export async function run(msg) {
}).catch(() => {});
};
/**
* @private
* Reset the session inactivity timeout timer.
* @returns {void}
*/
const resetTimeout = () => {
clearTimeout(sessionTimeout);
sessionTimeout = setTimeout(() => closeSession("timeout"), timeout);
@@ -315,7 +364,6 @@ export async function run(msg) {
break;
case "stop":
await player._stopMediaPlayer();
player.queue.reset();
reply = this.t(msg, "responses.player.stoppedCleared");
break;
+12 -5
View File
@@ -1,6 +1,7 @@
/**
* @file playnext.mjs — Add a song to the top of the queue (play next)
* @module commands.playnext
* @module commands/playnext
* @description Play a song and insert it at the top of the queue instead of the end.
* Supports inline provider prefixes and flag-based provider selection.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,6 +10,10 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the playnext command.
*/
export const command = new CommandBuilder()
.setName("playnext")
.setId("playnext")
@@ -34,9 +39,11 @@ export const command = new CommandBuilder()
.addAlias("pn");
/**
* Execute the playnext command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the playnext command.
* Searches for a track and adds the result to the top of the queue.
*
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing query and provider options.
* @returns {Promise<void>}
*/
export async function run(message, data) {
+21 -5
View File
@@ -1,6 +1,6 @@
/**
* @file radio.mjs — Play a radio stream or search for radio stations
* @module commands.radio
* @module commands/radio
* @description Play internet radio stations with interactive station selection via reactions.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,6 +10,10 @@ import { logger } from "../src/constants/Logger.mjs";
import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/constants/UI.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the radio command. Returns null if no stations configured.
*/
export const command = function() {
if (!this.config.radio?.length) return null;
return new CommandBuilder()
@@ -25,9 +29,11 @@ export const command = function() {
};
/**
* Execute the radio command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the radio command.
* Lists stations, plays a named station, or starts the default station.
*
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the station option.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
@@ -131,6 +137,16 @@ export async function run(msg, data) {
return playStation(this, msg, radios[0]);
}
/**
* Play a radio station on the player, switching if one is already playing.
* @private
* @async
* @param {object} ctx - The bot (Remix) instance context.
* @param {object} msg - The command message wrapper.
* @param {object} radio - The radio station config object.
* @param {object|null} [editTarget=null] - Optional message to edit instead of sending a new reply.
* @returns {Promise<void>}
*/
async function playStation(ctx, msg, radio, editTarget = null) {
const p = await ctx.getPlayer(msg, true, true, true);
if (!p) return;
+55 -5
View File
@@ -1,6 +1,6 @@
/**
* @file reload.mjs — Hot-reload commands without restarting the bot (owner-only)
* @module commands.reload
* @module commands/reload
* @description Owner-only command to hot-reload commands, source modules, or audio modules at runtime.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,6 +10,10 @@ import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
/**
* @type {CommandBuilder}
* @description Command definition for the reload command (owner-only).
*/
export const command = new CommandBuilder()
.setName("reload")
.setDescription("Reload commands, src modules, or audio modules. Leave blank to see all targets.")
@@ -25,6 +29,15 @@ export const command = new CommandBuilder()
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const ROOT = path.resolve(__dirname, "..");
/**
* Reload a single command by name, removing the old one and re-importing its file.
* @private
* @async
* @param {object} ctx - The bot (Remix) instance context.
* @param {object} msg - The command message wrapper.
* @param {string} name - The command name to reload.
* @returns {Promise<{ ok: boolean, msg: string }>} Result with success status and message.
*/
async function reloadCommand(ctx, msg, name) {
if (name === "index")
return { ok: false, msg: ctx.t(msg, "responses.reload.indexNoReload") };
@@ -61,6 +74,16 @@ async function reloadCommand(ctx, msg, name) {
return { ok: true, msg: ctx.t(msg, "responses.reload.reloaded", { name }) };
}
/**
* Reload a single source module by re-importing its file.
* @private
* @async
* @param {object} ctx - The bot (Remix) instance context.
* @param {object} msg - The command message wrapper.
* @param {string} filePath - Absolute path to the module file.
* @param {string} label - Human-readable label for error messages.
* @returns {Promise<{ ok: boolean, msg: string }>} Result with success status and message.
*/
async function reloadModule(ctx, msg, filePath, label) {
if (!fs.existsSync(filePath))
return { ok: false, msg: ctx.t(msg, "responses.reload.fileNotFound", { label }) };
@@ -72,6 +95,12 @@ async function reloadModule(ctx, msg, filePath, label) {
}
}
/**
* List all JS/MJS module files in a subdirectory.
* @private
* @param {string} subdir - The subdirectory name relative to project root.
* @returns {Array<{ file: string, label: string }>} Array of file info objects.
*/
function allModuleFiles(subdir) {
const dir = path.join(ROOT, subdir);
if (!fs.existsSync(dir)) return [];
@@ -80,6 +109,16 @@ function allModuleFiles(subdir) {
.map(f => ({ file: path.join(dir, f), label: `${subdir}/${f}` }));
}
/**
* Display lines in a paginated embed with arrow navigation.
* @private
* @async
* @param {object} msg - The command message wrapper.
* @param {string} title - The embed title.
* @param {string[]} lines - The lines of text to paginate.
* @param {number} [pageSize=14] - Number of lines per page.
* @returns {Promise<void>}
*/
async function showPaged(msg, title, lines, pageSize = 14) {
const pages = [];
for (let i = 0; i < lines.length; i += pageSize)
@@ -115,6 +154,15 @@ async function showPaged(msg, title, lines, pageSize = 14) {
setTimeout(() => { unsub?.(); }, 5 * 60_000);
}
/**
* Display reload results in a paginated embed.
* @private
* @async
* @param {object} msg - The command message wrapper.
* @param {object[]} results - Array of { ok, msg } result objects.
* @param {string} label - Category label for the title.
* @returns {Promise<void>}
*/
async function showResults(msg, results, label) {
const ok = results.filter(r => r.ok).length;
const bad = results.filter(r => !r.ok).length;
@@ -123,9 +171,11 @@ async function showResults(msg, results, label) {
}
/**
* Execute the reload command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the reload command.
* Reloads commands, src modules, or audio modules based on the target option.
*
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the target option.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
+8 -5
View File
@@ -1,10 +1,11 @@
/**
* @file remove.mjs — Remove a specific song from the queue by position
* @module commands.remove
* @module commands/remove
* @description Remove a specific track from the queue by its position.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the remove command. */
export const command = new CommandBuilder()
.setName("remove")
.setDescription("Remove a specific song from the queue.", "commands.remove")
@@ -15,9 +16,11 @@ export const command = new CommandBuilder()
.setRequired(true));
/**
* Execute the remove command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the remove command.
* Removes a track at the specified 1-based index from the queue.
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing the index option.
* @returns {Promise<void>}
*/
export async function run(message, data) {
+10 -4
View File
@@ -1,20 +1,26 @@
/**
* @file resume.mjs — Resume paused playback
* @module commands.resume
* @module commands/resume
* @description Resume paused playback in the current voice channel.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the resume command.
*/
export const command = new CommandBuilder()
.setName("resume")
.setDescription("Resume the playback in your voice channel", "commands.resume")
.setCategory("music");
/**
* Execute the resume command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* Run handler for the resume command.
* Resumes playback and sends a confirmation embed.
*
* @param {object} message - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(message) {
+20 -9
View File
@@ -1,6 +1,6 @@
/**
* @file search.mjs — Search for songs with interactive selection menu
* @module commands.search
* @module commands/search
* @description Search for tracks across providers and pick one to play via reaction selection.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,6 +10,7 @@ import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/co
import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/constants/UI.mjs";
import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the search command. */
export const command = new CommandBuilder()
.setName("search")
.setDescription(
@@ -37,9 +38,12 @@ export const command = new CommandBuilder()
);
/**
* Execute the search command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the search command.
* Searches for tracks, displays results as an embed with number reactions,
* and adds the selected track to the queue.
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing provider and query options.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
@@ -57,10 +61,12 @@ export async function run(msg, data) {
if (!channel?.send) return;
/**
* Build a search-result embed using EmbedBuilder.
* @param {string} description
* @param {string} [footerText]
* @param {string} [authorLabel] - defaults to `name` (provider name)
* @private
* Build a search result embed.
* @param {string} description - The embed description text.
* @param {string|null} footerText - Optional footer text.
* @param {string} [authorLabel=name] - The author field label (provider name).
* @returns {EmbedBuilder} The constructed embed.
*/
const makeEmbed = (description, footerText, authorLabel = name) => {
const b = new EmbedBuilder()
@@ -113,6 +119,11 @@ export async function run(msg, data) {
const channelId = rawMsg.channelId ?? rawMsg.channel_id ?? rawMsg.channel?.id;
const msgId = rawMsg.id;
/**
* @private
* Remove all reactions from the search result message.
* @returns {Promise<void>}
*/
const clearReactions = async () => {
try {
await rawMsg.removeAllReactions();
+8 -5
View File
@@ -1,6 +1,6 @@
/**
* @file seek.mjs — Seek to a specific position in the current track
* @module commands.seek
* @module commands/seek
* @description Seek to a specific position in the currently playing track.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,6 +9,7 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { Utils } from "../src/Utils.mjs";
import { ERROR_COLOR } from "../src/constants/UI.mjs";
/** @type {CommandBuilder} @description Command definition for the seek command. */
export const command = new CommandBuilder()
.setName("seek")
.setDescription("Seek to a specific position in the current track.", "commands.seek")
@@ -20,9 +21,11 @@ export const command = new CommandBuilder()
);
/**
* Execute the seek command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the seek command.
* Parses a duration string and seeks the player to that position.
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the position option.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
+24 -4
View File
@@ -1,6 +1,6 @@
/**
* @file servers.mjs — List servers the bot is currently in (owner-only)
* @module commands.servers
* @module commands/servers
* @description Owner-only command to list all servers the bot is in with pagination.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,6 +9,7 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the servers command (owner-only). */
export const command = new CommandBuilder()
.setName("servers")
.setDescription("Fetch a list of servers the bot is in")
@@ -17,8 +18,10 @@ export const command = new CommandBuilder()
/**
* Execute the servers command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @async
* Run handler for the servers command.
* Lists all guilds the bot is a member of, with paginated embed and reaction navigation.
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(msg) {
@@ -60,6 +63,13 @@ export async function run(msg) {
let currentPage = 0;
/**
* @private
* Build the embed payload for a specific page of the server list.
* @param {number} pageIdx - Zero-based page index.
* @param {boolean} [expired=false] - Whether the reaction controls have expired.
* @returns {object} Embed payload for message reply/edit.
*/
const buildPageContent = (pageIdx, expired = false) => {
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
@@ -90,6 +100,11 @@ export async function run(msg) {
await replyMsg.message.react(emoji).catch(() => {});
}
/**
* @private
* Remove all navigation reactions from the reply message.
* @returns {Promise<void>}
*/
const clearReactions = async () => {
try {
await replyMsg.message.removeAllReactions();
@@ -102,6 +117,11 @@ export async function run(msg) {
}
};
/**
* @private
* Reset the emoji removal timeout timer.
* @returns {void}
*/
const resetTimer = () => {
clearTimeout(emojiTimeout);
emojiTimeout = setTimeout(async () => {
+328 -410
View File
@@ -1,6 +1,6 @@
/**
* @file settings.mjs — Configure server settings — prefix, volume, 24/7 mode, DJ role, locale, and more
* @module commands.settings
* @module commands/settings
* @description Server settings management with subcommands (get/set/reset/help) and shortcut aliases (prefix, 247).
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -8,70 +8,51 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs";
import { logger } from "../src/constants/Logger.mjs";
import runnables from "../settings/runnables.mjs";
import { get247ChannelMode, set247ChannelMode, remove247ChannelMode } from "../src/constants/Helpers247.mjs";
function embed(desc, opts = {}) {
const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
if (opts.title) b.setTitle(opts.title);
if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL });
return { embeds: [b] };
}
/**
* Build a rich embed with fields for the 24/7 status panel.
* Instead of using the standard addField API, we build the base embed with
* EmbedBuilder, call .toJSON() to get the raw object, then attach a `fields`
* array directly.
* Command alias to setting key mapping.
* @type {Object.<string, string>}
*/
function richEmbed(fields, opts = {}) {
const b = new EmbedBuilder().setColor(getGlobalColor());
if (opts.title) b.setTitle(opts.title);
if (opts.description) b.setDescription(opts.description);
if (opts.footer) b.setFooter({ text: opts.footer });
if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL });
const raw = b.toJSON();
raw.fields = fields.map(f => ({
name: f.name,
value: f.value,
inline: f.inline ?? false,
}));
return { embeds: [raw] };
}
const SHORTCUTS = {
prefix: "prefix",
pfx: "prefix",
"247": "stay_247",
};
/** Aliases accepted for boolean settings */
/** @private @type {Set<string>} Strings that evaluate to boolean true. */
const BOOL_TRUE = new Set(["true", "1", "yes", "on", "enable", "enabled"]);
/** @private @type {Set<string>} Strings that evaluate to boolean false. */
const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]);
/** Settings whose values should be displayed as booleans */
/** @private @type {Set<string>} Setting keys that use boolean display formatting. */
const BOOL_SETTINGS = new Set(["songAnnouncements"]);
/** Valid locale codes — populated from Locale instance at runtime */
/** @private @type {Set<string>} Available locale codes, populated at load time. */
let VALID_LOCALES = new Set(["en"]);
/** Volume constraints */
/** @private @type {number} Minimum allowed volume value. */
const VOLUME_MIN = 1;
/** @private @type {number} Maximum allowed volume value. */
const VOLUME_MAX = 200;
const MAX_247_CHANNELS = 10;
/** @private @type {number} Maximum prefix length in characters. */
const PREFIX_MAX = 5;
/** @private @type {number} Maximum number of 24/7 channels per guild. */
const MAX_247_CHANNELS = 1;
/**
* Validate that a value looks like a real Fluxer ID.
* Fluxer IDs are large numeric snowflakes (typically 17-20 digits).
* We accept >= 15 digits to be safe, but reject anything shorter
* (which would be garbage like "3", "42", "move", etc.).
* Check whether a string looks like a valid Fluxer ID (Snowflake-like).
* @param {string} id - The ID to validate.
* @returns {boolean} True if the ID is 15-22 characters after cleaning.
*/
function isValidFluxerId(id) {
const cleaned = cleanId(id);
return cleaned.length >= 15 && cleaned.length <= 22;
}
/** Parse "true/false" and their aliases → boolean | null */
/**
* Parse a string into a boolean, or return null if unrecognised.
* @param {string} str - The string to parse.
* @returns {boolean|null} True, false, or null if not a boolean string.
*/
function parseBool(str) {
const s = String(str).toLowerCase().trim();
if (BOOL_TRUE.has(s)) return true;
@@ -79,19 +60,48 @@ function parseBool(str) {
return null;
}
/** Format a setting value for display */
/**
* Format a setting value for display in embed messages.
* @param {string} key - The setting key.
* @param {*} value - The setting value.
* @returns {string} Formatted display string.
*/
function displayValue(key, value) {
if (BOOL_SETTINGS.has(key)) return value ? "✅ enabled" : "❌ disabled";
if (BOOL_SETTINGS.has(key)) return value ? "\u2705 enabled" : "\u274c disabled";
if (value === null || value === undefined || value === "none") return "none";
return `\`${value}\``;
return "`" + value + "`";
}
/** Resolve guild name from a message context */
/**
* @private
* Get the display name of the guild from a message object.
* @param {object} message - The command message wrapper.
* @returns {string} The guild name, or a fallback string.
*/
function getGuildName(message) {
return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server";
}
/**
* @private
* Create a simple embed payload with global color, description, and optional title/footer.
* @param {string} desc - The embed description text.
* @param {object} [opts={}] - Optional overrides for title, iconURL, and footer.
* @returns {object} Embed payload for message.reply().
*/
function embed(desc, opts = {}) {
const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
if (opts.title) b.setTitle(opts.title);
if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL });
if (opts.footer) b.setFooter({ text: opts.footer });
return { embeds: [b] };
}
/**
* Parse the stay_247 setting into a Set of validated channel IDs.
* @param {ServerSettings} set - The guild settings instance.
* @returns {Set<string>} Set of cleaned, valid channel IDs.
*/
function get247Channels(set) {
const raw = set.get("stay_247");
if (!raw || raw === "none") return new Set();
@@ -105,218 +115,52 @@ function get247Channels(set) {
return new Set();
}
/**
* Save a Set of channel IDs back to the stay_247 setting.
* Writes 'none' if the set is empty.
* @param {ServerSettings} set - The guild settings instance.
* @param {Set<string>} channels - The channel IDs to save.
*/
function save247Channels(set, channels) {
const arr = [...channels].filter(id => id && isValidFluxerId(id));
set.set("stay_247", arr.length > 0 ? arr : "none");
}
function modeLabel(mode, t, guildId) {
if (t && guildId) {
if (mode === "auto") return t(guildId, "responses.settings.247Panel.modeAuto");
if (mode === "on") return t(guildId, "responses.settings.247Panel.modeOn");
return t(guildId, "responses.settings.247Panel.modeOff");
}
return mode === "auto" ? "🔄 Auto" : mode === "on" ? "✅ On" : "❌ Off";
}
function modeEmoji(mode) {
return mode === "auto" ? "🔄" : mode === "on" ? "✅" : "❌";
}
function modeColor(mode) {
return mode === "auto" ? 0xF59E0B : mode === "on" ? 0x10B981 : 0xEF4444;
}
/** Resolve a channel name from cache, falling back to mention */
/**
* @private
* Resolve a channel ID to a human-readable channel name from the client cache.
* @param {import('@fluxerjs/core').Client} client - The Discord/Fluxer client.
* @param {string} channelId - The channel ID to look up.
* @returns {string|null} The channel name, or null if not found.
*/
function resolveChannelName(client, channelId) {
try {
const ch = client?.channels?.get?.(channelId);
if (ch?.name) return ch.name;
} catch(e) { logger.warn("[Settings] Error:", e?.message); }
} catch (_) {}
return null;
}
/**
* Build a simple 24/7 status panel.
* Shows each saved channel with its mode — clean and minimal.
* @param {object} set - ServerSettings
* @param {object} ctx - Bot context (Remix instance)
* @param {object} message - Message object
* @param {Function} [t] - Locale translate function (guildId, key, data)
* @param {string} [guildId] - Guild ID for locale
* @private
* Create a translation function bound to the given context and guild.
* @param {object} ctx - The bot (Remix) context.
* @param {string} guildId - The guild ID for localization.
* @returns {Function} A translation function with signature (key, data?) => string.
*/
function build247StatusPanel(set, ctx, message, t, guildId) {
const channels = [...get247Channels(set)];
const prefix = ctx.handler.getPrefix(guildId);
const locale = (key, data = {}) => t ? t(guildId, key, { ...data, prefix }) : key;
if (channels.length === 0) {
return richEmbed([
{
name: locale("responses.settings.247Panel.gettingStarted"),
value: locale("responses.settings.247Panel.gettingStartedValue"),
inline: false,
},
], {
title: locale("responses.settings.247Panel.title"),
description: locale("responses.settings.247Panel.noChannelsSaved"),
footer: locale("responses.settings.247Panel.footer"),
});
}
const lines = channels.map(chId => {
const mode = get247ChannelMode(set, chId);
const chName = resolveChannelName(ctx.client, chId);
const label = chName ? `${chName}` : ``;
return `${modeEmoji(mode)} ${label} <#${chId}> — ${modeLabel(mode, t, guildId)}`;
});
const onCount = channels.filter(id => get247ChannelMode(set, id) === "on").length;
const autoCount = channels.filter(id => get247ChannelMode(set, id) === "auto").length;
const summaryParts = [];
if (onCount > 0) summaryParts.push(locale("responses.settings.247Panel.summaryOn", { count: onCount }));
if (autoCount > 0) summaryParts.push(locale("responses.settings.247Panel.summaryAuto", { count: autoCount }));
const channelsKey = channels.length === 1
? "responses.settings.247Panel.channelsSaved_one"
: "responses.settings.247Panel.channelsSaved_other";
return richEmbed([{
name: locale(channelsKey, { count: channels.length }),
value: lines.join("\n"),
inline: false,
}], {
title: locale("responses.settings.247Panel.title"),
description: summaryParts.join(" · "),
footer: locale("responses.settings.247Panel.footer"),
});
function tWrap(ctx, guildId) {
const tFn = ctx.locale?.translate?.bind(ctx.locale);
return (key, data = {}) => tFn ? tFn(guildId, key, data) : key;
}
/**
* Build a simple embed for the %247 on/auto confirmation.
* @param {object} set - ServerSettings
* @param {string} channelId - Clean channel ID
* @param {string} mode - "on" | "auto"
* @param {boolean} joined - Whether the bot joined
* @param {object} ctx - Bot context
* @param {string} guildId - Guild ID
* @param {Function} [t] - Locale translate function
* @private
* Get a human-readable label for a setting key, using locale translations when available.
* @param {string} key - The setting key.
* @param {Function|null} t - Translation function (guildId, key, data) => string.
* @param {string} guildId - The guild ID for localization.
* @returns {string} The pretty-printed setting label.
*/
function build247EnabledPanel(set, channelId, mode, joined, ctx, guildId, t) {
const channels = [...get247Channels(set)];
const modeStr = modeLabel(mode, t, guildId);
const prefix = ctx.handler.getPrefix(guildId);
const locale = (key, data = {}) => t ? t(guildId, key, { ...data, prefix }) : key;
const chName = resolveChannelName(ctx.client, channelId);
const label = chName ? `**${chName}** <#${channelId}>` : `<#${channelId}>`;
const lines = channels.map(id => {
const m = get247ChannelMode(set, id);
const n = resolveChannelName(ctx.client, id);
const l = n ? `${n}` : `<#${id}>`;
const marker = id === channelId ? locale("responses.settings.247Panel.currentMarker") : "";
return `${modeEmoji(m)} ${l} <#${id}> — ${modeLabel(m, t, guildId)}${marker}`;
});
const channelsKey = channels.length === 1
? "responses.settings.247Panel.channelsSaved_one"
: "responses.settings.247Panel.channelsSaved_other";
const summary = locale(channelsKey, { count: channels.length });
const b = new EmbedBuilder();
b.setColor(modeColor(mode));
b.setTitle(locale("responses.settings.247Panel.enabledTitle", { mode: modeStr }));
b.setDescription(locale("responses.settings.247Panel.enabledDescription", { channel: label, mode: modeStr, summary }));
b.setFooter({ text: locale("responses.settings.247Panel.enabledFooter") });
const raw = b.toJSON();
raw.fields = [{
name: locale("responses.settings.247Panel.savedChannels"),
value: lines.join("\n"),
inline: false,
}];
return { embeds: [raw] };
}
/**
* Build a simple embed for the %247 off confirmation.
* @param {object} set - ServerSettings
* @param {string} channelId - Clean channel ID
* @param {string} guildId - Guild ID
* @param {Function} [t] - Locale translate function
*/
function build247DisabledPanel(set, channelId, guildId, t, ctx) {
const channels = [...get247Channels(set)];
const prefix = ctx.handler.getPrefix(guildId);
const locale = (key, data = {}) => t ? t(guildId, key, { ...data, prefix }) : key;
if (channels.length === 0) {
return richEmbed([{
name: locale("responses.settings.247Panel.noChannelsSavedField"),
value: locale("responses.settings.247Panel.allChannelsRemoved"),
inline: false,
}], {
title: locale("responses.settings.247Panel.disabledTitle"),
footer: locale("responses.settings.247Panel.reenableFooter"),
});
}
const lines = channels.map(id => {
const m = get247ChannelMode(set, id);
const l = `<#${id}>`;
return `${modeEmoji(m)} ${l} — ${modeLabel(m, t, guildId)}`;
});
const channelsKey = channels.length === 1
? "responses.settings.247Panel.channelsRemaining_one"
: "responses.settings.247Panel.channelsRemaining_other";
return richEmbed([{
name: locale(channelsKey, { count: channels.length }),
value: lines.join("\n"),
inline: false,
}], {
title: locale("responses.settings.247Panel.disabledTitle"),
description: locale("responses.settings.247Panel.channelRemoved", { channel: channelId }),
footer: locale("responses.settings.247Panel.reenableFooter"),
});
}
function format247Status(set, t, guildId) {
const channels = get247Channels(set);
if (channels.size === 0) return t ? t(guildId, "responses.settings.247Panel.modeOff") : "❌ Disabled";
if (channels.size === 1) {
const chId = [...channels][0];
const mode = get247ChannelMode(set, chId);
return `${modeLabel(mode, t, guildId)} — <#${chId}>`;
}
const parts = [...channels].map(id => {
const mode = get247ChannelMode(set, id);
return `<#${id}> (${modeLabel(mode, t, guildId)})`;
});
return `${channels.size} channels: ${parts.join(", ")}`;
}
function format247Summary(set, t, guildId, ctx) {
const channels = [...get247Channels(set)];
const prefix = ctx.handler.getPrefix(guildId);
const locale = (key, data = {}) => t ? t(guildId, key, { ...data, prefix }) : key;
if (channels.length === 0) {
return [
`**24/7 Mode**`,
`Status: ${locale("responses.settings.247Panel.modeOff")}`,
"Saved channels: none"
].join("\n");
}
const lines = ["**24/7 Mode**"];
for (const id of channels) {
const mode = get247ChannelMode(set, id);
lines.push(`• <#${id}> — ${modeLabel(mode, t, guildId)}`);
}
return lines.join("\n");
}
function prettifySettingLabel(key, t, guildId) {
const localeMap = {
songAnnouncements: "responses.settings.labelSongAnnouncements",
@@ -325,55 +169,68 @@ function prettifySettingLabel(key, t, guildId) {
locale: "responses.settings.labelLocale",
stay_247: "responses.settings.label247",
volume: "responses.settings.labelVolume",
announcementChannelId: "responses.settings.labelAnnouncementChannel",
restrictVolume: "responses.settings.labelRestrictVolume",
autojoin_channel: "responses.settings.labelAutojoinChannel"
};
if (localeMap[key] && t && guildId) return t(guildId, localeMap[key]);
const fallback = {
songAnnouncements: "Song announcements",
prefix: "Prefix",
pfx: "Bot avatar style",
pfp: "Bot avatar style",
locale: "Locale",
stay_247: "24/7 mode",
volume: "Default volume",
announcementChannelId: "Announcement channel",
restrictVolume: "Restrict volume",
autojoin_channel: "Autojoin channel"
};
return fallback[key] ?? key.replace(/_/g, " ");
}
async function handle247(ctx, message, value) {
const set = ctx.getSettings(message);
const guildId = getMessageGuildId(message);
const mode = value.toLowerCase().trim();
/**
* Build an embed payload showing the current 24/7 status for the guild.
* @param {ServerSettings} set - The guild settings instance.
* @param {object} ctx - The bot (Remix) context.
* @param {string} guildId - The guild ID.
* @param {string|null} channelId - The channel ID (for active indicator), or null.
* @returns {object} Embed payload object for message.reply().
*/
function build247Panel(set, ctx, guildId, channelId) {
const channels = [...get247Channels(set)];
const prefix = ctx.handler.getPrefix(guildId);
const resolved = mode === "true" ? "auto" : mode === "false" ? "off" : mode;
if (!["off", "on", "auto"].includes(resolved)) {
return message.reply(embed(
ctx.t(message, "responses.settings.invalid247", { value, prefix: ctx.handler.getPrefix(guildId) })
));
if (channels.length > 0) {
const lines = channels.map(id => {
const name = resolveChannelName(ctx.client, id);
const isActive = id === channelId;
return (isActive ? "\u25b6 " : "\u2022 ") + (name ? "**" + name + "** " : "") + "<#" + id + ">";
});
return embed(
channels.length === 1 && channelId
? "\u2705 24/7 is now **enabled** in <#" + channelId + ">\n\n" +
"The bot will stay connected and auto-rejoin if disconnected."
: "\u2705 24/7 active in " + channels.length + " channel(s):\n\n" + lines.join("\n"),
{ title: "\u2705 24/7 Mode" }
);
}
if (resolved === "off") {
if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer")));
const { channelId } = await ctx.players.checkVoiceChannels(message);
const channels = get247Channels(set);
if (!channelId && channels.size > 1) {
return message.reply(embed(
ctx.t(message, "responses.settings.noVoice247", { mode: "off", prefix: ctx.handler.getPrefix(guildId) })
));
return embed(
"\u274c 24/7 is **disabled**\n\n" +
"The bot will leave voice channels when idle.\n\n" +
"Join a voice channel and use `" + prefix + "247` to enable.",
{ title: "\u274c 24/7 Mode" }
);
}
if (channelId) {
/**
* Disable 24/7 mode for a specific channel.
* Removes the channel from stay_247, marks intentional leave, and destroys the player.
* @param {object} ctx - The bot (Remix) context.
* @param {ServerSettings} set - The guild settings instance.
* @param {string} guildId - The guild ID.
* @param {string} channelId - The channel ID to disable.
* @returns {Promise<void>}
*/
async function disable247(ctx, set, guildId, channelId) {
const id = cleanId(channelId);
const channels = get247Channels(set);
channels.delete(id);
save247Channels(set, channels);
remove247ChannelMode(set, id, channels);
ctx.markIntentionalLeave?.(id);
const player = ctx.players.playerMap.get(id)
?? [...ctx.players.playerMap.values()].find(p =>
@@ -381,92 +238,107 @@ async function handle247(ctx, message, value) {
cleanId(p?._guildId ?? "") === cleanId(guildId)
);
if (player) {
const activeChannelId = cleanId(player._channelId ?? id);
ctx.players.playerMap.delete(activeChannelId);
if (activeChannelId !== id) ctx.players.playerMap.delete(id);
const activeId = cleanId(player._channelId ?? id);
ctx.players.playerMap.delete(activeId);
if (activeId !== id) ctx.players.playerMap.delete(id);
await player.leave().catch(() => {});
player.destroy();
}
const t247 = ctx.locale?.translate?.bind(ctx.locale);
return message.reply(build247DisabledPanel(set, id, guildId, t247, ctx));
}
save247Channels(set, new Set());
set.set("stay_247_mode", "off");
set.set("stay_247_modes", {});
for (const [chId, player] of [...ctx.players.playerMap.entries()]) {
if (cleanId(player?._guildId ?? "") === cleanId(guildId)) {
const activeChannelId = cleanId(player._channelId ?? chId);
ctx.markIntentionalLeave?.(activeChannelId);
ctx.players.playerMap.delete(activeChannelId);
if (activeChannelId !== chId) ctx.players.playerMap.delete(chId);
await player.leave().catch(() => {});
player.destroy();
}
}
const prefix = ctx.handler.getPrefix(guildId);
const t247 = ctx.locale?.translate?.bind(ctx.locale);
const loc = (key, data = {}) => t247 ? t247(guildId, key, { ...data, prefix }) : key;
return message.reply(richEmbed([{
name: loc("responses.settings.247Panel.allChannelsLabel"),
value: loc("responses.settings.247Panel.allChannelsDisabled"),
inline: false,
}], {
title: loc("responses.settings.247Panel.disabledTitle"),
description: loc("responses.settings.247Panel.noChannelsSavedShort"),
footer: loc("responses.settings.247Panel.reenableFooter"),
}));
}
if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer")));
const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message);
if (!userChannelId) {
return message.reply(embed(
ctx.t(message, "responses.settings.noVoice247", { mode: resolved, prefix: ctx.handler.getPrefix(guildId) })
));
}
const id = cleanId(userChannelId);
const channels = get247Channels(set);
if (!channels.has(id) && channels.size >= MAX_247_CHANNELS) {
return message.reply(embed(
ctx.t(message, "responses.settings.max247Channels", { max: MAX_247_CHANNELS, prefix: ctx.handler.getPrefix(guildId) })
));
}
channels.add(id);
set247ChannelMode(set, id, resolved);
save247Channels(set, channels);
const playerExists = ctx.players.playerMap.has(id) ||
[...ctx.players.playerMap.values()].some(p =>
cleanId(p?._channelId ?? "") === id && cleanId(p?._guildId ?? "") === cleanId(guildId)
);
if (playerExists) {
const t247 = ctx.locale?.translate?.bind(ctx.locale);
return message.reply(build247EnabledPanel(set, id, resolved, false, ctx, guildId, t247));
}
try {
await ctx._spawnPlayer(guildId, id);
const t247 = ctx.locale?.translate?.bind(ctx.locale);
return message.reply(build247EnabledPanel(set, id, resolved, true, ctx, guildId, t247));
} catch (e) {
const prefix = ctx.handler.getPrefix(guildId);
const t247 = ctx.locale?.translate?.bind(ctx.locale);
const loc = (key, data = {}) => t247 ? t247(guildId, key, { ...data, prefix }) : key;
return message.reply(embed(
loc("responses.settings.247Panel.joinFailed", { mode: modeLabel(resolved, t247, guildId), channel: id, error: e.message })
));
}
}
/**
* Validate and save a setting value.
* @returns {string|null} Error message string, or null on success.
* For stay_247, replies directly and always returns null.
* Enable 24/7 mode for a specific channel.
* Enforces MAX_247_CHANNELS (1) by disabling any existing 24/7 channel first,
* then saves the new channel and spawns a player if none exists.
* @param {object} ctx - The bot (Remix) context.
* @param {ServerSettings} set - The guild settings instance.
* @param {string} guildId - The guild ID.
* @param {string} channelId - The channel ID to enable.
* @returns {Promise<void>}
*/
async function enable247(ctx, set, guildId, channelId) {
const id = cleanId(channelId);
const channels = get247Channels(set);
if (channels.has(id)) return;
// Platform only supports 1 voice channel per bot per guild.
// If another channel already has 24/7, disable it first.
if (channels.size >= MAX_247_CHANNELS) {
for (const oldId of channels) {
if (oldId !== id) {
ctx.markIntentionalLeave?.(oldId);
const oldPlayer = ctx.players.playerMap.get(oldId)
?? [...ctx.players.playerMap.values()].find(p =>
cleanId(p?._channelId ?? "") === oldId &&
cleanId(p?._guildId ?? "") === cleanId(guildId)
);
if (oldPlayer) {
const activeId = cleanId(oldPlayer._channelId ?? oldId);
ctx.players.playerMap.delete(activeId);
if (activeId !== oldId) ctx.players.playerMap.delete(oldId);
await oldPlayer.leave().catch(() => {});
oldPlayer.destroy();
}
channels.delete(oldId);
}
}
}
channels.add(id);
save247Channels(set, channels);
const playerExists = ctx.players.playerMap.has(id) ||
[...ctx.players.playerMap.values()].some(p =>
cleanId(p?._channelId ?? "") === id && cleanId(p?._guildId ?? "") === cleanId(guildId)
);
if (!playerExists) {
try { await ctx._spawnPlayer(guildId, id); } catch (_) {}
}
}
/**
* Handle the !247 toggle command. If the user is in a 24/7 channel, disable it;
* otherwise, enable it for the user's current voice channel.
* @param {object} ctx - The bot (Remix) context.
* @param {object} message - The command message.
* @param {ServerSettings} set - The guild settings instance.
* @param {string} guildId - The guild ID.
* @returns {Promise<void>}
*/
async function handle247Toggle(ctx, message, set, guildId) {
const loc = tWrap(ctx, guildId);
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message);
if (!userChannelId) {
return message.reply(build247Panel(set, ctx, guildId, null));
}
const id = cleanId(userChannelId);
const channels = get247Channels(set);
if (channels.has(id)) {
await disable247(ctx, set, guildId, userChannelId);
return message.reply(build247Panel(set, ctx, guildId, id));
}
const result = await enable247(ctx, set, guildId, userChannelId);
if (result?.max) {
return message.reply(embed(
loc("responses.settings.max247Channels", { max: MAX_247_CHANNELS, prefix: ctx.handler.getPrefix(guildId) })
));
}
return message.reply(build247Panel(set, ctx, guildId, id));
}
/**
* Apply a new value to a setting, with type-specific validation.
* @param {object} ctx - The bot (Remix) context.
* @param {object} message - The command message.
* @param {ServerSettings} set - The guild settings instance.
* @param {string} key - The setting key.
* @param {string} rawValue - The raw string value from the command.
* @returns {Promise<string|null>} Error message string, or null on success.
*/
async function applySet(ctx, message, set, key, rawValue) {
if (BOOL_SETTINGS.has(key)) {
@@ -478,11 +350,6 @@ async function applySet(ctx, message, set, key, rawValue) {
return null;
}
if (key === "stay_247") {
await handle247(ctx, message, rawValue);
return null;
}
if (key === "volume") {
const num = parseInt(rawValue, 10);
if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) {
@@ -496,17 +363,17 @@ async function applySet(ctx, message, set, key, rawValue) {
if (!VALID_LOCALES.has(rawValue)) {
return ctx.t(message, "responses.settings.invalidLocale", {
locale: rawValue,
locales: [...VALID_LOCALES].map(l => `\`${l}\``).join(", ")
locales: [...VALID_LOCALES].map(l => "`" + l + "`").join(", ")
});
}
set.set(key, rawValue);
const guildId = getMessageGuildId(message);
if (guildId) ctx.locale.invalidateCache(guildId);
const gid = getMessageGuildId(message);
if (gid) ctx.locale.invalidateCache(gid);
return null;
}
if (key === "prefix") {
if (!rawValue || rawValue.length > 5) {
if (!rawValue || rawValue.length > PREFIX_MAX) {
return ctx.t(message, "responses.settings.prefixLength");
}
if (/\s/.test(rawValue)) {
@@ -516,35 +383,80 @@ async function applySet(ctx, message, set, key, rawValue) {
if (runnables[key]) {
const err = runnables[key].call(ctx, rawValue, { msg: message });
if (err) return `❌ ${err}`;
if (err) return "\u274c " + err;
}
set.set(key, rawValue);
return null;
}
/**
* @private
* @async
* Handle a settings shortcut command (e.g. `prefix`, `247`).
* Dispatches to 24/7 toggle, value display, or value set depending on arguments.
* @param {object} ctx - The bot (Remix) context.
* @param {object} message - The command message.
* @param {string} settingKey - The resolved setting key.
* @param {string[]} valueTokens - Remaining argument tokens after the shortcut alias.
* @returns {Promise<void>}
*/
async function handleShortcut(ctx, message, settingKey, valueTokens) {
const set = ctx.getSettings(message);
const guildId = getMessageGuildId(message);
const t247 = ctx.locale?.translate?.bind(ctx.locale);
if (valueTokens.length === 0) {
if (settingKey === "stay_247") {
const t247 = ctx.locale?.translate?.bind(ctx.locale);
return message.reply(build247StatusPanel(set, ctx, message, t247, getMessageGuildId(message)));
return handle247Toggle(ctx, message, set, guildId);
}
const val = set.get(settingKey);
return message.reply(embed(`\`${settingKey}\` → ${displayValue(settingKey, val)}`));
const label = prettifySettingLabel(settingKey, t247, guildId);
return message.reply(embed("**" + label + "**\nValue: " + displayValue(settingKey, val)));
}
const rawValue = valueTokens.join(" ");
if (settingKey === "stay_247") {
const mode = rawValue.toLowerCase().trim();
if (mode === "off" || mode === "false" || mode === "disable" || mode === "0") {
const loc = tWrap(ctx, guildId);
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
const { channelId } = await ctx.players.checkVoiceChannels(message);
if (channelId) {
await disable247(ctx, set, guildId, channelId);
return message.reply(build247Panel(set, ctx, guildId, cleanId(channelId)));
}
for (const [chId, player] of [...ctx.players.playerMap.entries()]) {
if (cleanId(player?._guildId ?? "") === cleanId(guildId)) {
const activeId = cleanId(player._channelId ?? chId);
ctx.markIntentionalLeave?.(activeId);
ctx.players.playerMap.delete(activeId);
if (activeId !== chId) ctx.players.playerMap.delete(chId);
await player.leave().catch(() => {});
player.destroy();
}
}
save247Channels(set, new Set());
return message.reply(build247Panel(set, ctx, guildId, null));
}
return handle247Toggle(ctx, message, set, guildId);
}
const err = await applySet(ctx, message, set, settingKey, rawValue);
if (err) return message.reply(embed(err));
if (settingKey !== "stay_247") {
const val = set.get(settingKey);
return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label: settingKey, value: displayValue(settingKey, val) })));
}
const label = prettifySettingLabel(settingKey, t247, guildId);
return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label, value: displayValue(settingKey, val) })));
}
/**
* @type {Function}
* @description Factory that builds the settings CommandBuilder and registers shortcut commands.
* Called at load time with `this` bound to the bot instance.
* @returns {CommandBuilder} The main settings command builder.
*/
export const command = function() {
if (this.locale) {
VALID_LOCALES = this.locale.availableLocales();
@@ -554,13 +466,13 @@ export const command = function() {
for (const [alias, settingKey] of Object.entries(SHORTCUTS)) {
const builder = new CommandBuilder()
.setName(alias)
.setDescription(`Shortcut for \`${settingKey}\`. Usage: $prefix${alias} [value]`)
.setId(`shortcut_${alias}`)
.setDescription("Shortcut for `" + settingKey + "`. Usage: $prefix" + alias + " [value]")
.setId("shortcut_" + alias)
.setCategory("util")
.setRequirement(e => e.addPermission("ManageGuild"))
.addTextOption(o =>
o.setName("value")
.setDescription(`New value for ${settingKey}`)
.setDescription("New value for " + settingKey)
.setRequired(false)
);
this.loader.commands.addCommand(builder);
@@ -568,7 +480,7 @@ export const command = function() {
}
}
const settingKeys = Object.keys(this.settingsMgr.defaults);
const settingKeys = this.settingsMgr.getPublicKeys();
return new CommandBuilder()
.setName("settings")
@@ -577,9 +489,8 @@ export const command = function() {
"$prefixsettings get",
"$prefixsettings get prefix",
"$prefixsettings set prefix %",
"$prefixsettings set locale de-DE",
"$prefixsettings set songAnnouncements off",
"$prefixsettings set stay_247 auto",
"$prefixsettings set stay_247 on",
"$prefixsettings set volume 80",
"$prefixsettings reset prefix",
"$prefixsettings help"
@@ -630,7 +541,7 @@ export const command = function() {
.addSubcommand(cmd =>
cmd.setName("help")
.setDescription("Show help for the settings system, or explain a specific setting.", "subcommands.settings.help")
.setDescription("Show help for the settings system.", "subcommands.settings.help")
.setId("helpSettings")
.addChoiceOption(c =>
c.addChoices(...settingKeys)
@@ -642,15 +553,18 @@ export const command = function() {
};
/**
* Execute the settings command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the settings command.
* Dispatches to the appropriate subcommand (set/get/reset/help) or shortcut handler.
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing the subcommand and its options.
* @returns {Promise<void>}
*/
export async function run(message, data) {
const set = this.getSettings(message);
const cmd = data.commandId || "getSettings";
const guildId = message.channel?.guildId ?? message.message?.guildId;
const t247 = this.locale?.translate?.bind(this.locale);
if (cmd?.startsWith("shortcut_")) {
const alias = cmd.replace("shortcut_", "");
@@ -677,7 +591,7 @@ export async function run(message, data) {
const rawValue = data.get("value")?.value;
if (!this.settingsMgr.isOption(settingKey)) {
const available = Object.keys(this.settingsMgr.defaults).join("`, `");
const available = this.settingsMgr.getPublicKeys().join("`, `");
return message.reply(embed(
this.t(message, "responses.settings.unknownSetting", { setting: settingKey }) + "\n" + this.t(message, "responses.settings.availableSettings", { settings: available })
));
@@ -689,21 +603,22 @@ export async function run(message, data) {
if (settingKey === "stay_247") return;
const newVal = set.get(settingKey);
return message.reply(embed(this.t(message, "responses.settings.setSuccess", { label: prettifySettingLabel(settingKey), value: displayValue(settingKey, newVal) })));
const label = prettifySettingLabel(settingKey, t247, guildId);
return message.reply(embed(this.t(message, "responses.settings.setSuccess", { label, value: displayValue(settingKey, newVal) })));
}
if (cmd === "getSettings") {
if (settingKey) {
if (settingKey === "stay_247") {
const t247 = this.locale?.translate?.bind(this.locale);
return message.reply(build247StatusPanel(set, this, message, t247, getMessageGuildId(message)));
const channels = get247Channels(set);
return message.reply(build247Panel(set, this, guildId, channels.size > 0));
}
const val = set.get(settingKey);
const description = this.settingsMgr.descriptions?.[settingKey];
const prefix = this.handler.getPrefix(guildId);
const resolvedDesc = description ? description.replace(/\$prefix/gi, prefix) : null;
let reply = `**${prettifySettingLabel(settingKey)}**\nValue: ${displayValue(settingKey, val)}`;
if (resolvedDesc) reply += `\n\n*${resolvedDesc}*`;
const desc = this.settingsMgr.descriptions?.[settingKey];
const resolvedDesc = desc ? desc.replace(/\$prefix/gi, prefix) : null;
const label = prettifySettingLabel(settingKey, t247, guildId);
let reply = "**" + label + "**\nValue: " + displayValue(settingKey, val);
if (resolvedDesc) reply += "\n\n*" + resolvedDesc + "*";
return message.reply(embed(reply));
}
@@ -711,16 +626,19 @@ export async function run(message, data) {
const guildName = getGuildName(message);
const rawGuild = message.message?.guild;
const iconUrl = rawGuild?.icon
? `https://cdn.fluxer.app/icons/${rawGuild.id}/${rawGuild.icon}.webp`
? "https://cdn.fluxer.app/icons/" + rawGuild.id + "/" + rawGuild.icon + ".webp"
: null;
const lines = Object.entries(d)
.filter(([k]) => k !== "stay_247_mode")
.map(([k]) => {
const channels = get247Channels(set);
const lines = this.settingsMgr.getPublicKeys()
.map(k => {
if (k === "stay_247") {
return `• **24/7 mode** — ${format247Status(set, this.locale?.translate?.bind(this.locale), getMessageGuildId(message))}`;
return "\u2022 **24/7 mode** " + String.fromCharCode(8212) + " " + (channels.size > 0
? channels.size + " channel(s)"
: "\u274c disabled");
}
return `• **${prettifySettingLabel(k)}** — ${displayValue(k, d[k])}`;
const label = prettifySettingLabel(k, t247, guildId);
return "\u2022 **" + label + "** " + String.fromCharCode(8212) + " " + displayValue(k, d[k]);
});
return message.reply(embed(
@@ -736,52 +654,52 @@ export async function run(message, data) {
}
set.reset(settingKey);
if (settingKey === "locale") {
const guildId = getMessageGuildId(message);
if (guildId) this.locale.invalidateCache(guildId);
const gid = getMessageGuildId(message);
if (gid) this.locale.invalidateCache(gid);
}
const def = set.get(settingKey);
const label = prettifySettingLabel(settingKey, t247, guildId);
return message.reply(embed(
this.t(message, "responses.settings.resetSuccess", { setting: settingKey, value: displayValue(settingKey, def) })
this.t(message, "responses.settings.resetSuccess", { setting: label, value: displayValue(settingKey, def) })
));
}
if (cmd === "helpSettings") {
const pfx = this.handler.getPrefix(guildId);
if (!settingKey) {
const keys = Object.keys(this.settingsMgr.defaults);
const keyList = keys.map(k => `\`${k}\``).join(", ");
const keys = this.settingsMgr.getPublicKeys();
const keyList = keys.map(k => "`" + k + "`").join(", ");
return message.reply(embed(
this.t(message, "responses.settings.helpTitle") + "\n\n" +
this.t(message, "responses.settings.helpAvailable", { settings: keyList }) + "\n\n" +
this.t(message, "responses.settings.helpSubcommands", { prefix: pfx }) + "\n\n" +
this.t(message, "responses.settings.helpShortcuts", { prefix: pfx }),
{ title: "⚙️ Settings Help" }
this.t(message, "responses.settings.helpSubcommands", { prefix }) + "\n\n" +
this.t(message, "responses.settings.helpShortcuts", { prefix }),
{ title: "\u2699\ufe0f Settings Help" }
));
}
const rawDescription = this.settingsMgr.descriptions?.[settingKey] ?? this.t(message, "responses.settings.noDescription");
const description = rawDescription.replace(/\$prefix/gi, pfx);
const description = rawDescription.replace(/\$prefix/gi, prefix);
const currentVal = set.get(settingKey);
const defaultVal = this.settingsMgr.defaults?.[settingKey];
let extra = "";
if (settingKey === "locale") {
extra = `\n**Valid values:** ${[...VALID_LOCALES].map(l => `\`${l}\``).join(", ")}`;
extra = "\n**Valid values:** " + [...VALID_LOCALES].map(l => "`" + l + "`").join(", ");
} else if (settingKey === "volume") {
extra = `\n**Valid range:** ${VOLUME_MIN}–${VOLUME_MAX}`;
extra = "\n**Valid range:** " + VOLUME_MIN + "\u2013" + VOLUME_MAX;
} else if (BOOL_SETTINGS.has(settingKey)) {
extra = `\n**Valid values:** \`true\`, \`false\`, \`on\`, \`off\``;
extra = "\n**Valid values:** `true`, `false`, `on`, `off`";
} else if (settingKey === "stay_247") {
extra = `\n**Valid values:** \`off\`, \`on\`, \`auto\`\n\n**Modes:**\n• \`on\` — Stays connected permanently. Won't rejoin after \`${pfx}leave\`.\n• \`auto\` — Stays connected & auto-rejoins after \`${pfx}leave\` or disconnect.\n• \`off\` — Leaves after inactivity.\n\n**Multi-Voice:** You can save multiple voice channels in the same server. Each channel has its own mode.`;
extra = "\n**Usage:** Join a voice channel and use `247` to toggle.\n\nThe bot stays in that channel and auto-rejoins if disconnected.";
}
const label = prettifySettingLabel(settingKey, t247, guildId);
return message.reply(embed(
`**⚙️ Setting: \`${settingKey}\`**\n\n` +
`${description}${extra}\n\n` +
`**Current value:** ${settingKey === "stay_247" ? format247Status(set, this.locale?.translate?.bind(this.locale), getMessageGuildId(message)) : displayValue(settingKey, currentVal)}\n` +
`**Default:** ${displayValue(settingKey, defaultVal)}`,
{ title: `⚙️ ${settingKey}` }
"**\u2699\ufe0f Setting: `" + settingKey + "`**\n\n" +
description + extra + "\n\n" +
"**Current value:** " + displayValue(settingKey, currentVal) + "\n" +
"**Default:** " + displayValue(settingKey, defaultVal),
{ title: "\u2699\ufe0f " + settingKey }
));
}
}
+10 -4
View File
@@ -1,20 +1,26 @@
/**
* @file shuffle.mjs — Shuffle the current queue
* @module commands.shuffle
* @module commands/shuffle
* @description Randomly re-order the tracks in the playback queue.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the shuffle command.
*/
export const command = new CommandBuilder()
.setName("shuffle")
.setDescription("Re-orders the queue randomly.", "commands.shuffle")
.setCategory("music");
/**
* Execute the shuffle command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* Run handler for the shuffle command.
* Shuffles the queue and sends a confirmation embed.
*
* @param {object} message - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(message) {
+7 -4
View File
@@ -1,12 +1,13 @@
/**
* @file skip.mjs — Skip the currently playing song
* @module commands.skip
* @module commands/skip
* @description Skip the currently playing track.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the skip command. */
export const command = new CommandBuilder()
.setName("skip")
.setDescription("Skip the current playing song.", "commands.skip")
@@ -14,8 +15,10 @@ export const command = new CommandBuilder()
.setCategory("music");
/**
* Execute the skip command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @async
* Run handler for the skip command.
* Skips the current track and shows which track was skipped.
* @param {object} message - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(message) {
+72 -4
View File
@@ -1,6 +1,6 @@
/**
* @file stats.mjs — Display bot statistics — uptime, servers, users, and memory usage
* @module commands.stats
* @module commands/stats
* @description Display bot statistics including guild count, user count, uptime, and ping.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,6 +9,10 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import { logger } from "../src/constants/Logger.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the stats command.
*/
export const command = new CommandBuilder()
.setName("stats")
.setDescription("Display stats about the bot like the uptime.", "commands.stats")
@@ -21,6 +25,13 @@ let cachedUserCount = null;
let cacheExpiresAt = 0;
let inflightPromise = null;
/**
* Run tasks with a concurrency limit.
* @private
* @param {number} limit - Maximum number of concurrent tasks.
* @param {Function[]} tasks - Array of task functions to execute.
* @returns {Promise<unknown[]>} Array of task results.
*/
async function pool(limit, tasks) {
const results = [];
const executing = new Set();
@@ -33,6 +44,13 @@ async function pool(limit, tasks) {
return results;
}
/**
* Fetch the total member count for a guild by paginating through members.
* @private
* @async
* @param {object} guild - The Discord guild object.
* @returns {Promise<number>} Total member count.
*/
async function fetchGuildMemberCount(guild) {
try {
let after = undefined;
@@ -58,6 +76,13 @@ async function fetchGuildMemberCount(guild) {
}
}
/**
* Refresh the cached total user count across all guilds.
* @private
* @async
* @param {object} client - The Discord client instance.
* @returns {Promise<number>} Total user count.
*/
async function refreshUserCount(client) {
const guilds = [...client.guilds.values()];
const counts = await pool(10, guilds.map(g => () => fetchGuildMemberCount(g)));
@@ -67,12 +92,24 @@ async function refreshUserCount(client) {
return cachedUserCount;
}
/**
* Get the total user count, using cache if still valid or refreshing if expired.
* @private
* @param {object} client - The Discord client instance.
* @returns {Promise<number>} Total user count.
*/
function getUserCount(client) {
if (cachedUserCount !== null && Date.now() < cacheExpiresAt) return Promise.resolve(cachedUserCount);
if (!inflightPromise) inflightPromise = refreshUserCount(client);
return inflightPromise;
}
/**
* Count players with active voice connections.
* @private
* @param {Map} playerMap - The player map from PlayerManager.
* @returns {number} Number of live connected players.
*/
function getLivePlayerCount(playerMap) {
let live = 0;
@@ -101,6 +138,13 @@ function getLivePlayerCount(playerMap) {
let cachedGuildCount = null;
let guildCacheExpiresAt = 0;
/**
* Get the total guild count via REST API with caching.
* @private
* @async
* @param {object} client - The Discord client instance.
* @returns {Promise<number>} Total guild count.
*/
async function getGuildCount(client) {
if (cachedGuildCount !== null && Date.now() < guildCacheExpiresAt) {
return cachedGuildCount;
@@ -133,6 +177,27 @@ async function getGuildCount(client) {
}
}
/**
* Build the stats embed with all bot information.
* @private
* @param {Function} t - Translation function.
* @param {object} msg - The command message wrapper.
* @param {object} stats - Statistics data object.
* @param {number} stats.guildCount - Number of guilds.
* @param {number} stats.userCount - Number of users.
* @param {number} stats.playerCount - Number of active players.
* @param {number} stats.scrobbleCount - Total Last.fm scrobbles.
* @param {number} stats.linkedUsers - Number of Last.fm linked users.
* @param {number} stats.ping - Bot response ping in ms.
* @param {string} stats.uptime - Formatted uptime string.
* @param {string} stats.comHash - Git commit hash.
* @param {string} stats.comLink - Git commit link URL.
* @param {string} [stats.reason] - Last restart reason.
* @param {string} [stats.footer] - Custom footer text.
* @param {boolean} stats.loading - Whether data is still loading.
* @param {boolean} stats.lastfmEnabled - Whether Last.fm integration is enabled.
* @returns {EmbedBuilder} The constructed embed.
*/
function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) {
const num = (v) => Utils.formatNumber(v);
const ld = (v) => loading ? "..." : v;
@@ -171,8 +236,11 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
}
/**
* Execute the stats command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* Run handler for the stats command.
* Collects bot statistics and displays them in an embed, initially with loading
* state then edited with the real data.
*
* @param {object} message - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(message) {
+6 -4
View File
@@ -1,12 +1,13 @@
/**
* @file support.mjs — Show support server invite link
* @module commands.support
* @module commands/support
* @description Displays a link and invitation to the bot's support server.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the support command. */
export const command = new CommandBuilder()
.setName("support")
.setDescription("The support server for Remix. Feel free to ask help, report bugs or just chat :)", "commands.support")
@@ -14,8 +15,9 @@ export const command = new CommandBuilder()
.setCategory("util");
/**
* run function.
* @param {object} msg
* Run handler for the support command.
* Sends an embed with the support server link.
* @param {object} msg - The command message wrapper.
* @returns {void}
*/
export function run(msg) {
+16 -5
View File
@@ -1,6 +1,6 @@
/**
* @file test.mjs — Test/debug command for voice channel user detection
* @module commands.test
* @module commands/test
* @description Owner-only diagnostic command to display voice channel user counts.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -8,15 +8,19 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the test command (owner-only). */
export const command = new CommandBuilder()
.setName("test")
.setDescription("Shows how many people are in each voice channel.")
.setCategory("util")
.setRequirement(r => r.setOwnerOnly(true));
/**
* Execute the test command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the test command.
* Iterates the voice state cache and reports user counts per voice channel.
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data (unused).
* @returns {Promise<void>}
*/
export async function run(msg, data) {
@@ -54,6 +58,13 @@ export async function run(msg, data) {
return msg.reply({ embeds: [embed] });
}
/**
* @private
* Resolve a channel ID to a human-readable channel name.
* Tries cache, guild cache, then REST fetch as fallback.
* @param {string} channelId - The voice channel ID.
* @returns {Promise<string>} The channel name or a fallback string.
*/
const getChannelName = async (channelId) => {
const cached = this.client.channels.get(channelId);
if (cached?.name) return cached.name;
+7 -4
View File
@@ -1,12 +1,13 @@
/**
* @file thumbnail.mjs — Get the thumbnail image for the current or specified track
* @module commands.thumbnail
* @module commands/thumbnail
* @description Display the thumbnail artwork of the currently playing track.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the thumbnail command. */
export const command = new CommandBuilder()
.setName("thumbnail")
.setDescription("Request the thumbnail of the currently playing song.", "commands.thumbnail")
@@ -14,8 +15,10 @@ export const command = new CommandBuilder()
.setCategory("music");
/**
* Execute the thumbnail command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @async
* Run handler for the thumbnail command.
* Fetches and displays the thumbnail of the currently playing track.
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>}
*/
export async function run(msg) {
+15 -5
View File
@@ -1,6 +1,6 @@
/**
* @file trackopt.mjs — Manage per-track options — auto-seek start position and end-time timer
* @module commands.trackopt
* @module commands/trackopt
* @description Set custom start/end times for tracks with named alias support.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,8 +10,10 @@ import { Utils } from "../src/Utils.mjs";
import { logger } from "../src/constants/Logger.mjs";
import { ERROR_COLOR } from "../src/constants/UI.mjs";
/** @private @type {string} The default alias name for non-named track options. */
const DEFAULT_ALIAS = "default";
/** @type {CommandBuilder} @description Command definition for the trackopt command with subcommands. */
export const command = new CommandBuilder()
.setName("trackopt")
.setDescription("Set custom start/end times for tracks. Supports named aliases — save multiple trims per track for different sections.", "commands.trackopt")
@@ -58,6 +60,12 @@ export const command = new CommandBuilder()
)
.addAlias("to");
/**
* @private
* Extract an alias:name token from a parts array, mutating the array in place.
* @param {string[]} parts - Mutable array of token strings.
* @returns {string} The extracted alias value, or DEFAULT_ALIAS if not found.
*/
function extractAlias(parts) {
for (let i = 0; i < parts.length; i++) {
if (parts[i].toLowerCase().startsWith("alias:")) {
@@ -70,9 +78,11 @@ function extractAlias(parts) {
}
/**
* Execute the trackopt command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the trackopt command.
* Dispatches to set/get/play/remove/list subcommands for custom track trim options.
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing subcommand and its options.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
+11 -5
View File
@@ -1,6 +1,6 @@
/**
* @file volume.mjs — Set or view the playback volume
* @module commands.volume
* @module commands/volume
* @description Get or change the playback volume for the current voice channel.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,6 +9,10 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { MAX_VOLUME } from "../src/constants/UI.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the volume command.
*/
export const command = new CommandBuilder()
.setName("volume")
.setDescription("Get or change the current volume.", "commands.volume")
@@ -21,9 +25,11 @@ export const command = new CommandBuilder()
.addAliases("v", "vol");
/**
* Execute the volume command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* Run handler for the volume command.
* Displays the current volume or sets it to a new value.
*
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing the volume option.
* @returns {Promise<void>}
*/
export async function run(message, data) {
+8 -6
View File
@@ -1,6 +1,6 @@
/**
* @file volumedefault.mjs — Set the default volume for the server
* @module commands.volumedefault
* @module commands/volumedefault
* @description View or set the server default volume. Requires Manage Server permission to set.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,7 +9,7 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { PermissionFlags } from "@fluxerjs/core";
import { MAX_VOLUME } from "../src/constants/UI.mjs";
/** @type {CommandBuilder} @description Command definition for the volumedefault command. */
export const command = new CommandBuilder()
.setName("volumedefault")
.setDescription("View or set the server default volume. (Requires Manage Server to set)", "commands.volumedefault")
@@ -22,9 +22,11 @@ export const command = new CommandBuilder()
.addAliases("vd");
/**
* Execute the volumedefault command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the volumedefault command.
* Displays or persists the server's default volume setting.
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing the optional volume option.
* @returns {Promise<void>}
*/
export async function run(message, data) {
+54 -15
View File
@@ -1,6 +1,6 @@
/**
* @file vote.mjs — Skip-vote system — start a vote to skip the current track
* @module commands.vote
* @module commands/vote
* @description View voting info, check voters, or browse voter lists for a server/bot on FluxerList.
*/
import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -11,7 +11,7 @@ import { FLUXERLIST, buildVoteLink } from "../src/constants/API.mjs";
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the vote command. */
export const command = new CommandBuilder()
.setName("vote")
.setDescription("View voting info or check voters for your server/bot on FluxerList", "commands.vote")
@@ -40,6 +40,13 @@ export const command = new CommandBuilder()
.setRequired(false)
);
/**
* @private
* Build an error embed when FluxerList is not configured.
* @param {Function} t - Translation function.
* @param {string} guildId - The guild ID for localization.
* @returns {object} Embed payload.
*/
function notConfigured(t, guildId) {
return {
embeds: [new EmbedBuilder()
@@ -48,6 +55,15 @@ function notConfigured(t, guildId) {
};
}
/**
* @private
* Build an error embed when no resource ID is available for the vote lookup.
* @param {string} type - The resource type ("server" or "bot").
* @param {string} prefix - The guild command prefix.
* @param {Function} t - Translation function.
* @param {string} guildId - The guild ID for localization.
* @returns {object} Embed payload.
*/
function noResourceId(type, prefix, t, guildId) {
return {
embeds: [new EmbedBuilder()
@@ -57,15 +73,18 @@ function noResourceId(type, prefix, t, guildId) {
}
/**
* Build a paginated voter list embed.
* @param {Array<{ username: string, fluxerId: number, votedAt: string }>} voters
* @param {number} total
* @param {number} page
* @param {number} limit
* @param {"server"|"bot"} type
* @param {string} resourceId
* @param {boolean} expired - Whether the navigation controls have expired
* @returns {object} Embed payload
* @private
* Build a paginated voters embed with ranked voter list.
* @param {Array<object>} voters - Array of voter objects.
* @param {number} total - Total number of voters across all pages.
* @param {number} page - Current page number (1-based).
* @param {number} limit - Voters per page.
* @param {string} type - Resource type ("server" or "bot").
* @param {string} resourceId - The server or bot ID.
* @param {boolean} [expired=false] - Whether navigation controls have expired.
* @param {Function} t - Translation function.
* @param {string} guildId - The guild ID for localization.
* @returns {object} Embed payload.
*/
function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired = false, t, guildId) {
const totalPages = Math.max(1, Math.ceil(total / limit));
@@ -101,9 +120,11 @@ function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired
}
/**
* Execute the vote command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message
* @param {Map<string, {value: *}>} data - Slash-command options map
* @async
* Run handler for the vote command.
* Handles info, check, and voters subcommands with optional pagination.
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing action, type, id, and page options.
* @returns {Promise<void>}
*/
export async function run(msg, data) {
@@ -191,6 +212,14 @@ export async function run(msg, data) {
let currentPage = voterData.page;
/**
* @private
* Build a voter page embed from fetched voter data.
* @param {number} pageIdx - Page number (1-based).
* @param {object} data - Voter data from FluxerList API.
* @param {boolean} [expired=false] - Whether controls have expired.
* @returns {object} Embed payload.
*/
const buildPage = (pageIdx, data, expired = false) => {
return buildVotersEmbed(data.voters, data.total, pageIdx, 20, resolvedType, id, expired, t, guildId);
};
@@ -203,6 +232,11 @@ export async function run(msg, data) {
await replyMsg.message.react(emoji).catch(() => {});
}
/**
* @private
* Remove all navigation reactions from the voter list message.
* @returns {Promise<void>}
*/
const clearReactions = async () => {
try {
await replyMsg.message.removeAllReactions();
@@ -214,6 +248,11 @@ export async function run(msg, data) {
};
let emojiTimeout = null;
/**
* @private
* Reset the emoji removal timeout timer for the voter pagination session.
* @returns {void}
*/
const resetTimer = () => {
clearTimeout(emojiTimeout);
emojiTimeout = setTimeout(async () => {
+5 -24
View File
@@ -1,5 +1,5 @@
{
"Comment": "Fluxer music bot configuration. IMPORTANT: Node.js >= 22.0.0 is required (moonlink.js v5 dependency). Run 'node --version' to verify.",
"Comment": "Fluxer music bot configuration. Requires Node.js >= 22.13.0. Run 'node --version' to verify.",
"token": "your bot token",
"fluxer.js": {
"rest": {
@@ -8,9 +8,6 @@
"retries": 3
}
},
"fluxer-api": {
"Comment": "Configuration options for a fluxer REST client if self-hosting. See: https://docs.fluxer.app"
},
"prefix": "your desired prefix (such as %)",
"presenceInterval": null,
"presenceContents-Comment": "Each entry can be a plain string (e.g. 'Ping for Prefix') or an object. Objects support: text (required), emoji_name (unicode emoji or custom emoji name), emoji_id (snowflake ID for custom guild emojis only), activity ({ name, type, url? }). Activity types: 0=Playing, 1=Streaming, 2=Listening, 3=Watching, 5=Competing. For custom guild emojis, provide both emoji_name AND emoji_id. For unicode emojis, only emoji_name is needed.",
@@ -32,16 +29,12 @@
"activity": { "name": "RedTech & NoLogicAlan", "type": 2 }
}
],
"spotify": {
"clientId": "your spotify client id",
"clientSecret": "your spotify client secret"
},
"nodelink": {
"host": "localhost",
"port": 3000,
"password": "youshallnotpass",
"requestTimeout": 60000,
"Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors."
"Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors. All audio sources (Spotify, Deezer, Apple Music, etc.) are resolved by NodeLink, so configure source credentials in nodelink.config.json, not here."
},
"comment-radio": {
"message": "If you have radio stations you'd like to connect, add them to the array below. Radio stations must be rendered like following:",
@@ -59,8 +52,6 @@
}
},
"radio": [],
"helpCatalog": true,
"helpPagination": true,
"mysql": {
"host": "your-mysql-host.com",
"port": 3306,
@@ -68,22 +59,13 @@
"password": "password of your user",
"database": "name of the target database"
},
"webPort": 80,
"dashboard": {
"enabled": false,
"redis": {
"url": "redis://localhost:6379"
}
},
"dashboardUrl": "The url the dashboard is accessible with.",
"ssl": {
"private": "path-to-private-key.pem",
"cert": "path-to-certificate.pem",
"useSSL": false,
"httpPort": 80
"Comment": "Optional dashboard backend. When enabled, the bot speaks Redis RPC (request/response/info channels) with an external web frontend. Login codes are verified (bcrypt) from the MySQL login_codes table. Keep Redis network-isolated — the RPC channel has no shared secret."
},
"sessionSecret": "secret for the expressjs session middleware; https://www.npmjs.com/package/express-session#user-content-secret",
"geniusToken": "Genius access token (Used for lyrics); optional",
"lastfm": {
"Comment": "Last.fm integration: auto-scrobble songs, play loved/top/recent tracks. Register at https://www.last.fm/api/account/create",
"enabled": true,
@@ -102,7 +84,7 @@
},
"owners": ["user id for owner-only commands", "another user id"],
"playerAFKTimeout": 60000,
"Comment": "The above specifies the time in ms after which a player goes inactive; Optional.",
"Comment2": "The above specifies the time in ms after which a player goes inactive; Optional.",
"customStatsFooter": "Text shown in the footer of the $prefixstats embed; optional.",
"embedColor": "0xe9196c",
"logging": {
@@ -119,8 +101,7 @@
"guild": true,
"recovery": false,
"settings": true,
"worker": false,
"moonlink": false,
"lavalink": true,
"dashboard": false,
"redis": false
},
+12 -17
View File
@@ -1,26 +1,21 @@
# Bot token from https://fluxer.app/developers
BOT_TOKEN=your_bot_token_here
# Docker Compose environment for Remix.
# Copy this file to docker/.env (same folder as docker-compose.yml) and edit.
# MySQL credentials
MYSQL_ROOT_PASSWORD=change_me_root
# --- MySQL (used by the mysql service; reference the same values in config.json) ---
MYSQL_ROOT_PASSWORD=remix_root_pw
MYSQL_DATABASE=remix
MYSQL_USER=remix
MYSQL_PASSWORD=change_me
MYSQL_PASSWORD=remix_pw
# Web dashboard port mapping (host:container)
# --- Host port mappings ---
# Port exposed on the host for the bot (dashboard backend / health endpoint)
WEB_PORT=8080
# NodeLink port mapping
# Port exposed on the host for NodeLink (audio node)
NODELINK_PORT=3000
# Timezone
# --- Timezone applied to all containers ---
TZ=UTC
# Optional: paste your entire config.json as a single line (base64 or raw JSON)
# If set, the entrypoint will write it to /app/config.json on first boot.
# CONFIG_JSON={"token":"...","mysql":{...}}
# Fluxer OAuth2 (for dashboard)
FLUXER_OAUTH_ID=
FLUXER_OAUTH_SECRET=
FLUXER_OAUTH_REDIRECT_URI=
# --- Optional: raw JSON config written to /app/config.json on first boot ---
# Takes precedence over docker/config_example.json when no config.json is mounted.
# CONFIG_JSON={"token":"YOUR_TOKEN","mysql":{"host":"mysql","port":3306,"user":"remix","password":"remix_pw","database":"remix"},"nodelink":{"host":"nodelink","port":3000,"password":"youshallnotpass"}}
+1 -12
View File
@@ -16,10 +16,6 @@
"password": "youshallnotpass",
"requestTimeout": 60000
},
"spotify": {
"clientId": "",
"clientSecret": ""
},
"lastfm": {
"apiKey": "",
"apiSecret": "",
@@ -30,14 +26,8 @@
"enabled": false,
"redis": {
"url": "redis://redis:6379"
},
"fluxer": {
"id": "",
"secret": "",
"redirectUri": ""
}
},
"webPort": 80,
"logging": {
"enabled": true,
"warn": true,
@@ -52,8 +42,7 @@
"guild": true,
"recovery": true,
"settings": true,
"worker": false,
"moonlink": true,
"lavalink": true,
"dashboard": false,
"redis": false
},
+125 -114
View File
@@ -1,6 +1,7 @@
/**
* @file index.mjs — Fluxer Remix bot — main entry point; initializes client, voice, commands, players, and event handlers
* @module index
* @description Entry point for the Fluxer music bot. Creates the {@link Remix} instance,
* sets up process-level error handlers, and registers signal-based graceful shutdown.
*/
import * as fs from "fs";
@@ -15,8 +16,7 @@ import { RemoteSettingsManager } from "./src/Settings.mjs";
import { PlayerManager } from "./src/PlayerManager.mjs";
import childProcess from "node:child_process";
import { getVoiceManager } from "@fluxerjs/voice";
import { FluxerRevoice } from "./src/constants/FluxerRevoice.mjs";
import { MoonlinkManager } from "./src/MoonlinkManager.mjs";
import { LavalinkManager } from "./src/LavalinkManager.mjs";
import { Dashboard } from "./src/dashboard/Dashboard.mjs";
import { Locale } from "./src/constants/Locale.mjs";
import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs";
@@ -26,13 +26,11 @@ import { FluxerListManager } from "./src/FluxerListManager.mjs";
import { TrackOptionsManager } from "./src/TrackOptionsManager.mjs";
/**
* Create a backward-compatible "bot view" wrapper around VoiceStateCache.
*
* The old code used separate Maps for observedVoiceUsers and observedVoiceBots.
* VoiceStateCache merged both into one object, but the default iterator/size
* only exposes human users. This wrapper provides the Map-like interface that
* iterates BOT entries instead, so code that does `for (const [k, v] of observedVoiceBots)`
* still gets bot data, not human data.
* Create a Map-like view object that proxies bot voice-state lookups
* through the VoiceStateCache's bot-specific methods.
* @param {object} voiceCache - The {@link VoiceStateCache} instance.
* @returns {Map} A Map-like object with `size`, `get`, `set`, `has`, `delete`,
* `forEach`, and iterator methods backed by the voice cache.
*/
function createBotView(voiceCache) {
return {
@@ -52,9 +50,16 @@ function createBotView(voiceCache) {
/**
* Remix class.
* @class
* @description Main bot class. Orchestrates client, settings, players, lavalink,
* gateway events, commands, and 24/7 voice channel management.
*/
export class Remix {
/**
* Bootstrap the entire bot: load config, create Discord client, initialise
* settings/commands/players/dashboard, set up event handlers, load modules,
* and log in to Discord.
*/
constructor() {
let config;
try {
@@ -77,7 +82,7 @@ export class Remix {
setGlobalColor(config.embedColor);
this.locale = new Locale();
this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
this.locale.load();
this.dashboard = new Dashboard(this, {
@@ -214,8 +219,8 @@ export class Remix {
};
commands.owners = config.owners ?? [];
this.moonlink = null;
let moonlinkInitialised = false;
this.lavalink = null;
let lavalinkInitialised = false;
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
@@ -252,32 +257,24 @@ export class Remix {
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);
if (cleaned.length === 0 && (val && val !== "none")) {
serverSettings.set("stay_247_mode", "off");
}
logger.settings(
`[settings] Cleaned stay_247 for guild ${guildId}: ${JSON.stringify(val)} → ${JSON.stringify(newVal)}`
);
}
const modesMap = serverSettings.get("stay_247_modes");
if (!modesMap || typeof modesMap !== "object") {
const guildMode = serverSettings.get("stay_247_mode") ?? "off";
if (guildMode && guildMode !== "off" && cleaned.length > 0) {
const newModes = {};
for (const chId of cleaned) {
newModes[chId] = guildMode;
}
serverSettings.set("stay_247_modes", newModes);
logger.settings(
`[settings] Migrated stay_247_mode → stay_247_modes for guild ${guildId}: ${guildMode} → ${JSON.stringify(newModes)}`
);
}
}
}
});
@@ -303,30 +300,14 @@ export class Remix {
this.dashboard.setBotId(botId);
this.trackOptions.setBotId(botId);
if (!moonlinkInitialised) {
moonlinkInitialised = true;
this.moonlink = new MoonlinkManager(config.nodelink ?? {}, client);
this.moonlink.on("ready", (sessionId) => {
logger.moonlink(`[Moonlink] Session ready: ${sessionId}`);
for (const player of this.players?.playerMap?.values() ?? []) {
player._nl.sessionId = sessionId;
}
this.playerContext.moonlink = this.moonlink;
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");
});
try {
await this.moonlink.init(botId);
} catch (e) {
logger.error("[Moonlink] Init failed:", e.message);
}
} else {
logger.moonlink("[Moonlink] Reconnected — re-initialising node session.");
try {
await this.moonlink.init(botId);
} catch (e) {
logger.error("[Moonlink] Re-init failed:", e.message);
}
await this.lavalink.init();
this.playerContext.lavalink = this.lavalink;
}
this.gatewayHandler.onReady();
@@ -348,15 +329,12 @@ export class Remix {
}
});
this.revoice = FluxerRevoice.getInstance(client);
client._remix = this;
this.playerContext = {
client: this.client,
config,
nodelink: config.nodelink,
moonlink: null,
revoice: this.revoice,
lavalink: null,
};
this.players = new PlayerManager(settings, commands, {
config,
@@ -616,18 +594,9 @@ export class Remix {
}
/**
* Attach error handlers on all @fluxerjs/ws shard WebSockets.
*
* When the Fluxer gateway's underlying WebSocket closes (e.g. network
* blip, server restart), @fluxerjs/ws throws a "WebSocket error" from
* its internal error handler. Without an .on("error") listener on the
* WS object itself, this escalates to Node's uncaughtException handler,
* producing a noisy stack trace even though the bot recovers
* automatically via gateway reconnection.
*
* By attaching .on("error") handlers here, we catch the error at the
* source, log a single clean line, and prevent it from reaching
* uncaughtException.
* Attach proactive error handlers to WebSocket sockets/shards to prevent
* unhandled crashes from WebSocket transport errors. Re-armed periodically.
* @private
*/
_attachWsErrorHandlers() {
try {
@@ -704,6 +673,12 @@ export class Remix {
}
}
/**
* Mark a channel leave as intentional (user-initiated) to prevent
* the 24/7 auto-rejoin system from rejoining.
* @param {string} channelId - The channel ID.
* @param {number|null} [ttlMs=null] - Time-to-live in ms (default: config.timers.intentionalLeaveTTL or 10s).
*/
markIntentionalLeave(channelId, ttlMs = null) {
const cleanChId = cleanId(channelId);
if (!cleanChId) return;
@@ -716,12 +691,12 @@ export class Remix {
}
/**
* Spawn a player for a voice channel without requiring a user message.
* Used by the 24/7 settings command and the leave command's auto-rejoin.
*
* @param {string} guildId — The guild ID
* @param {string} channelId — The voice channel ID to join
* @returns {Promise<Player>} The created player
* Spawn a new Player for a channel. Used by 24/7 boot recovery and enable247.
* Guards against duplicate players, missing channels, and pending joins.
* @param {string} guildId - The guild ID.
* @param {string} channelId - The target voice channel ID.
* @returns {Promise<Player>} The spawned and connected player.
* @throws {Error} If channel not found, not a voice channel, or join fails.
*/
async _spawnPlayer(guildId, channelId) {
const cleanGuildId = cleanId(guildId);
@@ -733,7 +708,7 @@ export class Remix {
?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId);
if (existing) return existing;
if (!this.moonlink) throw new Error("Audio node not ready yet — try again in a moment");
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");
@@ -748,9 +723,7 @@ export class Remix {
const player = new Player(this.config.token, {
client: this.client,
config: this.config,
nodelink: this.config.nodelink,
moonlink: this.moonlink ?? null,
revoice: this.revoice ?? null,
lavalink: this.lavalink ?? null,
settingsMgr: this.settingsMgr ?? this.settings ?? null,
getPrefix: (guildId) => this.handler.getPrefix(guildId),
observedVoiceUsers: this.observedVoiceUsers ?? null,
@@ -768,8 +741,8 @@ export class Remix {
player.on("autoleave", () => {
const mode = player._get247Mode();
if (mode === "auto" || mode === "on") {
logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 ${mode} channel ${cleanChannelId} (guild ${cleanGuildId})`);
if (mode === "on") {
logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 channel ${cleanChannelId} (guild ${cleanGuildId})`);
return;
}
if (player._hasHumansInChannel()) {
@@ -875,6 +848,15 @@ export class Remix {
}
}
/**
* Leave a voice channel programmatically. Removes 24/7 if active,
* destroys the player, and optionally sends a confirmation message.
* @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);
@@ -887,24 +869,6 @@ export class Remix {
? new Set(raw.map(id => cleanId(id)).filter(Boolean))
: new Set([cleanId(raw)]);
const channelMode = channels.has(cleanChId) ? get247ChannelMode(set, cleanChId) : "off";
if (channels.has(cleanChId) && !force) {
if (channelMode === "auto") {
if (message) {
const prefix = this.handler.getPrefix(cleanGuildId);
const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId;
message.replyEmbed(
this.locale.translate(guildIdForLocale, "responses.leave.autoRejoinHint", {
channel: cleanChId,
prefix
})
);
}
return false;
}
}
if (channels.has(cleanChId)) {
channels.delete(cleanChId);
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
@@ -931,18 +895,22 @@ export class Remix {
return true;
}
/** @param {import("./src/MessageHandler.mjs").Message} message */
/**
* Get the server settings for the guild associated with a message.
* @param {object} message - The incoming message wrapper.
* @returns {object} The {@link ServerSettings} for the guild, or a fallback.
*/
getSettings(message) {
const guildId = message?.channel?.channel?.guildId ?? message?.guildId ?? null;
return this.settingsMgr.getServer(guildId);
}
/**
* Translate a key for the guild of the given message.
* @param {import("./src/MessageHandler.mjs").Message} message
* @param {string} key
* @param {Object} [data={}]
* @returns {string}
* Shorthand to translate a locale key for the guild of a given message.
* @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
@@ -952,18 +920,25 @@ export class Remix {
return this.locale.translate(guildId, key, data);
}
/**
* Get or create a player for the given message context.
* Delegates to {@link PlayerManager.getPlayer}.
* @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);
}
/**
* Return all guilds the given user shares with this bot.
* No longer gated behind settingsMgr — works with or without MySQL.
* Uses cached members first, falls back to observedVoiceUsers, then
* an async REST fetch for large guilds where the member cache is incomplete.
*
* @param {import("@fluxerjs/core").User} user
* @returns {Promise<Array<{name:string,id:string,icon:string|null,voiceChannels:Array}>>}
* 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.
* @async
* @param {object} user - The Discord user.
* @returns {Promise<Array<object>>} Array of server summary objects with channels.
*/
async getSharedServers(user) {
if (!user) return [];
@@ -1017,6 +992,13 @@ export class Remix {
return shared;
}
/**
* Create and attach a paginated message to the given message.
* @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),
@@ -1028,6 +1010,12 @@ export class Remix {
const remix = new Remix();
/**
* Check whether an error is a known-ignorable WebSocket transport crash
* from the fluxer.js ws or undici internals.
* @param {Error} err - The error to check.
* @returns {boolean} True if the error should be silently recovered.
*/
const isIgnorableWsCrash = (err) => {
const message = String(err?.message ?? err ?? "");
const stack = String(err?.stack ?? "");
@@ -1065,8 +1053,31 @@ process.on("uncaughtExceptionMonitor", (err, origin) => {
logger.error("Error:", err, origin);
});
/**
* Graceful shutdown handler: destroys all active players, closes
* Lavalink, Redis, and Dashboard DB connections, then exits.
* @async
* @returns {Promise<void>}
*/
const saveAndExit = async () => {
logger.recovery("\n[Shutdown] Cleaning up before exit...");
try {
if (remix.players?.playerMap) {
for (const [channelId, player] of remix.players.playerMap) {
try { player.destroy(); } catch (e) { logger.warn("[Shutdown] Player destroy error:", e?.message); }
}
remix.players.playerMap.clear();
}
} catch (e) {
logger.warn("[Shutdown] Player cleanup error:", e?.message);
}
try {
if (remix.lavalink) {
remix.lavalink.destroy();
}
} catch (e) {
logger.warn("[Shutdown] Lavalink cleanup error:", e?.message);
}
try {
if (remix.dashboard?.redis?.destroy) {
await remix.dashboard.redis.destroy();
+368 -3437
View File
File diff suppressed because it is too large. Load diff
+9 -8
View File
@@ -5,21 +5,22 @@
},
"dependencies": {
"@fluxerjs/core": "^2.2.0",
"@fluxerjs/util": "^2.2.0",
"@fluxerjs/voice": "^2.2.0",
"bcryptjs": "^3.0.3",
"ffmpeg-static": "^5.3.0",
"ffprobe-static": "^3.1.0",
"follow-redirects": "^1.16.0",
"moonlink.js": "^5.2.0",
"lavalink-client": "^2.10.3",
"mysql2": "^3.9.0",
"redis": "^5.12.1",
"revoice.js": "^0.2.1696"
},
"opusscript": "^0.0.8",
"prism-media": "^1.3.5",
"redis": "^5.12.1"
},w
"scripts": {
"dev": "node --inspect index.mjs --trace-warnings",
"start": "node index.mjs",
"commands": "node index.mjs usage",
"defaultsSync": "node index.mjs sreload",
"migrate": "node settings/migrate.mjs"
},
"optionalDependencies": {
"@discordjs/opus": "^0.10.0"
}
}
+31 -30
View File
@@ -1,37 +1,38 @@
# WIP Web Dashboard for Remix
# Settings System
Control Remix through a web interface and set server settings and similar.
Per-guild settings for Remix, backed by MySQL.
Installation instructions will follow soon:tm:
## How it works
## Setup
- Defaults live in `storage/defaults.json`. Every guild starts from this template.
- `src/Settings.mjs` contains the implementation:
- `SettingsManager` — defines the setting keys, their defaults and descriptions.
- `ServerSettings` — per-guild view; `get`/`set`/`reset` operate in memory and persist with an 80 ms debounced write.
- `RemoteSettingsManager` — loads every guild row from the MySQL `settings` table (`id` primary key + `data` JSON column) and writes individual keys back with `JSON_SET`.
- The `settings` table is the only table you need to create manually:
1. Create a mysql server with the following table:
```MySQL
CREATE TABLE `ksiTokens` (
`user` varchar(26) NOT NULL,
`id` varchar(50) NOT NULL,
`token` varchar(70) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`createdAt` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
CREATE TABLE `logins` (
`user` text NOT NULL,
`id` varchar(50) NOT NULL,
`token` varchar(70) NOT NULL,
`verified` tinyint(1) NOT NULL,
`createdAt` datetime NOT NULL
```sql
CREATE TABLE `settings` (
`id` varchar(70) NOT NULL,
`data` json NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
```
2. Fill out the connection details in `config.json` in the remix root directory (See `config.example.json`)
3. SSL setup:
- Create a certificate. For example [using Let's Encrypt](https://letsencrypt.org/de/getting-started/)
- Find the path to your private key and certificate pem files. Certbot uses `/etc/letsencrypt/live/remix.fairuse.org/privkey.pem` for the private key and `/etc/letsencrypt/live/remix.fairuse.org/fullchain.pem` for the certificate file. Fill in the paths in the config file
- set `useSSL` in `config.json` to `true`
- Make sure to configure the ports correctly. HTTPS connects to port `443` so make sure to set `webPort` accordingly.
Credits for Website design:
- NoLogicAlan
- ophx
- ShadowLp174
- Fantic
## Files
| File | Purpose |
| :--- | :--- |
| `Settings.mjs` | Re-export of `src/Settings.mjs` classes |
| `migrate.mjs` | One-shot tool that clones every guild row from one settings table/bot ID to another (`npm run migrate`) |
| `runnables.mjs` | Validators applied when a setting changes (e.g. `prefix` must be ≤ 5 chars with no whitespace, `pfp` only accepts `default`) |
## Managing settings in a server
Use the `%settings` command (requires Manage Server):
- `%settings get` — view all settings for this server
- `%settings set <key> <value>` — change a setting
- `%settings reset <key>` — reset a setting to its default
- `%settings help` — explain a specific key
Shortcut commands `prefix` / `pfx` and `247` map to the corresponding settings keys.
+2 -7
View File
@@ -1,10 +1,5 @@
/**
* @file Settings.mjs — Dashboard Settings — server-side settings manager for the web dashboard
* @module settings.Settings
*/
/**
* Re-exports from src/Settings.mjs for backward compatibility.
* The canonical definitions now live in src/Settings.mjs.
* @module settings/Settings
* @description Re-exports the core Settings classes from `src/Settings.mjs`.
*/
export { SettingsManager, ServerSettings, RemoteSettingsManager } from "../src/Settings.mjs";
+4 -2
View File
@@ -1,6 +1,8 @@
/**
* @file migrate.mjs — Migration script — migrates settings and 24/7 channel data between Redis and SQLite backends
* @module settings.migrate
* @module settings/migrate
* @description One-shot migration script that copies all server settings from one
* RemoteSettingsManager instance to another (e.g. between databases or bot IDs).
* Reads `config.json` for MySQL credentials and runs once on the "ready" event.
*/
import { RemoteSettingsManager } from "../src/Settings.mjs";
+26 -27
View File
@@ -1,44 +1,43 @@
/**
* @file runnables.mjs — Runnable validators — server-side validation functions for settings values (prefix, volume, 24/7 mode, etc.)
* @module settings.runnables
* @module settings/runnables
* @description Validation runnables for settings values.
* Each function is called with (value, context) and returns an error string or null.
*/
export default {
/**
* Validate a prefix setting value.
* @param {string} value - The proposed prefix
* @param {object} _data - Additional context (reserved for future use)
* @returns {true|string} True if valid, error message string if invalid
* @param {*} value - The value to validate.
* @param {object} ctx - Command context (unused but provided by the settings system).
* @returns {string|null} Error message if invalid, or null if valid.
*/
prefix(value, _data) {
if (!value || typeof value !== "string") return "Prefix must be a non-empty string.";
if (value.length > 10) return "Prefix must be 10 characters or fewer.";
if (/\s/.test(value)) return "Prefix must not contain whitespace.";
return true;
export default {
prefix(value) {
if (!value || typeof value !== 'string') return 'Prefix must be a non-empty string.';
if (value.length > 5) return 'Prefix must be 5 characters or fewer.';
if (/\s/.test(value)) return 'Prefix must not contain whitespace.';
return null;
},
/**
* Validate a profile picture setting value.
* @param {string} value - The proposed pfp value
* @param {object} _data - Additional context (reserved for future use)
* @returns {true|string} True if valid, error message string if invalid
* Validate a pfp (profile picture) setting value.
* Only 'default' is accepted on Fluxer.
* @param {*} value - The value to validate.
* @returns {string|null} Error message if invalid, or null if valid.
*/
pfp(value, _data) {
if (value !== "default") {
return "Profile picture customisation is not supported on Fluxer.";
pfp(value) {
if (value !== 'default') {
return 'Profile picture customisation is not supported on Fluxer.';
}
return true;
return null;
},
/**
* Validate the 24/7 stay mode setting.
* @param {string|boolean} value - The proposed stay_247 value
* @param {object} _data - Additional context (reserved for future use)
* @returns {true|string} True if valid, error message string if invalid
* Validate stay_247 setting. Always valid — the 24/7 system manages
* this value internally via the toggle command.
* @param {*} value - The value (ignored).
* @returns {string|null} Always null (no error).
*/
stay_247(value, _data) {
if (value === true || value === false || value === "true" || value === "false") return true;
if (typeof value === "string" && value.length > 0) return true;
return "Invalid value for 24/7 mode.";
stay_247(value) {
return null;
},
};
+105 -99
View File
@@ -1,8 +1,4 @@
/**
* @file CommandHandler.mjs — CommandHandler — registers, resolves, and dispatches slash and prefix commands with option parsing and requirements
* @module src.CommandHandler
*/
/** @module src/CommandHandler @description Command registration, loading, parsing, and execution framework with builder pattern, subcommands, and flags. */
import { pathToFileURL } from "node:url";
import { logger } from "./constants/Logger.mjs";
import { Utils } from "./Utils.mjs";
@@ -13,20 +9,16 @@ import { SettingsManager } from "./Settings.mjs";
import path from "node:path";
import * as fs from "node:fs";
/**
* CommandBuilder class.
*/
/** @class CommandBuilder @description Fluent builder for constructing command definitions with name, description, options, subcommands, aliases, and requirements. */
export class CommandBuilder {
/** Create a new CommandBuilder with default empty state. */
constructor() {
this.name = null;
this.description = null;
this.id = null;
this.aliases = [];
/** @type {CommandBuilder[]} */
this.subcommands = [];
/** @type {Option[]} */
this.options = [];
/** @type {CommandRequirement[]} */
this.requirements = [];
this.category = "default";
this.examples = [];
@@ -34,59 +26,78 @@ export class CommandBuilder {
this.uid = Utils.uid();
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
/** @type {CommandBuilder} */
this.parent = null;
}
/** Set the command name and add it as the primary alias. @param {string} n @returns {CommandBuilder} */
setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; }
/** Set the command description. @param {string} d @returns {CommandBuilder} */
setDescription(d) { this.description = d; return this; }
/** Set the command ID. @param {string} id @returns {CommandBuilder} */
setId(id) { this.id = id; return this; }
/** @returns {string} Full command path including parent chain (e.g. "music play"). */
get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; }
/** Add a permission/owner-only requirement. @param {Function} config @returns {CommandBuilder} */
setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; }
/** Add a subcommand builder. @param {Function} config @returns {CommandBuilder} */
addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; }
/** Add a string option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; }
/** Add a number option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; }
/** Add a boolean option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; }
/** Add a channel option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; }
/** Add a user option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; }
/** Add a text (remaining-args) option. Only one is allowed per command. @param {Function} config @returns {CommandBuilder} @throws {Error} If a text option already exists. */
addTextOption(config) {
if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option.");
this.options.push(config(new Option("text")));
return this;
}
/** Add a choice option (enum-like). @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; }
/** Add an alias. @param {string} alias @returns {CommandBuilder} */
addAlias(alias) { if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this; this.aliases.push(alias.toLowerCase()); return this; }
/** Add multiple aliases. @param {...string} aliases @returns {CommandBuilder} */
addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; }
/** Set the command category. @param {string} cat @returns {CommandBuilder} */
setCategory(cat) { this.category = cat; return this; }
/** Add usage examples. @param {...string} examples @returns {CommandBuilder} */
addExamples(...examples) { this.examples.push(...examples); return this; }
}
/**
* CommandRequirement class.
*/
/** @class CommandRequirement @description Defines permission and owner-only requirements for commands. */
export class CommandRequirement {
/** @type {boolean} Whether the command is restricted to bot owners. */
ownerOnly = false;
/** Create a new CommandRequirement. */
constructor() {
this.permissions = [];
this.permissionError = "You don't have the needed permissions to run this command!";
return this;
}
/** @param {boolean} bool @returns {CommandRequirement} */
setOwnerOnly(bool) { this.ownerOnly = bool; return this; }
/**
* @param {string} p Fluxer permission string (ManageChannels", "ManageGuild")
*/
/** @param {string} p @returns {CommandRequirement} */
addPermission(p) { this.permissions.push(p); return this; }
/** @param {...string} p @returns {CommandRequirement} */
addPermissions(...p) { this.permissions.push(...p); return this; }
/** @returns {string[]} */
getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; }
/** @param {string} e @returns {CommandRequirement} */
setPermissionError(e) { this.permissionError = e; return this; }
}
/**
* Option class.
*/
/** @class Option @description Represents a command option (string, number, boolean, channel, choice, flag) with validation and formatting. */
export class Option {
/** @type {number} @description Maximum choices before switching to compact format. */
static THRESHOLD = 10;
/** @type {number} @description Number of choice columns per line in compact format. */
static COLS_PER_LINE = 5;
/** Format choice values in a compact multi-column layout. @param {string[]} choices @param {number} [perLine=Option.COLS_PER_LINE] @returns {string} */
static formatChoicesCompact(choices, perLine = Option.COLS_PER_LINE) {
const lines = [];
for (let i = 0; i < choices.length; i += perLine) {
@@ -95,6 +106,7 @@ export class Option {
return lines.join('\n');
}
/** Format choice values inline, switching to compact layout above the threshold. @param {string[]} choices @returns {string} */
static formatChoicesInline(choices) {
if (choices.length <= Option.THRESHOLD) {
return '`' + choices.join('`, `') + '`';
@@ -102,6 +114,7 @@ export class Option {
return Option.formatChoicesCompact(choices, 6);
}
/** Format choice values for a usage string, truncating with "…" if over max. @param {string[]} choices @param {number} [max=6] @returns {string} */
static formatChoicesUsage(choices, max = 6) {
if (choices.length <= max) return choices.join(' | ');
return choices.slice(0, max).join(' | ') + ' | ...';
@@ -110,12 +123,10 @@ export class Option {
userRegex = /^<@!?(?<id>\d+)>/;
idRegex = /^(?<id>\d+)/;
/** @type {Function} */
/** @type {Function|null} Dynamic default value resolver. */
dynamicDefault;
/**
* @param {string} [type="string"] Option value type — "string", "number", "boolean", "channel", "user", or "text"
*/
/** Create a new Option. @param {string} [type="string"] */
constructor(type = "string") {
this.name = null;
this.description = null;
@@ -131,33 +142,39 @@ export class Option {
this.dynamicDefault = null;
}
/** Factory to create an Option or Flag instance. @param {string} type @param {boolean} [flag=false] @returns {Option|Flag} */
static create(type, flag = false) {
return (!flag) ? new Option(type) : new Flag(type);
}
/** Set the option name. @param {string} n @returns {Option} */
setName(n) { this.name = n; this.aliases[0] = n; return this; }
/** Set the option description. @param {string} d @returns {Option} */
setDescription(d) { this.description = d; return this; }
/** Set whether the option is required. @param {boolean} r @returns {Option} */
setRequired(r) { this.required = r; return this; }
/** Set the option ID. @param {string} id @returns {Option} */
setId(id) { this.id = id; return this; }
/** Set the option type. @param {string} t @returns {Option} */
setType(t) { this.type = t; return this; }
/** Add flag aliases (e.g. "v" for "-v"). @param {...string} a @returns {Option} */
addFlagAliases(...a) { this.aliases.push(...a); return this; }
/** Add a single valid choice value. @param {string} c @returns {Option} @throws {Error} If option type is not "choice". */
addChoice(c) { if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!"); this.choices.push(c); return this; }
/** Add multiple valid choice values. @param {...string} cs @returns {Option} @throws {Error} If option type is not "choice". */
addChoices(...cs) { if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!"); cs.forEach(c => this.addChoice(c)); return this; }
/** Set the default value when the option is omitted. @param {*} value @returns {Option} */
setDefault(value) { this.defaultValue = value; return this; }
/** Set a dynamic default resolver function. @param {Function} callback @returns {Option} */
setDynamicDefault(callback) { this.dynamicDefault = callback; return this; }
/** Check whether a value is considered empty/omitted. @param {*} i @returns {boolean} */
empty(i) {
if (i === undefined || i === null) return true;
return (!i && !(String(i).includes("0")));
}
/**
* @param {string} i
* @param {Client} client
* @param {import("@fluxerjs/core").Message} msg
* @param {string} [type]
* @returns {boolean}
*/
/** Validate an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {boolean} */
validateInput(i, client, msg, type) {
switch (type || this.type) {
case "text":
@@ -189,13 +206,7 @@ export class Option {
}
}
/**
* @param {string} i
* @param {Client} client
* @param {import("@fluxerjs/core").Message} msg
* @param {string} [type]
* @returns {string|number|boolean}
*/
/** Format/parse an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {*} */
formatInput(i, client, msg, type) {
switch (type || this.type) {
case "text":
@@ -227,6 +238,7 @@ export class Option {
}
}
/** Generate a type-error message for this option. @returns {string} */
get typeError() {
if (this.tError) return this.tError;
switch (this.type) {
@@ -243,49 +255,42 @@ export class Option {
return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`";
}
}
/** Set a custom type-error message template. @param {string} e */
set typeError(e) { this.tError = e; }
}
/**
* Flag class.
*/
/** @class Flag @description A flag-type option that cannot be text. Extends Option. */
export class Flag extends Option {
/**
* @param {string} [type="string"] Flag value type — anything Option supports except "text"
*/
/** Create a Flag (non-text option). @param {string} [type="string"] */
constructor(type = "string") {
if (type === "text") throw new Error("Flags can't be of type 'text'!");
super(type);
}
}
/**
* PrefixManager class.
*/
/** @class PrefixManager @description Manages per-guild command prefixes (falling back to config or default). */
export class PrefixManager {
/** @type {SettingsManager} */
/** @type {RemoteSettingsManager} */
settings;
/** @type {string|null} Prefix from config.json — used as fallback when DB has no value */
/** @type {string|null} */
configPrefix;
/**
* @param {SettingsManager} settings Settings manager used to look up per-guild prefixes
* @param {string|null} [configPrefix=null] Fallback prefix from config.json when no DB value exists
*/
/** @param {RemoteSettingsManager} settings @param {string|null} [configPrefix=null] */
constructor(settings, configPrefix = null) { this.settings = settings; this.configPrefix = configPrefix; }
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
getPrefix(guildId) {
const serverPrefix = this.settings.getServer(guildId).get("prefix");
return serverPrefix ?? this.configPrefix ?? "%";
}
}
/**
* HelpHandler class.
*/
/** @class HelpHandler @description Generates paginated help text for commands. */
export class HelpHandler {
/** @type {CommandHandler} */
commands;
/** @type {number} Commands per help page. */
commandsPerPage = 5;
/** Default pagination handler that builds paginated help pages. @param {object} msg - Message wrapper with message data. @param {HelpHandler} helpHandler @param {Array} cmds @returns {string|null} */
paginationHandler = (msg, helpHandler, cmds) => {
const guildId = msg.message.guildId;
let form = this.commands.t(guildId, "cmdHandler.help.pageStructure");
@@ -302,35 +307,39 @@ export class HelpHandler {
return null;
}
/** @type {Function|null} Custom help handler function override. */
customHelpHandler = null;
/**
* @param {CommandBuilder[]} commands Loaded command list to generate help pages from
*/
/** @param {CommandHandler} commands */
constructor(commands) { this.commands = commands; }
/** @param {string} string @returns {string} Capitalised first letter. */
static capitalise(string) {
if (string.length < 1) return string;
if (string.length === 1) return string.toUpperCase();
return string.charAt(0).toUpperCase() + string.slice(1);
}
/** @param {Array} [cmds] @returns {Array} Non-owner-only commands. */
userCommands(cmds) {
return (cmds || this.commands.commands).filter(c =>
c.requirements.findIndex(r => r.ownerOnly) === -1
);
}
/** @returns {number} Total number of help pages. */
pageNumber() {
return Math.ceil(this.commands.commands.length / this.commandsPerPage);
}
/** @param {object} message @returns {string|null} */
help(message) {
if (this.customHelpHandler) return this.customHelpHandler(message);
if (this.paginationHandler) return this.genHelp(null, message, true);
return this.getHelpPage(0, message);
}
/** @param {number} n @param {object} msg @param {Array} [cmds=null] @returns {string} */
getHelpPage(n, msg, cmds = null) {
if (!cmds) cmds = this.commands.commands;
if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds);
@@ -340,6 +349,7 @@ export class HelpHandler {
return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands);
}
/** @param {object|null} page @param {object} msg @param {boolean} [paginate=false] @param {Array} [cmds=null] @returns {string} */
genHelp(page, msg, paginate = false, cmds = null) {
cmds = this.userCommands(cmds);
if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds);
@@ -357,8 +367,10 @@ export class HelpHandler {
return this.commands.format(content, guildId);
}
/** Get the description of a command. @param {CommandBuilder} command @returns {string} */
commandDescription(command) { return command.description; }
/** Build a usage string for a command including options and flags. @param {CommandBuilder} cmd @param {object} msg @returns {string} */
commandUsage(cmd, msg) {
if (cmd.subcommands.length > 0) {
return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]";
@@ -375,6 +387,7 @@ export class HelpHandler {
return options.trim();
}
/** Generate detailed help for a single command. @param {object} command @param {object} msg @returns {string} */
getCommandHelp(command, msg) {
const guildId = msg.message.guildId;
let content = `${HelpHandler.capitalise(command.name)}\n`;
@@ -420,39 +433,33 @@ export class HelpHandler {
}
}
/**
* CommandHandler class.
*/
/** @class CommandHandler @description Main command dispatcher. Parses incoming messages, matches commands, validates arguments, checks permissions, and emits run events. @extends {EventEmitter} */
export class CommandHandler extends EventEmitter {
/** @type {Function|null} Custom handler when the bot is pinged. */
onPing = null;
/** @type {boolean} Whether the bot responds to pings as a prefix. */
pingPrefix = true;
/** @type {string[]} Bot owner user IDs. */
owners = [];
/** @type {MessageHandler} */
messages;
/** @type {Client} */
client;
/** @type {PrefixManager} */
prefixes;
/** @type {HelpHandler} */
helpHandler;
commandNames = [];
/** @type {CommandBuilder[]} */
commands = [];
/** @type {import('./constants/Locale.mjs').Locale|null} */
locale = null;
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`";
textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string.";
/** @private @type {Map<string, number>} Per-user last command timestamps for cooldown enforcement. */
_cmdCooldowns = new Map();
/** @private @type {number} Cooldown duration in milliseconds between commands per non-owner user. */
_cmdCooldownMs = 1500;
/**
* @param {MessageHandler} handler MessageHandler instance to listen for incoming messages on
* @param {string} [prefix="%"] Default command prefix used when no per-guild prefix is set
*/
/** @param {MessageHandler} handler - The message handler instance. @param {string} [prefix="%"] - Default command prefix. */
constructor(handler, prefix = "%") {
super();
this.messages = handler;
@@ -466,25 +473,24 @@ export class CommandHandler extends EventEmitter {
this.messages.onMessage(this.messageHandler.bind(this));
}
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
getPrefix(guildId) { return this.prefixes.getPrefix(guildId); }
/** Enable or disable ping-as-prefix. @param {boolean} bool */
setPingPrefix(bool) { this.pingPrefix = bool; }
/** Set the prefix manager instance. @param {PrefixManager} manager */
setPrefixManager(manager) { this.prefixes = manager; }
/** Set a custom help handler. @param {HelpHandler} handler */
setHelpHandler(handler) { this.helpHandler = handler; }
/** @param {import('./constants/Locale.mjs').Locale} locale */
/** Set the locale manager. @param {object} locale */
setLocale(locale) { this.locale = locale; }
/**
* Translate a locale key for a given guild.
* @param {string} guildId
* @param {string} key
* @param {Object} [replacements={}]
* @returns {string}
*/
/** Translate a locale key. @param {string} guildId @param {string} key @param {object} [replacements={}] @returns {string} */
t(guildId, key, replacements = {}) {
if (!this.locale) return key;
return this.locale.translate(guildId, key, replacements);
}
/** Replace $prefix and $helpCmd placeholders in text. @param {string} text @param {string} guildId @returns {string} */
format(text, guildId) {
const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId);
return text
@@ -492,6 +498,7 @@ export class CommandHandler extends EventEmitter {
.replace(/\$helpCmd/gi, this.helpCommand);
}
/** Remove a command from the registry. @param {CommandBuilder} command */
removeCommand(command) {
command.aliases.forEach(a => {
const idx = this.commandNames.indexOf(a);
@@ -501,6 +508,7 @@ export class CommandHandler extends EventEmitter {
if (idx !== -1) this.commands.splice(idx, 1);
}
/** @private Handle an incoming message and route to command processing. @param {Message} msg */
messageHandler(msg) {
if (!msg || !msg.content) return;
const trimmed = msg.content.trim();
@@ -574,6 +582,7 @@ export class CommandHandler extends EventEmitter {
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
}
/** Parse and execute a command with its options. @param {CommandBuilder} cmd @param {string[]} args @param {Message} msg @param {string|boolean} [previous=false] @param {boolean} [external=false] @returns {object|undefined} */
processCommand(cmd, args, msg, previous = false, external = false) {
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
@@ -619,6 +628,7 @@ export class CommandHandler extends EventEmitter {
const opts = [];
const texts = [];
/** @private Collect quoted arguments spanning multiple tokens. @param {number} index @param {string} currVal @param {string[]} as @returns {{args: string[], index: number}|null} */
const collectArguments = (index, currVal, as) => {
const lastChar = currVal.charAt(currVal.length - 1);
if (lastChar === '"') return { args: as, index };
@@ -733,9 +743,7 @@ export class CommandHandler extends EventEmitter {
return commandRunData;
}
/**
* Checks requirements using fluxerjs permission API.
*/
/** Check whether the message author meets all command requirements (owner, permissions). @param {CommandBuilder} cmd @param {Message} msg @returns {boolean} */
assertRequirements(cmd, msg) {
const authorId = msg.message?.author?.id;
const isOwner = this.owners.includes(authorId);
@@ -781,9 +789,12 @@ export class CommandHandler extends EventEmitter {
return true;
}
/** Validate an input for a given option type. @param {string} type @param {*} i @param {object} m @returns {boolean} */
validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); }
/** Format an input for a given option type. @param {string} type @param {*} i @param {object} m @returns {*} */
formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); }
/** @private Build a type-error message for an option. @param {string} guildId @param {Option} option @param {*} value @param {string} previous @returns {string} */
_optionTypeError(guildId, option, value, previous) {
if (option.tError) {
return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
@@ -802,10 +813,12 @@ export class CommandHandler extends EventEmitter {
}).replace(/\$previousCmd/gi, previous);
}
/** @private Build a text-wrap error message. @param {string} guildId @param {string} value @param {string} quote @returns {string} */
_textWrapErrorMsg(guildId, value, quote) {
return this.t(guildId, 'cmdHandler.textWrapError', { $value: value, $quote: quote });
}
/** Register a command builder and sort the command list alphabetically. @param {CommandBuilder} builder @returns {CommandBuilder[]} */
addCommand(builder) {
this.commandNames.push(...builder.aliases);
this.commands.push(builder);
@@ -818,22 +831,18 @@ export class CommandHandler extends EventEmitter {
}
}
/**
* CommandLoader class.
*/
/** @class CommandLoader @description Dynamically loads command files from a directory, registers builders, and binds run handlers. */
export class CommandLoader {
/** @type {CommandHandler} */
/** @type {CommandHandler} Reference to the command handler. */
commands;
/** @type {Map<string, string>} */
/** @type {Map<string, string>} Command UID → file path. */
commandFiles = new Map();
/** @type {Map<string, Function>} */
/** @type {Map<string, Function>} Command UID → run function. */
runnables = new Map();
/** @type {object} Shared context (the bot instance). */
context;
/**
* @param {Map<string, CommandBuilder>} commands Map that loaded commands will be registered into
* @param {Object} context Shared context object (client, settings, locale, etc.) passed to command factories
*/
/** @param {CommandHandler} commands @param {object} context - Bot context object. */
constructor(commands, context) {
this.commands = commands;
this.context = context;
@@ -865,11 +874,7 @@ export class CommandLoader {
});
}
/**
* Normalise both ESM named-export shape and legacy default-export shape.
* Named ESM: export const command; export function run; export const exportDef
* Legacy CJS: module.exports = { command, run, export }
*/
/** Normalize a module export to { command, run, exportDef }. @param {object} cData @returns {object} */
canonData(cData) {
if (cData.command !== undefined) {
return {
@@ -886,6 +891,7 @@ export class CommandLoader {
};
}
/** @async Load all command files from a directory. @param {string} dir @returns {Promise<undefined[]>} */
loadFromDir(dir) {
const files = fs.readdirSync(dir)
.filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs")));
+644
View File
@@ -0,0 +1,644 @@
/** @module src/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. */
import { logger } from "./constants/Logger.mjs";
import { WebMOpusMuxer } from "./constants/audio/WebMOpusMuxer.mjs";
import { EventEmitter } from "node:events";
import { Readable } from "node:stream";
import http from "node:http";
import https from "node:https";
import prismMedia from "prism-media";
const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus;
/** @type {number} @description Maximum number of HTTP redirect hops to follow. */
const MAX_REDIRECTS = 5;
/** @type {number} @description PCM sample rate expected from NodeLink loadstream (48kHz stereo s16le). */
const PCM_RATE = 48000;
/** @type {number} @description PCM channel count expected from NodeLink loadstream. */
const PCM_CHANNELS = 2;
/** @type {number} @description Opus frame size in samples per channel (20ms @ 48kHz). */
const PCM_FRAME_SIZE = 960;
/** @type {number} @description Opus encoding bitrate. */
const OPUS_BITRATE = 128000;
/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */
const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
/** @type {Buffer} @description OGG container magic bytes ("OggS"). */
const OGG_MAGIC = Buffer.from("OggS", "ascii");
/** @extends {EventEmitter} */
export class FluxerAudioBridge extends EventEmitter {
_conn = null;
_stream = null;
_encoder = null;
_sourceStream = null;
_playing = false;
_stopped = false;
_startedAt = 0;
_currentUri = null;
_lavalink = null;
_playGeneration = 0;
_durationTimer = null;
_endResolve = null;
_endReject = null;
_usedTrackstream = false;
/** @type {boolean} @description Whether audio is currently playing. */
get playing() { return this._playing; }
/** @type {number} @description Timestamp (ms) when playback started. */
get startedAt() { return this._startedAt; }
/** @type {string|null} @description URI of the currently playing track. */
get currentUri() { return this._currentUri; }
/** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */
constructor(lavalinkManager = null) {
super();
this._lavalink = lavalinkManager;
}
/**
* Play a track through a Fluxer voice connection, entirely in-process.
* Routing order:
* 1. trackstream passthrough (seek=0, no filters) — NodeLink hands back a WebM/Opus
* direct URL which the voice connection plays natively (zero re-encode).
* 2. loadstream — NodeLink returns raw PCM (48k stereo s16le) with server-side
* seek/filters; PCM is Opus-encoded in-process and muxed to WebM.
* 3. direct URL fallback — magic-byte sniff: WebM passthrough or Ogg/Opus remux.
* @param {object} conn - Fluxer voice connection
* @param {object} trackInfo - Track metadata (encoded, title, url, guildId)
* @param {object} [options]
* @param {number} [options.seekSeconds=0]
* @param {number} [options.durationMs=0]
* @param {object} [options.filterPayload]
* @returns {Promise<"finished"|"stopped">}
*/
async play(conn, trackInfo, options = {}) {
this.stop();
if (!conn) throw new Error("[AudioBridge] No voice connection provided");
const generation = ++this._playGeneration;
this._conn = conn;
this._playing = true;
this._stopped = false;
this._startedAt = Date.now();
this._currentUri = trackInfo?.url ?? trackInfo?.title ?? "unknown";
this._usedTrackstream = false;
const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000);
const durationMs = options.durationMs || 0;
try {
// --- Route 1: trackstream passthrough (no re-encode at all) ---
if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) {
try {
const direct = await this._getTrackstreamUrl(trackInfo);
if (direct?.url && /webm|opus/i.test(direct.format || "")) {
this._usedTrackstream = true;
logger.player("[AudioBridge] Passthrough webm/opus via trackstream (zero-copy): " + (trackInfo.title || "unknown"));
await conn.play(direct.url);
if (generation !== this._playGeneration) return "stopped";
if (durationMs > 0) await this._waitDuration(durationMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (trackstream passthrough)");
return "finished";
}
return "stopped";
}
logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), using loadstream");
} catch (e) {
logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message);
this._playing = true;
this._stopped = false;
this._startedAt = Date.now();
}
}
// --- Route 2: loadstream (PCM -> in-process Opus encode -> WebM) ---
if (trackInfo.encoded && this._lavalink) {
const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload);
if (generation !== this._playGeneration) {
loaded.stream.destroy();
return "stopped";
}
const routed = await this._routeByMagic(loaded.stream);
this._sourceStream = loaded.stream;
if (routed.kind === "webm") {
logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") +
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : ""));
this._stream = routed.stream;
await conn.play(routed.stream);
} else if (routed.kind === "ogg") {
logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown"));
this._stream = await this._remuxOggToWebM(routed.stream);
await conn.play(this._stream);
} else {
logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") +
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") +
(options.filterPayload ? " [filters]" : ""));
this._stream = this._buildPcmPipeline(routed.stream);
await conn.play(this._stream);
}
if (generation !== this._playGeneration) return "stopped";
await this._awaitEnd(durationMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (loadstream)");
return "finished";
}
return "stopped";
}
// --- Route 3: direct URL fallback (magic sniff: webm passthrough / ogg remux) ---
if (trackInfo.url && trackInfo.url.startsWith("http")) {
logger.player("[AudioBridge] Fetching directly: " + trackInfo.url.substring(0, 80) + "...");
const response = await fetch(trackInfo.url, {
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
redirect: "follow",
});
if (!response.ok) {
throw new Error("HTTP " + response.status + " for " + trackInfo.url);
}
const stream = Readable.fromWeb(response.body);
this._sourceStream = stream;
const routed = await this._routeByMagic(stream);
if (routed.kind === "webm") {
this._stream = routed.stream;
await conn.play(routed.stream);
} else if (routed.kind === "ogg") {
this._stream = await this._remuxOggToWebM(routed.stream);
await conn.play(this._stream);
} else {
throw new Error(
"[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " +
"Resolve the track through the Lavalink node instead — in-process playback has no FFmpeg decoder."
);
}
if (generation !== this._playGeneration) return "stopped";
await this._awaitEnd(durationMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (direct URL)");
return "finished";
}
return "stopped";
}
throw new Error("Could not get audio stream for: " + (trackInfo.title || trackInfo.url || "unknown"));
} catch (e) {
if (generation !== this._playGeneration) return "stopped";
if (this._stopped || !this._playing) return "stopped";
this._playing = false;
logger.error("[AudioBridge] Playback error: " + e.message);
throw e;
} finally {
this._cleanup();
}
}
/**
* Wait for playback end: duration timer for fixed-length tracks, pipeline
* end event for live/radio streams (durationMs = 0). Rejects early on
* pipeline errors so the player can skip to the next track.
* @param {number} durationMs
* @returns {Promise<void>}
* @private
*/
_awaitEnd(durationMs) { return new Promise((resolve, reject) => {
this._endResolve = resolve;
this._endReject = reject;
const failFast = (err) => {
if (this._playing && !this._stopped) {
this._playing = false;
reject(err);
} else {
resolve();
}
};
if (durationMs > 0) {
this._durationTimer = setTimeout(resolve, durationMs);
} else {
// No duration info (radio/live): wait until the WebM stream is fully consumed.
const stream = this._stream;
if (!stream) return resolve();
const onEnd = () => resolve();
stream.once("end", onEnd);
stream.once("close", onEnd);
stream.once("error", failFast);
}
if (this._sourceStream) {
this._sourceStream.once("error", failFast);
}
if (this._encoder) {
this._encoder.once("error", failFast);
}
});
}
/**
* Simple timed wait used by the trackstream passthrough route (no local
* pipeline to watch). Resolves early if stopped.
* @param {number} durationMs
* @returns {Promise<void>}
* @private
*/
_waitDuration(durationMs) {
return new Promise((resolve) => {
const timer = setTimeout(() => {
this._durationTimer = null;
resolve();
}, durationMs);
this._durationTimer = timer;
});
}
/**
* Peek at the first bytes of a stream and classify it, pushing the peeked
* bytes back so nothing is lost.
* @param {Readable} stream
* @returns {Promise<{stream: Readable, kind: "webm"|"ogg"|"pcm"}>}
* @private
*/
async _routeByMagic(stream) {
const head = await this._peek(stream, 4);
if (head.length >= 4 && head.subarray(0, 4).equals(WEBM_MAGIC)) return { stream, kind: "webm" };
if (head.length >= 4 && head.subarray(0, 4).equals(OGG_MAGIC)) return { stream, kind: "ogg" };
return { stream, kind: "pcm" };
}
/**
* Read up to `n` bytes from a paused-mode stream, then unshift them.
* @param {Readable} stream
* @param {number} n
* @returns {Promise<Buffer>}
* @private
*/
_peek(stream, n) {
return new Promise((resolve, reject) => {
const tryRead = () => {
const chunks = [];
let total = 0;
let chunk;
while (total < n && (chunk = stream.read()) !== null) {
chunks.push(chunk);
total += chunk.length;
}
if (total >= n || stream.readableEnded) {
const buf = Buffer.concat(chunks);
cleanup();
if (buf.length > 0) stream.unshift(buf);
resolve(buf.subarray(0, n));
return;
}
waitForMore();
};
const onReadable = () => { cleanup(); tryRead(); };
const onEnd = () => { cleanup(); tryRead(); };
const onError = (err) => { cleanup(); reject(err); };
const cleanup = () => {
stream.off("readable", onReadable);
stream.off("end", onEnd);
stream.off("error", onError);
};
stream.once("readable", onReadable);
stream.once("end", onEnd);
stream.once("error", onError);
tryRead();
});
}
/**
* Build the in-process PCM -> Opus -> WebM pipeline.
* @param {Readable} pcmStream - s16le 48kHz stereo byte stream
* @returns {WebMOpusMuxer} - byte stream consumable by conn.play()
* @private
*/
_buildPcmPipeline(pcmStream) {
let encoder;
try {
encoder = new PrismOpusEncoder({
rate: PCM_RATE,
channels: PCM_CHANNELS,
frameSize: PCM_FRAME_SIZE,
});
} catch (e) {
pcmStream.destroy();
throw new Error(
"No Opus encoder available (" + e.message + "). Install one: npm install @discordjs/opus (or opusscript)"
);
}
try { encoder.setBitrate(OPUS_BITRATE); } catch (_) {}
const muxer = new WebMOpusMuxer({ sampleRate: PCM_RATE, channels: PCM_CHANNELS });
this._encoder = encoder;
pcmStream.on("error", (err) => {
logger.warn("[AudioBridge] PCM source error: " + err.message);
encoder.destroy(err);
});
encoder.on("error", (err) => {
muxer.destroy(err);
});
pcmStream.pipe(encoder).pipe(muxer);
return muxer;
}
/**
* Remux an Ogg/Opus stream into WebM/Opus (packet-level, no re-encode).
* @param {Readable} oggStream
* @returns {Promise<WebMOpusMuxer>}
* @private
*/
async _remuxOggToWebM(oggStream) {
const demuxer = new PrismOggDemuxer();
const muxer = new WebMOpusMuxer();
oggStream.on("error", (err) => demuxer.destroy(err));
demuxer.on("error", (err) => muxer.destroy(err));
// Wait for the OpusHead so we reject non-Opus OGG early with a clear error.
const headPromise = new Promise((resolve, reject) => {
demuxer.once("head", () => resolve());
demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message)));
oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message)));
});
oggStream.pipe(demuxer).pipe(muxer);
await headPromise;
return muxer;
}
/**
* @param {object} trackInfo
* @returns {Promise<{url: string, format: string}>}
* @private
*/
async _getTrackstreamUrl(trackInfo) {
const nlInfo = this._lavalink.getNodeLinkInfo?.();
if (!nlInfo) throw new Error("NodeLink info not available");
const protocol = nlInfo.secure ? "https" : "http";
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
const headers = { "Authorization": nlInfo.password };
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
const params = "encodedTrack=" + encodeURIComponent(trackInfo.encoded);
const url = baseUrl + "/v4/trackstream?" + params;
logger.player("[AudioBridge] Querying /v4/trackstream...");
const body = await this._httpGetJson(url, headers);
const directUrl = body?.url;
if (!directUrl || typeof directUrl !== "string") {
throw new Error("trackstream returned no URL");
}
const format = body?.format || "";
logger.player("[AudioBridge] trackstream: format=" + format + " url=" + directUrl.substring(0, 100) + "...");
return { url: directUrl, format };
}
/**
* @param {object} trackInfo
* @param {number} [seekMs=0]
* @param {object|null} [filterPayload]
* @returns {Promise<{stream: Readable, inputFormat: string|null}>}
* @private
*/
async _streamFromLoadstream(trackInfo, seekMs = 0, filterPayload = null) {
const nlInfo = this._lavalink.getNodeLinkInfo?.();
if (!nlInfo) {
throw new Error("NodeLink info not available");
}
const protocol = nlInfo.secure ? "https" : "http";
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
const headers = { "Authorization": nlInfo.password };
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
let baseParams = "encodedTrack=" + encodeURIComponent(trackInfo.encoded) + "&position=" + seekMs + "&volume=100";
if (filterPayload) {
baseParams += "&filters=" + encodeURIComponent(JSON.stringify(filterPayload));
}
const url = baseUrl + "/v4/loadstream?" + baseParams;
logger.player("[AudioBridge] Querying /v4/loadstream (seek: " + seekMs + "ms)...");
return this._httpRequestStream(url, headers);
}
/**
* @param {string} url
* @param {object} [headers]
* @returns {Promise<object>}
* @private
*/
_httpGetJson(url, headers = {}, _redirectCount = 0) {
return new Promise((resolve, reject) => {
if (_redirectCount >= MAX_REDIRECTS) {
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
}
const urlObj = new URL(url);
const client = urlObj.protocol === "https:" ? https : http;
const req = client.request({
protocol: urlObj.protocol,
host: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname + urlObj.search,
method: "GET",
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
}, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
res.resume();
let loc = res.headers.location;
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
return this._httpGetJson(loc, headers, _redirectCount + 1).then(resolve, reject);
}
if (res.statusCode !== 200) {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
});
return;
}
let data = "";
res.on("data", (chunk) => { data += chunk; });
res.on("end", () => {
try {
resolve(JSON.parse(data));
} catch (e) {
reject(new Error("Invalid JSON from trackstream: " + data.substring(0, 200)));
}
});
});
req.on("error", reject);
req.setTimeout(15_000, () => {
req.destroy();
reject(new Error("trackstream timeout (15s)"));
});
req.end();
});
}
/**
* @param {string} url
* @param {object} [headers]
* @param {number} [_redirectCount=0]
* @returns {Promise<{stream: Readable, inputFormat: string|null}>}
* @private
*/
_httpRequestStream(url, headers = {}, _redirectCount = 0) {
return new Promise((resolve, reject) => {
if (_redirectCount >= MAX_REDIRECTS) {
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
}
const urlObj = new URL(url);
const client = urlObj.protocol === "https:" ? https : http;
const req = client.request({
protocol: urlObj.protocol,
host: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname + urlObj.search,
method: "GET",
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
}, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
res.resume();
let nextHeaders = headers;
let loc = res.headers.location;
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
try {
const redirectHost = new URL(loc).hostname;
if (redirectHost !== urlObj.hostname) {
const { Authorization, "Session-Id": _, ...safe } = headers;
nextHeaders = safe;
}
} catch (_) {}
return this._httpRequestStream(loc, nextHeaders, _redirectCount + 1).then(resolve, reject);
}
if (res.statusCode !== 200) {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
});
return;
}
logger.player("[AudioBridge] loadstream response: " + res.statusCode + " content-type=" + (res.headers["content-type"] || "?"));
resolve({ stream: res, inputFormat: res.headers["content-type"] || null });
});
req.on("error", reject);
req.setTimeout(30_000, () => {
req.destroy();
reject(new Error("loadstream timeout (30s)"));
});
req.end();
});
}
/** Stop current playback and clean up resources. */
stop() {
const wasPlaying = this._playing;
this._stopped = true;
this._playing = false;
this._playGeneration++;
this._cleanup();
if (this._conn) {
try { this._conn.stop(); } catch (_) {}
}
if (wasPlaying) {
this.emit("stopped");
logger.player("[AudioBridge] Playback stopped");
}
}
/**
* Set the playback volume on the voice connection.
* @param {number} percent - Volume 0–100.
*/
setVolume(percent) {
if (this._conn) {
try { this._conn.setVolume(percent); } catch (e) {
logger.warn("[AudioBridge] setVolume error: " + e.message);
}
}
}
/** @returns {number} Current volume percentage (0–100). */
getVolume() {
if (this._conn) {
try { return this._conn.getVolume(); } catch (_) {}
}
return 100;
}
/** @returns {boolean} Whether the voice connection is currently active. */
isConnected() {
if (this._conn) {
try { return this._conn.isConnected(); } catch (_) {}
}
return false;
}
/**
* Clear timers, settle pending waits, and tear down the pipeline.
* @private
*/
_cleanup() {
if (this._durationTimer) { clearTimeout(this._durationTimer); this._durationTimer = null; }
if (this._endResolve) {
const resolve = this._endResolve;
this._endResolve = null;
this._endReject = null;
resolve();
}
for (const s of [this._stream, this._encoder, this._sourceStream]) {
if (s) {
try { s.destroy(); } catch (_) {}
}
}
this._stream = null;
this._encoder = null;
this._sourceStream = null;
}
/** Stop playback, release the voice connection, and remove all listeners. */
destroy() {
this.stop();
this._conn = null;
this._currentUri = null;
this.removeAllListeners();
}
}
+11 -80
View File
@@ -1,19 +1,4 @@
/**
* @file FluxerListManager.mjs — FluxerListManager — FluxerList bot listing API client for vote checking and server stats
* @module src.FluxerListManager
*/
/**
* FluxerListManager.mjs — FluxerList API client for voter data queries.
*
* Features:
* - Fetch paginated voter lists for servers and bots
* - Bearer token authentication (fl_ prefixed API keys)
* - In-memory response caching with configurable TTL
* - Graceful error handling (401/403 auth errors, network failures)
*
* FluxerList API docs: https://fluxerlist.com/api/v1
*/
/** @module src/FluxerListManager @description FluxerList API integration for fetching server/bot voter lists with caching. */
import { logger } from "./constants/Logger.mjs";
import {
@@ -23,18 +8,9 @@ import {
buildFluxerListUrl,
} from "./constants/API.mjs";
/**
* FluxerListManager class.
*/
/** @class FluxerListManager @description Fetches and caches voter lists from the FluxerList API for servers and bots. */
export class FluxerListManager {
/**
* @param {object} config - The `fluxerlist` section from config.json
* @param {string} [config.apiKey] - FluxerList API key (prefixed with fl_)
* @param {string} [config.serverId] - Default server ID or slug for voter queries
* @param {string} [config.botId] - Default bot ID or slug for voter queries
* @param {string} [config.serverSlug] - Server URL slug for website links (e.g. "remix-hq")
* @param {string} [config.botSlug] - Bot URL slug for website links (e.g. "remix")
*/
/** @param {object} [config={}] @param {string} [config.apiKey] @param {string} [config.serverId] @param {string} [config.botId] @param {string} [config.serverSlug] @param {string} [config.botSlug] */
constructor(config = {}) {
this.apiKey = config?.apiKey ?? "";
this.serverId = config?.serverId ?? "";
@@ -52,23 +28,12 @@ export class FluxerListManager {
}
}
/**
* Generate a cache key from the request parameters.
* @param {"server"|"bot"} type
* @param {string} id
* @param {number} page
* @param {number} limit
* @returns {string}
*/
/** @private @param {string} type @param {string} id @param {number} page @param {number} limit @returns {string} */
_cacheKey(type, id, page, limit) {
return `${type}:${id}:p${page}:l${limit}`;
}
/**
* Get a cached response if still fresh.
* @param {string} key
* @returns {object|null}
*/
/** @private @param {string} key @returns {object|null} */
_getCached(key) {
const entry = this._cache.get(key);
if (!entry) return null;
@@ -79,12 +44,7 @@ export class FluxerListManager {
return entry.data;
}
/**
* Store a response in the cache with the configured TTL.
* @param {string} key
* @param {object} data
* @param {number} [ttlMs] - Override TTL in milliseconds
*/
/** @private @param {string} key @param {object} data @param {number} [ttlMs] */
_setCached(key, data, ttlMs) {
this._cache.set(key, {
data,
@@ -99,18 +59,7 @@ export class FluxerListManager {
}
}
/**
* Fetch the list of voters for a server or bot.
*
* @param {"server"|"bot"} type - Resource type
* @param {string} [id] - Server or bot ID or slug (falls back to config default)
* @param {object} [options]
* @param {number} [options.page=1] - Page number (1-based)
* @param {number} [options.limit=50] - Results per page (max 100)
* @param {boolean} [options.skipCache=false] - Bypass cache and fetch fresh data
* @returns {Promise<{ total: number, page: number, limit: number, voters: Array<{ username: string, fluxerId: number, votedAt: string }> }>}
* @throws {Error} If the API key is missing or the request fails
*/
/** @async Fetch voters from FluxerList API. @param {"server"|"bot"} type @param {string} [id] @param {object} [options={}] @param {number} [options.page] @param {number} [options.limit] @param {boolean} [options.skipCache] @returns {Promise<object>} @throws {Error} On auth, not-found, or HTTP errors. */
async getVoters(type, id, options = {}) {
this._assertEnabled();
@@ -173,36 +122,17 @@ export class FluxerListManager {
return data;
}
/**
* Convenience: fetch voters for a server.
* @param {string} [id] - Server ID or slug (falls back to config default)
* @param {object} [options] - Same as getVoters options
* @returns {Promise<object>}
*/
/** @async @param {string} [id] @param {object} [options] @returns {Promise<object>} */
async getServerVoters(id, options = {}) {
return this.getVoters("server", id, options);
}
/**
* Convenience: fetch voters for a bot.
* @param {string} [id] - Bot ID or slug (falls back to config default)
* @param {object} [options] - Same as getVoters options
* @returns {Promise<object>}
*/
/** @async @param {string} [id] @param {object} [options] @returns {Promise<object>} */
async getBotVoters(id, options = {}) {
return this.getVoters("bot", id, options);
}
/**
* Fetch ALL voters across all pages for a resource.
* Use with caution on resources with many voters — this makes multiple API calls.
*
* @param {"server"|"bot"} type
* @param {string} [id] - Resource ID or slug
* @param {object} [options]
* @param {number} [options.limit=100] - Results per page (uses max to minimize calls)
* @returns {Promise<Array<{ username: string, fluxerId: number, votedAt: string }>>}
*/
/** @async Fetch all pages of voters for a resource. @param {"server"|"bot"} type @param {string} [id] @param {object} [options] @returns {Promise<Array>} */
async getAllVoters(type, id, options = {}) {
this._assertEnabled();
@@ -223,6 +153,7 @@ export class FluxerListManager {
return allVoters;
}
/** @private @throws {Error} If not configured. */
_assertEnabled() {
if (!this.enabled) {
throw new Error("FluxerList integration is not configured (missing apiKey in config.json).");
+141 -314
View File
@@ -1,8 +1,4 @@
/**
* @file GatewayHandler.mjs — GatewayHandler — processes raw WebSocket events for voice state tracking, 24/7 recovery, and guild lifecycle
* @module src.GatewayHandler
*/
/** @module src/GatewayHandler @description Handles all Discord gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. */
import { Events, GatewayOpcodes } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice";
import { logger, _wsErrorCooldown } from "./constants/Logger.mjs";
@@ -13,16 +9,11 @@ import { REQUIRED_BOT_PERMISSIONS } from "./MessageHandler.mjs";
import { cleanId } from "./Utils.mjs";
import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "./constants/VoiceStateResolver.mjs";
/**
* GatewayHandler — manages raw WebSocket gateway events, voice-state tracking,
* presence rotation, and high-level Fluxer event handlers (GuildCreate,
* GuildDelete, VoiceStateUpdate).
*
* Extracted from index.mjs to reduce the Remix constructor footprint.
*/
/** @class GatewayHandler @description Handles all Discord gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. Key responsibilities include voice state cache seeding and updates, bot move-away detection with 24/7 rejoin scheduling, boot recovery with sequential rejoin of 24/7 channels, inactivity timer management on human join/leave, and guild create/delete handling with startup grace period. */
export class GatewayHandler {
/**
* @param {import('../../index.mjs').Remix} remix The running bot instance.
* Create a new GatewayHandler.
* @param {import('../index.mjs').Remix} remix - The bot context.
*/
constructor(remix) {
this.remix = remix;
@@ -40,31 +31,21 @@ export class GatewayHandler {
this.presenceTimer = null;
this.presenceIndex = 0;
/** @type {Map<string, {channelId, guildId}>} guildId:userId → state */
this._prevVoiceState = new Map();
/** @type {Map<string, {guild, timer}>} guildId → deferred cleanup data */
this._deferredGuildDeletes = new Map();
/** @type {number} How long to defer GuildDelete processing during startup (ms) */
this._startupDeleteGraceMs = 15_000;
/** @type {boolean} Whether we're still in the startup grace period */
this._inStartupGrace = true;
/** @type {number} Counter for deferred deletions (used for batch summary log) */
this._deferredDeleteCount = 0;
/** @type {number} Timestamp of the last Events.Ready fire (initial + reconnects). 0 = never. */
this._lastReadyAt = 0;
/** @type {number} Window after a Ready event during which voice disconnects are treated as WS-induced (ms). */
this._wsReconnectGraceMs = 30_000;
/** @type {number} How recently another player in the same guild must have connected to count as move evidence, vs. a long-stable second 24/7 channel (ms). */
this._moveEvidenceWindowMs = 10_000;
}
/**
* Check whether a voice disconnect was likely caused by a recent WS reconnect
* rather than a user-initiated leave. Uses the time since the last Events.Ready
* fire as the signal — if the bot just re-identified, any voice session
* invalidation is almost certainly WS-induced.
* Check whether a WebSocket reconnect happened recently (within 30s).
* Used to treat transient disconnects as non-24/7-requiring.
* @returns {boolean}
*/
isWsReconnectRecent() {
@@ -72,22 +53,21 @@ export class GatewayHandler {
return Date.now() - this._lastReadyAt < this._wsReconnectGraceMs;
}
/**
* Generate a composite key for bots in the observedVoiceBots map.
* Bots can be in multiple guilds so we namespace by guildId.
*/
/** @private Build a composite bot key for voice state tracking. @param {string} userId @param {string} guildId @returns {string|null} */
getObservedVoiceBotKey(userId, guildId) {
const cleanUserId = cleanId(userId ?? "");
const cleanGuildId = cleanId(guildId ?? "");
return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : cleanUserId || null;
}
/** @private Build a previous voice state lookup key. @param {string} userId @param {string} guildId @returns {string|null} */
getPrevVoiceStateKey(userId, guildId) {
const cleanUserId = cleanId(userId ?? "");
const cleanGuildId = cleanId(guildId ?? "");
return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : null;
}
/** Find a previous voice state entry for a user. @param {string} userId @param {string|null} [guildId=null] @returns {{key: string|null, value: object|null}} */
findPrevVoiceStateEntry(userId, guildId = null) {
const directKey = this.getPrevVoiceStateKey(userId, guildId);
if (directKey && this._prevVoiceState.has(directKey)) {
@@ -107,12 +87,12 @@ export class GatewayHandler {
}
/**
* Check if the bot has all required permissions in a newly joined guild.
* If critical permissions are missing, log a warning and attempt to send
* a notification to the guild's system channel (or first text channel).
*
* @param {import('@fluxerjs/core').Guild} guild
* @param {string} guildId
* Check and warn about missing bot permissions in a guild.
* Sends an embed to the system channel if critical or optional perms are missing.
* @param {object} guild - The guild object.
* @param {string} guildId - The guild ID.
* @returns {Promise<void>}
* @private
*/
async _checkGuildPermissions(guild, guildId) {
const { remix } = this;
@@ -175,8 +155,8 @@ export class GatewayHandler {
}
/**
* Seed observedVoiceUsers / observedVoiceBots from all cached guild voice
* states. Called once on Ready after the guild cache is populated.
* Seed the voice state cache from VoiceManager or guild cache on startup.
* @private
*/
seedVoiceStatesFromGuilds() {
const { remix } = this;
@@ -229,19 +209,11 @@ export class GatewayHandler {
}
/**
* Re-read the guild's voice_states cache and update observedVoiceUsers
* for any human users found in the specified channel.
*
* This is crucial after bot recovery: when the bot restarts and rejoins a
* voice channel, the initial `seedVoiceStatesFromGuilds()` may have run
* before the guild cache was fully populated, or before the bot received
* VOICE_STATE_UPDATE events for users already in the channel. Calling
* this after a player joins ensures the bot knows about humans who were
* already present.
*
* @param {string} guildId
* @param {string} channelId
* @returns {number} Number of human users found in the channel.
* Re-seed voice states for a specific channel from multiple sources.
* Checks VoiceManager, guild cache, VoiceStateCache, and LiveKit participants.
* @param {string} guildId - The guild ID.
* @param {string} channelId - The channel ID.
* @returns {number} Number of humans found in the channel.
*/
reseedVoiceStatesForChannel(guildId, channelId) {
const { remix } = this;
@@ -370,13 +342,7 @@ export class GatewayHandler {
return humansFound;
}
/**
* Attach a raw "message" listener to the shard-0 WebSocket so we can
* process gateway opcodes (READY, GUILD_CREATE, VOICE_STATE_UPDATE, etc.)
* before @fluxerjs/core emits its high-level events.
*
* Safe to call on every reconnect — will detach from the old socket first.
*/
/** Attach a raw WebSocket listener to cache VOICE_SERVER_UPDATE events. @private */
attachRawListener() {
const { remix } = this;
const client = remix.client;
@@ -500,6 +466,7 @@ export class GatewayHandler {
} catch(e) { logger.warn("[Gateway] attachRawListener failed:", e?.message); }
}
/** Rotate the bot's presence/status text at a configured interval. @private */
setupPresenceRotation() {
if (this.presenceContents.length === 0) return;
@@ -549,8 +516,8 @@ export class GatewayHandler {
}
/**
* Register all high-level Fluxer event listeners on the Fluxer client.
* Call once during bot startup.
* Register all gateway event handlers (GuildCreate, GuildDelete, VoiceStateUpdate, VoiceStatesSync).
* Called once during bot initialisation.
*/
setupEventHandlers() {
const { remix } = this;
@@ -656,9 +623,10 @@ export class GatewayHandler {
}
/**
* Main voice state update dispatcher — calls focused sub-handlers.
* Parses the raw VOICE_STATE_UPDATE payload, computes the old channel,
* then delegates to specialised methods.
* Main handler for VOICE_STATE_UPDATE events. Routes to human or bot sub-handlers.
* @param {object} data - The voice state update payload from the gateway.
* @returns {Promise<void>}
* @private
*/
async _handleVoiceStateUpdate(data) {
const { remix } = this;
@@ -697,15 +665,7 @@ export class GatewayHandler {
this._handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, data);
}
/**
* Handle bulk voice state sync from GUILD_CREATE or READY.
* Populates VoiceStateCache with all users currently in voice channels
* for a guild. This is the PRIMARY way the bot learns about users who
* were already in voice when the bot started (before it receives any
* individual VOICE_STATE_UPDATE events).
*
* @param {{ guildId: string, voiceStates: Array<{user_id: string, channel_id: string|null, member?: {user?: {bot?: boolean}}}> }} data
*/
/** Handle VoiceStatesSync bulk event from the gateway. @param {object} data - Sync payload with voiceStates array. @private */
_handleVoiceStatesSync(data) {
const { remix } = this;
const client = remix.client;
@@ -739,10 +699,7 @@ export class GatewayHandler {
}
}
/**
* Update the voice state cache when users move between channels.
* Adds users to the cache on join, removes them on leave.
*/
/** @private Update the voice state cache for a user joining/leaving. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object|null} prev */
_updateVoiceStateCache(userId, guildId, oldChannelId, newChannelId, isBot, prev) {
const { remix } = this;
@@ -757,10 +714,7 @@ export class GatewayHandler {
}
}
/**
* Update the previous state map (LRU eviction).
* Maintains a bounded map of previous voice states for computing oldChannelId.
*/
/** @private Update the previous-voice-state map and evict stale entries. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object} prevEntry @param {object|null} prev */
_updatePreviousStates(userId, guildId, oldChannelId, newChannelId, isBot, prevEntry, prev) {
const { remix } = this;
const prevKey = prevEntry.key;
@@ -795,12 +749,7 @@ export class GatewayHandler {
}
}
/**
* Find which player is affected by this voice state change.
* Checks both old and new channels for an existing player.
*
* @returns {{ player: object|null, playerGuildId: string|null, homeChannelId: string|null }}
*/
/** @private Find a player affected by a voice state change. @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @returns {{player: Player|null, playerGuildId: string|null, homeChannelId: string|null}} */
_findAffectedPlayer(guildId, oldChannelId, newChannelId) {
const { remix } = this;
@@ -825,10 +774,7 @@ export class GatewayHandler {
return { player: null, playerGuildId: null, homeChannelId: null };
}
/**
* Manage inactivity timers when humans join/leave voice channels.
* Also handles dashboard updates for human voice state changes.
*/
/** @private Manage inactivity timers when a human joins or leaves a voice channel. @param {Player|null} player @param {string|null} playerGuildId @param {string|null} homeChannelId @param {string} userId @param {string|null} oldChannelId @param {string|null} newChannelId @param {string} vsuGuildId @param {object} vsu */
async _handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, vsu) {
const { remix } = this;
const client = remix.client;
@@ -910,8 +856,16 @@ export class GatewayHandler {
}
/**
* Handle the bot being moved to a different channel or disconnected.
* Covers 24/7 re-key on move and auto-rejoin / autoleave on disconnect.
* Handle a voice state update for the bot itself.
* Detects move-away from 24/7 channels and unexpected disconnects.
* @param {Player|null} player - The affected player (if any).
* @param {string|null} playerGuildId - The guild ID from the player.
* @param {string|null} homeChannelId - The 24/7 home channel ID from the player.
* @param {string|null} oldChannelId - The channel the bot was in.
* @param {string|null} newChannelId - The channel the bot moved to (null if disconnected).
* @param {string} vsuGuildId - The guild ID from the VSU event.
* @param {object} vsu - The raw VSU payload.
* @private
*/
_handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, vsu) {
const { remix } = this;
@@ -919,175 +873,86 @@ export class GatewayHandler {
const guildId = vsuGuildId;
if (newChannelId && guildId && oldChannelId && oldChannelId !== newChannelId) {
try {
const cleanNew = cleanId(newChannelId);
const cleanOld = cleanId(oldChannelId);
const moveSet = remix.settingsMgr.getServer(guildId);
const moveRaw = moveSet?.get("stay_247");
const saved247Channels = (!moveRaw || moveRaw === "none")
? []
: Array.isArray(moveRaw)
? moveRaw.map(id => cleanId(id)).filter(id => id.length >= 15)
: [cleanId(moveRaw)].filter(id => id.length >= 15);
if (saved247Channels.length > 1) {
// During boot recovery, ignore move events — the recovery loop handles rejoining.
if (this._bootRecoveryActive) {
logger.voice247(
`[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanNew} ` +
`because guild ${guildId} already has multiple saved 24/7 channels ` +
`[${saved247Channels.join(", ")}]`
`[247] Ignoring bot move ${cleanId(oldChannelId)} → ${cleanId(newChannelId)} during boot recovery.`
);
return;
}
try {
const cleanNew = cleanId(newChannelId);
const cleanOld = cleanId(oldChannelId);
const existingPlayer = remix.players.playerMap.get(cleanOld);
const newChannelAlreadySaved = (() => {
// Check if old channel is a saved 24/7 channel
const oldIs247 = (() => {
try {
const set = remix.settingsMgr.getServer(guildId);
const raw = set?.get("stay_247");
if (!raw || raw === "none") return false;
const saved = Array.isArray(raw)
? raw.map(id => cleanId(id)).filter(id => id.length >= 15)
: [cleanId(raw)].filter(id => id.length >= 15);
return saved.includes(cleanNew);
} catch (_) {
return false;
}
return get247ChannelMode(set, cleanOld) === "on";
} catch (_) { return false; }
})();
const newChannelPendingSpawn =
remix.players?._pendingJoins?.has?.(cleanNew) ||
false;
// Check if new channel is a saved 24/7 channel or has a pending spawn
const newChannelSaved = (() => {
try {
const set = remix.settingsMgr.getServer(guildId);
return get247ChannelMode(set, cleanNew) === "on";
} catch (_) { return false; }
})();
const newChannelPendingSpawn = remix.players?._pendingJoins?.has?.(cleanNew) || false;
const existingPlayer = remix.players.playerMap.get(cleanOld);
if (oldIs247 && existingPlayer) {
// Old channel is 24/7 — bot physically moved away, so the voice
// connection to old channel is dead. Destroy the old player and
// schedule a fresh rejoin so it gets a new live connection.
logger.voice247(
`[247] Bot moved away from 24/7 channel ${cleanOld} → ${cleanNew}. ` +
`Destroying stale player, scheduling rejoin for ${cleanOld}.`
);
remix.players.playerMap.delete(cleanOld);
const homeCh = cleanId(existingPlayer._home247Channel ?? "");
if (homeCh && homeCh !== cleanOld) remix.players.playerMap.delete(homeCh);
try { existingPlayer.destroy(); } catch (_) {}
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
setTimeout(() => {
this._rejoinChannel(cleanId(guildId), cleanOld).catch(err => {
logger.warn(`[247] Failed to rejoin ${cleanOld} after move-away:`, err.message);
});
}, rejoinDelay);
} else if (newChannelSaved || newChannelPendingSpawn) {
// New channel is already 24/7 or being spawned — keep both, don't rekey.
logger.voice247(
`[247] Keeping both channels ${cleanOld} and ${cleanNew} ` +
`(saved=${newChannelSaved} pending=${newChannelPendingSpawn})`
);
} else if (existingPlayer && cleanNew !== cleanOld) {
// Neither channel is 24/7 — safe to rekey the player.
const targetChannel = client.channels.get(cleanNew)
?? client.channels.get?.(cleanNew)
?? null;
const targetGuildId = cleanId(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? "");
const playerGuildIdLocal = cleanId(existingPlayer?._guildId ?? "");
const guildPlayers = [...remix.players.playerMap.entries()].filter(([, p]) =>
cleanId(p?._guildId ?? "") === cleanId(guildId ?? "")
);
const guildIsAmbiguous = guildPlayers.length > 1;
let rekeyed = false;
if (existingPlayer && cleanNew !== cleanOld) {
if (newChannelAlreadySaved || newChannelPendingSpawn) {
logger.voice247(
`[247] Keeping both channels ${cleanOld} and ${cleanNew} ` +
`(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
);
rekeyed = false;
} else
if (guildIsAmbiguous) {
const playerAtNewKey = remix.players.playerMap.get(cleanNew);
if (playerAtNewKey && playerAtNewKey !== existingPlayer) {
existingPlayer._channelId = cleanNew;
existingPlayer._home247Channel = cleanNew;
if (targetGuildId) existingPlayer._guildId = targetGuildId;
rekeyed = false;
logger.voice247(
`[247] Updated player channel ${cleanOld} → ${cleanNew} ` +
`(guild ${guildId} has ${guildPlayers.length} active players, ` +
`new key occupied by another player — skipped re-key)`
);
} else {
if (!playerAtNewKey || playerAtNewKey === existingPlayer) {
remix.players.playerMap.delete(cleanOld);
remix.players.playerMap.set(cleanNew, existingPlayer);
existingPlayer._channelId = cleanNew;
existingPlayer._home247Channel = cleanNew;
if (targetGuildId) existingPlayer._guildId = targetGuildId;
rekeyed = true;
logger.voice247(
`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew} ` +
`(guild ${guildId} has ${guildPlayers.length} active players)`
);
}
} else if (playerGuildIdLocal && targetGuildId && playerGuildIdLocal !== targetGuildId) {
if (!existingPlayer) {
logger.voice247(
`[247] Stale cross-guild move ${cleanOld} → ${cleanNew} ` +
`(no player in playerMap for old channel — updating bot state only)`
);
} else {
const vsuGuildIdClean = cleanId(guildId ?? "");
if (vsuGuildIdClean && targetGuildId === vsuGuildIdClean) {
existingPlayer._guildId = targetGuildId;
existingPlayer._channelId = cleanNew;
existingPlayer._home247Channel = cleanNew;
remix.players.playerMap.delete(cleanOld);
remix.players.playerMap.set(cleanNew, existingPlayer);
rekeyed = true;
logger.voice247(
`[247] Fixed stale guild during recovery: re-keyed ${cleanOld} → ${cleanNew} ` +
`(playerGuild ${playerGuildIdLocal} → ${targetGuildId})`
);
} else {
logger.warn(
`[247] Refused cross-guild re-key ${cleanOld} → ${cleanNew} ` +
`(playerGuild=${playerGuildIdLocal} targetGuild=${targetGuildId})`
);
}
}
} else {
remix.players.playerMap.delete(cleanOld);
remix.players.playerMap.set(cleanNew, existingPlayer);
existingPlayer._channelId = cleanNew;
existingPlayer._home247Channel = cleanNew;
if (targetGuildId) existingPlayer._guildId = targetGuildId;
rekeyed = true;
logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew}`);
}
}
const set = remix.settingsMgr.getServer(guildId);
const raw = set?.get("stay_247");
if ((rekeyed || existingPlayer) && raw && raw !== "none") {
const channels = Array.isArray(raw)
? new Set(raw.map(id => cleanId(id)).filter(id => id.length >= 15))
: new Set();
if (channels.has(cleanOld) && cleanOld !== cleanNew && cleanNew.length >= 15) {
if (channels.has(cleanNew) || newChannelAlreadySaved || newChannelPendingSpawn) {
} else {
logger.voice247(
`[247] Preserved stay_247 channels ${cleanOld} and ${cleanNew} ` +
`(saved=${channels.has(cleanNew) || newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
);
return;
}
const currentGuildPlayers = [...remix.players.playerMap.values()].filter(p =>
cleanId(p?._guildId ?? "") === cleanId(guildId ?? "")
);
if (currentGuildPlayers.length > 1) {
if (!channels.has(cleanNew)) {
channels.add(cleanNew);
set.set("stay_247", [...channels]);
const modes2 = set.get("stay_247_modes");
if (modes2 && typeof modes2 === "object" && !Array.isArray(modes2) && !modes2[cleanNew]) {
modes2[cleanNew] = modes2[cleanOld] ?? "auto";
set.set("stay_247_modes", modes2);
}
logger.voice247(
`[247] Added stay_247 channel ${cleanNew} (kept ${cleanOld}) — guild has ${currentGuildPlayers.length} active players`
`[247] Skipped re-key ${cleanOld} → ${cleanNew} (new key occupied by another player)`
);
}
return;
}
channels.delete(cleanOld);
channels.add(cleanNew);
set.set("stay_247", [...channels]);
const modes = set.get("stay_247_modes");
if (modes && typeof modes === "object" && !Array.isArray(modes)) {
if (modes[cleanOld] && !modes[cleanNew]) {
modes[cleanNew] = modes[cleanOld];
}
delete modes[cleanOld];
set.set("stay_247_modes", modes);
}
logger.voice247(`[247] Updated stay_247: ${cleanOld} → ${cleanNew}`);
}
}
// Simplified 24/7: stay_247 list only changes via !247 command.
// Do NOT auto-add/remove channels on bot move.
} catch (e) {
logger.warn("[247] Failed to auto-save channel:", e.message);
logger.warn("[247] Bot move handler failed:", e.message);
}
}
@@ -1115,8 +980,6 @@ export class GatewayHandler {
if (remix.intentionalLeaves.has(cleanOld)) {
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`);
} else if (remix.revoice?._intentionalDisconnects?.has?.(cleanOld)) {
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional (revoice).`);
} else if (this._isGuildMoveInProgress(cleanGuild, cleanOld)) {
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — guild move in progress, skipping.`);
} else if (this._bootRecoveryActive) {
@@ -1126,10 +989,10 @@ export class GatewayHandler {
const mode = set ? get247ChannelMode(set, cleanOld) : "off";
const wsInduced = this.isWsReconnectRecent();
if (mode === "auto" || wsInduced) {
const reason = wsInduced && mode !== "auto"
if (mode === "on" || wsInduced) {
const reason = wsInduced && mode !== "on"
? `WS reconnect detected (${Math.round((Date.now() - this._lastReadyAt) / 1000)}s ago) — treating as transient, scheduling rejoin`
: `24/7 auto mode — cleaning up and scheduling rejoin`;
: `24/7 mode — scheduling rejoin`;
logger.voice247(
`[VoiceState] Bot unexpectedly disconnected from ${cleanOld} — ${reason}.`
);
@@ -1169,31 +1032,29 @@ export class GatewayHandler {
}
}
/** @type {Set<string>} Channel IDs currently being rejoined (dedup guard) */
/** @private @type {Set<string>} @description Channel IDs currently being rejoined (duplicate guard). */
_rejoinInProgress = new Set();
/** @type {Map<string, number>} Channel IDs with retry attempt counts */
/** @private @type {Map<string, number>} @description Channel ID → retry count for exponential backoff. */
_rejoinAttempts = new Map();
/** @type {boolean} Whether boot recovery (rejoin247Channels) is currently running */
/** @private @type {boolean} @description Whether boot recovery is actively rejoining 24/7 channels. */
_bootRecoveryActive = false;
/** @type {number} Maximum number of rejoin retry attempts */
/** @type {number} @description Maximum number of rejoin retry attempts per channel. */
static MAX_REJOIN_RETRIES = 3;
/**
* Shared rejoin attempt logic with exponential backoff retry.
* Used by both _rejoinChannel (disconnect recovery) and
* rejoin247Channels (boot recovery).
*
* @param {string} channelId - Clean channel ID
* @param {string} guildId - Clean guild ID
* @param {number} [maxRetries=3] Maximum retry attempts
* @param {number} [baseDelay=5000] Base delay for exponential backoff (ms)
* @param {string} [context="Rejoin"] Log context prefix
* @returns {Promise<object|null>} The spawned player, or null on failure
* Attempt to spawn a player for a channel with exponential-backoff retries.
* @param {string} channelId - The target channel ID.
* @param {string} guildId - The guild ID.
* @param {number} [maxRetries=3] - Maximum retry attempts.
* @param {number} [baseDelay=5000] - Base delay in ms (doubled each retry).
* @param {string} [context='Rejoin'] - Label for log messages.
* @returns {Promise<Player|null>} The spawned player, or null if all retries failed.
* @private
*/
async _attemptRejoin(channelId, guildId, maxRetries = 3, baseDelay = 5_000, context = "Rejoin") {
async _attemptRejoin(channelId, guildId, maxRetries = 3, baseDelay = 5_000, context = 'Rejoin') {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const player = await this.remix._spawnPlayer(guildId, channelId);
@@ -1206,8 +1067,8 @@ export class GatewayHandler {
} catch (err) {
const errMsg = err?.message ?? String(err);
const isTrackTimeout = errMsg.includes("track publication timed out")
|| errMsg.includes("publishToRoom failed")
|| errMsg.includes("Failed to create MediaPlayer")
|| errMsg.includes("lavalink player create failed")
|| errMsg.includes("Failed to create audio player")
|| errMsg.includes("internal error");
if (isTrackTimeout && attempt < maxRetries) {
@@ -1231,14 +1092,12 @@ export class GatewayHandler {
}
/**
* Rejoin a voice channel after an unexpected disconnect.
* Used by the %247 auto mode to automatically reconnect.
*
* Includes deduplication (prevents concurrent rejoin for the same channel)
* and delegates retry logic to _attemptRejoin.
*
* @param {string} guildId
* @param {string} channelId
* Safely rejoin a 24/7 channel. Guards against duplicate joins,
* intentional leaves, missing channels, and pending joins.
* @param {string} guildId - The guild ID.
* @param {string} channelId - The target channel ID.
* @returns {Promise<Player|null>} The spawned player, or null if skipped.
* @private
*/
async _rejoinChannel(guildId, channelId) {
const { remix } = this;
@@ -1268,12 +1127,6 @@ export class GatewayHandler {
return;
}
if (remix.revoice?._intentionalDisconnects?.has?.(cleanChannelId)) {
logger.voice247(`[Rejoin] Channel ${cleanChannelId} was intentionally left (revoice) — skipping.`);
this._rejoinAttempts.delete(cleanChannelId);
return;
}
const channel = remix.client?.channels?.get?.(cleanChannelId);
if (!channel) {
logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`);
@@ -1301,16 +1154,7 @@ export class GatewayHandler {
}
}
/**
* Check whether a guild-move operation is currently in progress for the
* given guild and old channel. During a move, Fluxer sends two
* VoiceStateUpdate events (leave old + join new) in rapid succession;
* the "leave" should NOT be treated as an unexpected disconnect.
*
* @param {string} guildId The guild ID to check
* @param {string} oldChannelId The channel the bot appears to have left
* @returns {boolean} True if a move is in progress and the disconnect should be ignored
*/
/** @private Check whether a guild currently has a move in progress (recently connected player or pending join). Used to suppress false positive disconnect-rejoin loops. @param {string} guildId - The guild ID. @param {string} oldChannelId - The channel the bot just left. @returns {boolean} True if a move is in progress within the evidence window. */
_isGuildMoveInProgress(guildId, oldChannelId) {
const { remix } = this;
const cleanGuild = cleanId(guildId);
@@ -1346,21 +1190,7 @@ export class GatewayHandler {
return false;
}
/**
* Invoke after the bot has connected and Moonlink has been initialised.
* Seeds voice states, attaches raw WS listener, kicks off presence rotation,
* and rejoins 24/7 channels with staggered delays to avoid overwhelming
* the LiveKit server.
*/
/**
* Paginate /users/@me/guilds via REST and add any guilds that Fluxer
* didn't cache (because their GUILD_CREATE was never received) as
* lightweight stubs into client.guilds. This ensures guild count and
* any guild-map lookups reflect the real server count.
*
* Stubs only carry { id, name } — enough for counting and ID lookups.
* They are skipped if a full guild object is already in the cache.
*/
/** @async @private Fetch all guilds the bot is in via REST and create stub entries in the client cache for any missing guilds. This ensures settings and 24/7 lookups work even for guilds that haven't sent GUILD_CREATE yet. */
async seedGuildsFromRest() {
const { remix } = this;
const client = remix.client;
@@ -1428,11 +1258,7 @@ export class GatewayHandler {
}
}
/**
* Try to get the Guild class from @fluxerjs/core so we can create proper
* Guild instances for stubs instead of plain objects.
* Returns null if the class can't be resolved.
*/
/** @private @returns {Function|null} The Guild constructor class. */
_getGuildClass() {
if (this._GuildClass) return this._GuildClass;
try {
@@ -1448,6 +1274,11 @@ export class GatewayHandler {
return null;
}
/**
* Called when the bot receives the READY event.
* Seeds voice states, starts presence rotation, ends startup grace period,
* and begins 24/7 boot recovery.
*/
onReady() {
this._lastReadyAt = Date.now();
this.seedVoiceStatesFromGuilds();
@@ -1478,14 +1309,10 @@ export class GatewayHandler {
}
/**
* Rejoin all 24/7 channels after boot with staggered delays.
*
* Both %247 auto and %247 on channels are rejoined because:
* %247 auto: always stays in voice (disconnect + reboot)
* %247 on: only on reboot, not on disconnect
*
* Channels are rejoined one at a time with a delay between each to
* avoid overwhelming the LiveKit server with concurrent track publications.
* Boot recovery: sequentially rejoin all saved 24/7 channels.
* Sets _bootRecoveryActive=true to suppress fake move events during the process.
* Cleans up missing channels from settings to prevent repeated failures.
* @returns {Promise<void>}
*/
async rejoin247Channels() {
this._bootRecoveryActive = true;
@@ -1503,7 +1330,7 @@ export class GatewayHandler {
for (const channelId of channels) {
const mode = get247ChannelMode(serverSettings, channelId);
if (mode === "auto" || mode === "on") {
if (mode === "on") {
channelsToRejoin.push({ guildId, channelId, mode });
}
}
@@ -1603,14 +1430,14 @@ export class GatewayHandler {
`[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.`
);
setTimeout(() => { this._bootRecoveryActive = false; }, 15_000);
this._bootRecoveryActive = false;
}
/**
* Perform the actual cleanup for a guild that the bot was removed from.
* Extracted from the GuildDelete handler so it can be called after the
* startup grace period expires.
* @param {string} guildId
* Process a confirmed guild deletion. Cleans up voice cache and previous state.
* Does NOT delete 24/7 settings (preserved for re-invite).
* @param {string} guildId - The deleted guild ID.
* @private
*/
_processGuildDelete(guildId) {
const { remix } = this;
+262 -325
View File
File diff suppressed because it is too large. Load diff
+599
View File
@@ -0,0 +1,599 @@
/** @module src/LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. */
import { LavalinkManager as LavalinkClientManager, NodeType } from "lavalink-client";
import { logger, _wsErrorCooldown } from "./constants/Logger.mjs";
import { EventEmitter } from "node:events";
import { Events } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice";
/** @class LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. Wraps the lavalink-client library and provides node lifecycle management, search, player creation, and WebSocket payload interception. @extends {EventEmitter} */
export class LavalinkManager extends EventEmitter {
/** @type {LavalinkClientManager} @description The underlying lavalink-client manager instance. */
lavalink = null;
/** @type {string|null} @description Current Lavalink session ID. */
_sessionId = null;
/** @type {object} @description Bot client reference. */
_client = null;
/** @type {object} @description Node configuration (id, host, port, password, secure). */
_nodeCfg = null;
/** @type {boolean} @description Whether a node is currently connected. */
_nodeConnected = false;
/** @private @type {Set<string>} @description Guild IDs with pending leave requests. */
_pendingLeaves = new Set();
/** @private @type {Map<string, object>} @description Cached VOICE_SERVER_UPDATE payloads keyed by guild ID. */
_cachedVoiceServerUpdates = new Map();
/** Create a new LavalinkManager and initialize the underlying lavalink-client connection. @param {object} nodeCfg - Node configuration (id, host, port, password, secure). @param {object} client - Discord bot client instance. @param {object} user - Bot user object with id and username. */
constructor(nodeCfg, client, user) {
super();
this.setMaxListeners(50);
this._nodeCfg = nodeCfg;
this._client = client;
const requestSignalTimeoutMS = Number(nodeCfg.requestTimeout ?? 60_000);
this.lavalink = new LavalinkClientManager({
nodes: [
{
id: nodeCfg.id ?? "main",
host: nodeCfg.host ?? "localhost",
port: nodeCfg.port ?? 2333,
authorization:nodeCfg.password ?? "youshallnotpass",
secure: nodeCfg.secure ?? false,
nodeType: NodeType.NodeLink,
requestSignalTimeoutMS: Number.isFinite(requestSignalTimeoutMS) ? requestSignalTimeoutMS : 60_000,
},
],
client: {
id: user?.id ?? "0",
username: user?.username ?? "bot",
},
sendToShard: (guildId, payload) => {
this._sendPayload(guildId, payload);
},
autoSkip: true,
playerOptions: {
volumeDecrementer: 1,
},
});
this._setupVoiceForwarding(client);
this._setupLavalinkEvents();
}
/** @private Set up internal Lavalink event forwarding (node connect/disconnect/error, track events). */
_setupLavalinkEvents() {
const nodeMgr = this.lavalink.nodeManager ?? this.lavalink.nodes;
if (nodeMgr) {
try {
nodeMgr.on("error", (node, err) => {
logger.error("[Lavalink] NodeManager error:", node?.id, err?.message ?? err);
});
nodeMgr.on("connect", (node) => {
this._nodeConnected = true;
logger.lavalink("[Lavalink] Node connected (nodeManager): " + node.id);
});
nodeMgr.on("disconnect", (node, reason) => {
this._nodeConnected = false;
logger.warn("[Lavalink] Node disconnected (nodeManager):", node?.id, reason);
});
nodeMgr.on("reconnect", (node) => {
this._nodeConnected = true;
logger.lavalink("[Lavalink] Node reconnecting (nodeManager): " + node.id);
});
} catch (e) {
logger.warn("[Lavalink] nodeManager event setup error:", e?.message);
}
} else {
logger.warn("[Lavalink] Neither nodeManager nor nodes found on lavalink-client instance");
}
this.lavalink.on("nodeConnect", (node) => {
this._nodeConnected = true;
logger.lavalink("[Lavalink] Node connected (manager): " + node.id);
});
this.lavalink.on("nodeReconnect", (node) => {
this._nodeConnected = true;
logger.lavalink("[Lavalink] Node reconnecting (manager): " + node.id);
});
this.lavalink.on("nodeDisconnect", (node, reason) => {
this._nodeConnected = false;
logger.warn("[Lavalink] Node disconnected (manager):", node.id, reason);
});
this.lavalink.on("nodeError", (node, err) => {
logger.error("[Lavalink] Node error (manager):", node.id, err?.message ?? err);
});
this.lavalink.on("playerCreate", (player) => {
logger.lavalink(`[Lavalink] Player created: ${player.guildId}`);
});
this.lavalink.on("playerDestroy", (player) => {
logger.lavalink(`[Lavalink] Player destroyed: ${player.guildId}`);
});
this.lavalink.on("trackStart", (player, track) => {
this.emit("trackStart", player, track);
});
this.lavalink.on("trackEnd", (player, track, payload) => {
const reason = payload?.reason ?? "FINISHED";
this.emit("trackEnd", player, track, reason);
});
this.lavalink.on("queueEnd", (player) => {
this.emit("queueEnd", player);
});
this.lavalink.on("playerDisconnect", (player) => {
this.emit("playerDisconnected", player);
});
this.lavalink.on("playerMove", (player, oldChannelId, newChannelId) => {
logger.lavalink(
`[Lavalink] Player moved in ${player.guildId}: ${oldChannelId} → ${newChannelId}`
);
});
}
/** @private Intercept and forward gateway payloads to Lavalink. Blocks op4 voice joins (handled by vm.join). */
_sendPayload(guildId, payload) {
try {
if (payload?.op === 4 && payload?.d) {
const d = payload.d;
const channelId = d.channel_id;
if (channelId) {
logger.lavalink(
"[LavalinkManager] sendToShard op4 join BLOCKED — voice joins go through vm.join() in Player.join()"
);
return;
} else {
const guildKey = String(guildId);
if (!this._pendingLeaves.has(guildKey)) {
logger.lavalink("[LavalinkManager] sendToShard op4 leave BLOCKED — no explicit leave request for guild " + guildKey);
return;
}
this._pendingLeaves.delete(guildKey);
const vm = getVoiceManager(this._client);
if (vm) {
logger.lavalink("[LavalinkManager] sendToShard op4: routing voice leave via vm.leaveChannel");
try {
const player = this.lavalink?.players?.get?.(guildKey);
const chId = player?.voiceChannelId;
if (chId) {
vm.leaveChannel(chId);
}
return;
} catch (e) {
logger.warn("[LavalinkManager] vm.leaveChannel failed:", e.message);
}
}
}
}
if (typeof this._client?.ws?.send === "function") {
this._client.ws.send(0, payload);
return;
}
const shard = this._client?.ws?.shards?.get?.(0);
if (!shard) {
logger.warn("[LavalinkManager] No WebSocket shard available");
return;
}
if (typeof shard.send === "function") {
shard.send(payload);
} else if (shard.ws?.send) {
shard.ws.send(JSON.stringify(payload));
} else {
logger.warn("[LavalinkManager] Cannot send - no valid send method found");
}
} catch (e) {
logger.warn("[LavalinkManager] Send error:", e.message);
}
}
/** @private Attach raw WebSocket listeners to cache VOICE_SERVER_UPDATE events and handle errors. */
_setupVoiceForwarding(client) {
const attachRawWs = () => {
try {
const shard0 = client.ws?.shards?.get?.(0);
const wsObj = shard0?.ws ?? null;
if (!wsObj) return;
if (this._rawWsHandler && this._rawWsObj && this._rawWsObj !== wsObj) {
try {
if (typeof this._rawWsObj.removeEventListener === "function") {
this._rawWsObj.removeEventListener(
"message",
this._rawWsMessageListener ?? this._rawWsHandler
);
this._rawWsObj.removeEventListener("error", this._rawWsErrorHandler);
} else if (typeof this._rawWsObj.off === "function") {
this._rawWsObj.off(
"message",
this._rawWsMessageListener ?? this._rawWsHandler
);
this._rawWsObj.off("error", this._rawWsErrorHandler);
}
} catch (e) {
logger.warn(
"[LavalinkManager] Raw WS listener cleanup:",
e?.message
);
}
}
if (wsObj === this._rawWsObj) return;
const botId = this._client?.user?.id;
let _vsuLogCooldown = 0;
let _vsuBotLogCooldown = 0;
this._rawWsHandler = (rawData) => {
try {
const text = typeof rawData === "string" ? rawData : rawData?.data;
const payload = typeof text === "string" ? JSON.parse(text) : rawData;
if (payload?.t === "VOICE_SERVER_UPDATE") {
if (!payload.d?.guild_id) {
logger.warn(
"[LavalinkManager] VOICE_SERVER_UPDATE: Missing guild_id",
payload
);
return;
}
const guildKey = String(payload.d.guild_id);
const now = Date.now();
logger.lavalink("[LavalinkManager] VOICE_SERVER_UPDATE for guild " + guildKey +
" endpoint=" + (payload.d.endpoint || "none") +
" token=" + (typeof payload.d.token === "string" ? payload.d.token.substring(0, 12) + "..." : "none"));
if (now - _vsuLogCooldown > 5_000) {
_vsuLogCooldown = now;
}
this._cachedVoiceServerUpdates.set(guildKey, payload);
if (this._cachedVoiceServerUpdates.size > 500) {
const oldest = this._cachedVoiceServerUpdates.keys().next().value;
if (oldest !== undefined) this._cachedVoiceServerUpdates.delete(oldest);
}
}
} catch (e) {
logger.warn(
"[LavalinkManager] Raw WS message parse error:",
e?.message
);
}
};
this._rawWsErrorHandler = (errOrEvent) => {
if (typeof errOrEvent?.preventDefault === "function")
errOrEvent.preventDefault();
const err = errOrEvent?.error ?? errOrEvent?.message ?? errOrEvent;
const now = Date.now();
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS)
return;
_wsErrorCooldown.lastLogged = now;
logger.warn(
"[LavalinkManager] Raw WS socket error (will reconnect):",
err?.message ?? err
);
};
this._rawWsMessageListener = (event) =>
this._rawWsHandler(event?.data ?? event);
if (typeof wsObj.addEventListener === "function") {
wsObj.addEventListener("message", this._rawWsMessageListener);
wsObj.addEventListener("error", this._rawWsErrorHandler);
} else if (typeof wsObj.on === "function") {
wsObj.on("message", this._rawWsMessageListener);
wsObj.on("error", this._rawWsErrorHandler);
}
this._rawWsObj = wsObj;
} catch (e) {
logger.warn("[LavalinkManager] Raw WS setup error:", e.message);
}
};
if (this.lavalink) {
logger.lavalink("[LavalinkManager] lavalink.sendRawData type: " + typeof this.lavalink.sendRawData);
logger.lavalink("[LavalinkManager] lavalink players type: " + typeof this.lavalink.players);
try {
const pSize = this.lavalink.players?.size ?? this.lavalink.players?.length ?? "unknown";
logger.lavalink("[LavalinkManager] lavalink players size: " + pSize);
} catch(_) {}
}
attachRawWs();
client.on(Events.Ready, attachRawWs);
}
/** @private Forward a raw payload to the Lavalink node via sendRawData. */
_forwardToLavalink(payload, guildKey, label) {
try {
if (typeof this.lavalink.sendRawData !== "function") {
logger.error("[LavalinkManager] sendRawData is NOT a function! type=" + typeof this.lavalink.sendRawData);
return;
}
const player = this.lavalink.players?.get?.(guildKey);
logger.lavalink("[LavalinkManager] _forwardToLavalink " + label +
" guild=" + guildKey +
" playerExists=" + !!player +
" playerConnected=" + (player?.connected ?? "noPlayer"));
this.lavalink.sendRawData(payload);
const playerAfter = this.lavalink.players?.get?.(guildKey);
if (playerAfter) {
const vs = playerAfter.voiceServer;
logger.lavalink("[LavalinkManager] After sendRawData(" + label + "):" +
" voiceServer=" + (vs ? "endpoint=" + (vs.endpoint || "none") : "none") +
" connected=" + (playerAfter.connected ?? "undefined"));
} else {
logger.lavalink("[LavalinkManager] After sendRawData(" + label + "): player not found!");
}
} catch (e) {
logger.error("[LavalinkManager] _forwardToLavalink(" + label + ") error:", e.message, e.stack?.substring(0, 200));
}
}
/**
* Replay a cached VOICE_SERVER_UPDATE payload to the Lavalink node.
* @param {string} guildId - The guild ID.
* @returns {boolean} True if a cached update was found and replayed.
*/
replayVoiceServerUpdate(guildId) {
const guildKey = String(guildId);
const cached = this._cachedVoiceServerUpdates.get(guildKey);
if (!cached) {
logger.lavalink("[LavalinkManager] No cached VOICE_SERVER_UPDATE to replay for guild " + guildKey);
return false;
}
try {
logger.lavalink("[LavalinkManager] Replaying cached VOICE_SERVER_UPDATE for guild " + guildKey);
this.lavalink.sendRawData(cached);
return true;
} catch (e) {
logger.warn("[LavalinkManager] Replay VOICE_SERVER_UPDATE error:", e.message);
return false;
}
}
/** @async Initialize the Lavalink connection. Sets up session handling, registers node connect listeners, and warns if the node is unreachable after 3 seconds. @returns {Promise<void>} */
async init() {
this.setMaxListeners(50);
try {
this.lavalink?.setMaxListeners?.(50);
} catch (e) {
logger.warn("[Lavalink] init setMaxListeners:", e?.message);
}
const cfg = this._nodeCfg;
logger.lavalink(
`[Lavalink] Initializing — node: ${cfg?.id ?? "main"} @ ${cfg?.host ?? "localhost"}:${cfg?.port ?? 2333} (secure: ${cfg?.secure ?? false}, type: NodeLink)`
);
try {
this.lavalink.init({
id: this._client?.user?.id ?? "0",
username: this._client?.user?.username ?? "bot",
});
} catch (e) {
logger.warn("[Lavalink] init error:", e?.message);
}
const onNodeConnect = (node) => {
this._nodeConnected = true;
try {
node.updateSession(true, 300_000);
this._sessionId = node.sessionId ?? this._sessionId;
logger.lavalink(
"[Lavalink] Node ready: " + node.id + " | session: " + this._sessionId
);
this.emit("ready", this._sessionId);
} catch (e) {
logger.warn(
"[Lavalink] nodeConnect handler error:",
e?.message
);
}
};
this.lavalink.on("nodeConnect", onNodeConnect);
setTimeout(() => {
if (!this._nodeConnected) {
const h = cfg?.host || "localhost";
const p = cfg?.port || 2333;
logger.warn(
"[Lavalink] Node at " + h + ":" + p + " is NOT connected yet. " +
"Make sure your NodeLink/Lavalink server is running. " +
"The bot will retry when a voice join is attempted."
);
}
}, 3_000);
}
/** @async Search for tracks on the Lavalink node. Tries player-based search first, then falls back to direct node lookup. @param {string} query - The search query string or URL. @param {object} [options] - Search options. @param {string} [options.source] - Lavalink source identifier (e.g. 'ytmsearch'). @param {string} [options.requester] - Requester identifier. @returns {Promise<object>} Lavalink search result with tracks array. @throws {Error} If no connected node is available. */
async search(query, options = {}) {
try {
const players = this.lavalink?.players;
if (players?.size > 0) {
const firstPlayer = players.values?.().next?.().value;
if (firstPlayer?.node) {
logger.lavalink("[Lavalink] search via player.node for guild " + firstPlayer.guildId);
if (options.source) {
return firstPlayer.node.search({ query, source: options.source });
}
return firstPlayer.node.search(query);
}
}
} catch (_) { /* fall through to node-based search */ }
const node = this._getConnectedNode();
if (node) {
logger.lavalink("[Lavalink] search via _getConnectedNode()");
if (options.source) {
return node.search({ query, source: options.source });
}
return node.search(query);
}
try {
const nodes = this.lavalink?.nodes;
const nodeId = this._nodeCfg?.id ?? "main";
const node = nodes?.get?.(nodeId) ?? nodes?.cache?.get?.(nodeId);
if (node) {
logger.lavalink("[Lavalink] search via fallback node.get()");
if (options.source) {
return node.search({ query, source: options.source });
}
return node.search(query);
}
} catch (_) {}
throw new Error("No connected Lavalink node available for search");
}
/** Get the Lavalink player for a guild. @param {string} guildId - The guild ID. @returns {object|null} The Lavalink player, or null if not found. */
getPlayer(guildId) {
return this.lavalink.players.get(String(guildId));
}
/** Close all node WebSocket connections and clean up. */
destroy() {
try {
for (const [id, node] of this.lavalink?.nodes?.cache?.entries?.() ?? []) {
try {
node.socket?.close?.();
} catch (e) {
logger.warn(`[Lavalink] destroy node ${id}:`, e?.message);
}
}
} catch (e) {
logger.warn("[Lavalink] destroy:", e?.message);
}
}
/** Check whether at least one Lavalink node is currently connected. @returns {boolean} */
hasConnectedNode() {
return this._nodeConnected === true;
}
/** @async Wait for a Lavalink node to become connected. Polls at 1-second intervals until connected or timeout. @param {object} [options] - Wait options. @param {number} [options.timeoutMs=15000] - Maximum time to wait in milliseconds. @param {number} [options.intervalMs=1000] - Polling interval in milliseconds. @returns {Promise<void>} Resolves when a node is connected. @throws {Error} If timeout is reached without a connected node. */
waitForNode(options = {}) {
const timeoutMs = options.timeoutMs ?? 15_000;
const intervalMs = options.intervalMs ?? 1_000;
const host = this._nodeCfg?.host || "???";
const port = this._nodeCfg?.port || 2333;
const errMsg =
"[LavalinkManager] No Lavalink node connected after " +
Math.round(timeoutMs / 1000) + "s. " +
"Is your NodeLink/Lavalink server running at " + host + ":" + port + "? " +
"Check: 1) Server is started, 2) Host/port/password are correct in config.json -> nodelink";
return new Promise((resolve, reject) => {
if (this._nodeConnected) return resolve();
let elapsed = 0;
const timer = setInterval(() => {
elapsed += intervalMs;
if (this._nodeConnected) {
clearInterval(timer);
return resolve();
}
if (elapsed >= timeoutMs) {
clearInterval(timer);
reject(new Error(errMsg));
}
}, intervalMs);
timer.unref?.();
});
}
/** @private Get a connected Lavalink node, trying multiple strategies (cache, get, leastUsedNodes, leastLoadNodes). @returns {object|null} A connected node instance, or null if none available. */
_getConnectedNode() {
try {
const nodes = this.lavalink?.nodeManager ?? this.lavalink?.nodes;
if (!nodes) return null;
let store = nodes.cache ?? null;
if (store && typeof store.get === "function" && this._nodeConnected) {
const nodeId = this._nodeCfg?.id ?? "main";
const node = store.get(nodeId);
if (node) return node;
if (store.size > 0) {
const first = store.values?.().next?.().value;
if (first) return first;
}
}
if (typeof nodes.get === "function" && this._nodeConnected) {
const nodeId = this._nodeCfg?.id ?? "main";
const node = nodes.get(nodeId);
if (node) return node;
if (nodes.size > 0) {
const first = nodes.values?.().next?.().value;
if (first) return first;
}
}
if (this._nodeConnected) {
try {
const arr = nodes.leastUsedNodes?.();
if (arr?.length) return arr[0];
} catch (_) {}
try {
const arr = nodes.leastLoadNodes?.();
if (arr?.length) return arr[0];
} catch (_) {}
}
return null;
} catch (e) {
return null;
}
}
/** Get a connected Lavalink node. Public alias for _getConnectedNode. @returns {object|null} A connected node instance, or null. */
getNode() {
return this._getConnectedNode();
}
/** @type {string|null} @description Current Lavalink session ID. */
get sessionId() {
return this._sessionId;
}
/**
* Mark a guild as having a pending leave request so the intercepted op4 leave is allowed through.
* @param {string} guildId - The guild ID.
*/
requestLeave(guildId) {
if (guildId) this._pendingLeaves.add(String(guildId));
}
/** Get connection info for the configured NodeLink node. Useful for health checks and dashboard display. @returns {{host: string, port: number, sessionId: string|null, secure: boolean, password: string}|null} Connection info object, or null if no config. */
getNodeLinkInfo() {
const cfg = this._nodeCfg;
if (!cfg) return null;
return {
host: cfg.host ?? "localhost",
port: cfg.port ?? 2333,
sessionId: this._sessionId ?? null,
secure: cfg.secure ?? false,
password: cfg.password ?? "youshallnotpass",
};
}
}
+111 -319
View File
@@ -1,19 +1,10 @@
/**
* @file MessageHandler.mjs — MessageHandler — wraps Fluxer messages with reply helpers, embed builders, permission checks, and voice state utilities
* @module src.MessageHandler
*/
/** @module src/MessageHandler @description Message creation, reaction observation, permission checking, pagination, and command help display. */
import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
import { logger } from "./constants/Logger.mjs";
import { Utils } from "./Utils.mjs";
/**
* All permissions the bot needs to function correctly, mapped to
* human-readable names and explanations.
* Ordered by importance — text perms first, then voice perms.
*
* @type {ReadonlyMap<string, { name: string, desc: string }>}
*/
/** @type {Map<string, {name: string, desc: string}>} @description Required bot permissions with human-readable names and descriptions. */
export const REQUIRED_BOT_PERMISSIONS = Object.freeze(new Map([
["ViewChannel", { name: "View Channels", desc: "See channels and read their content" }],
["SendMessages", { name: "Send Messages", desc: "Respond to commands and send messages" }],
@@ -26,13 +17,13 @@ export const REQUIRED_BOT_PERMISSIONS = Object.freeze(new Map([
["Speak", { name: "Speak", desc: "Stream audio in voice channels" }],
]));
/** Permission flag keys that are absolutely critical — bot cannot work without these. */
/** @type {string[]} @description Permission keys that are strictly required for the bot to function. */
export const CRITICAL_PERMISSIONS = ["ViewChannel", "SendMessages", "EmbedLinks", "Connect", "Speak"];
/** Permission flag keys that are nice-to-have but bot can partially work without. */
/** @type {string[]} @description Permission keys that are optional but improve the user experience. */
export const OPTIONAL_PERMISSIONS = ["AddReactions", "ReadMessageHistory", "ManageMessages", "AttachFiles"];
/** Parse a color value from config — accepts hex string "0xe9196c", "#e9196c", or number */
/** Parse a color value (hex string, number) into an integer. @param {string|number} value @param {number} [fallback=0xe9196c] @returns {number} */
export function parseColor(value, fallback = 0xe9196c) {
if (!value) return fallback;
if (typeof value === "number") return value;
@@ -41,31 +32,17 @@ export function parseColor(value, fallback = 0xe9196c) {
return isNaN(n) ? fallback : n;
}
/** Global embed color — set once at startup from config */
/** @private */
let _globalColor = 0xe9196c;
/**
* setGlobalColor function.
* @param {{*}} value
* @returns {*}
*/
/** Set the global embed color. @param {string|number} value */
export function setGlobalColor(value) { _globalColor = parseColor(value); }
/**
* getGlobalColor function.
* @returns {*}
*/
/** @returns {number} The current global embed color. */
export function getGlobalColor() { return _globalColor; }
/**
* Strip non-digit characters from a value, returning a clean ID string.
* Re-exported from Utils.mjs for backward compatibility.
*/
/** Re-export of {@link cleanId} from Utils for convenience. @type {function} */
export { cleanId } from "./Utils.mjs";
/**
* Resolve a guild ID from various message-like shapes.
* @param {object} message
* @returns {string|null}
*/
/** Extract the guild ID from various message wrapper shapes. @param {object} message @returns {string|null} */
export function getMessageGuildId(message) {
return message?.channel?.guildId ??
message?.channel?.guild?.id ??
@@ -78,25 +55,18 @@ export function getMessageGuildId(message) {
null;
}
/**
* MessageHandler class.
*/
/** @class MessageHandler @description Handles message creation, reaction observation, permission checking, and pagination. */
export class MessageHandler {
/**
* Fluxer.js client instance
* @type {Client}
* @public
*/
/** @type {Client} */
client;
/** @type {Map<string, object>} Message ID → reaction observer data. */
observedReactions;
/** @type {Map<string, string[]>} */
/** @type {Map<string, Array>} Channel ID → user message observer callbacks. */
observedChannels;
/** @type {import('./constants/Locale.mjs').Locale} */
/** @type {object|null} Locale manager instance. */
locale;
/**
* @param {Client} client
*/
/** @param {Client} client - The Discord client. */
constructor(client) {
this.client = client;
@@ -114,21 +84,16 @@ export class MessageHandler {
});
}
/** @param {import('./constants/Locale.mjs').Locale} locale */
/** Set the locale manager. @param {object} locale */
setLocale(locale) { this.locale = locale; }
/**
* Translate a locale key for a given guild.
* @param {string} guildId
* @param {string} key
* @param {Object} [replacements={}]
* @returns {string}
*/
/** Translate a locale key. @param {string} guildId @param {string} key @param {object} [replacements={}] @returns {string} */
t(guildId, key, replacements = {}) {
if (!this.locale) return key;
return this.locale.translate(guildId, key, replacements);
}
/** @private Register reaction add/remove event listeners. */
setupEvents() {
const reactionUpdate = (payload) => {
const { userId, messageId, emoji } = payload;
@@ -148,13 +113,7 @@ export class MessageHandler {
this.client.on(Events.MessageReactionRemove, (payload) => reactionUpdate(payload));
}
/**
* Checks if the bot has the specified permissions in a specific channel.
*
* @param {string[]} permissions An array of permission flag keys to check for.
* @param {BaseChannel} channel The channel to check the permissions in.
* @returns {string[]} Missing permission flag keys.
*/
/** Return the permission keys the bot is missing in a channel. @param {string[]} permissions @param {object} channel @returns {string[]} Missing permission keys. */
checkPermissions(permissions, channel) {
if (!channel?.guild) return [];
const me = channel.guild.members?.me ?? null;
@@ -170,14 +129,7 @@ export class MessageHandler {
return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p));
}
/**
* Check ALL required bot permissions in a channel.
* Returns an object with critical vs optional missing permissions
* so the caller can decide how severe the problem is.
*
* @param {BaseChannel} channel The channel to check.
* @returns {{ missing: string[], criticalMissing: string[], optionalMissing: string[] }}
*/
/** Check all REQUIRED_BOT_PERMISSIONS and split into critical vs optional. @param {object} channel @returns {{missing: string[], criticalMissing: string[], optionalMissing: string[]}} */
checkAllBotPermissions(channel) {
const allKeys = [...REQUIRED_BOT_PERMISSIONS.keys()];
const missing = this.checkPermissions(allKeys, channel);
@@ -188,14 +140,7 @@ export class MessageHandler {
};
}
/**
* Build a rich permission-error embed listing all missing permissions
* with human-readable names and explanations.
*
* @param {string[]} missingKeys Permission flag keys that are missing.
* @param {string} [guildId] Guild ID for locale translation.
* @returns {EmbedBuilder}
*/
/** Build an EmbedBuilder showing missing permissions. @param {string[]} missingKeys @param {string} guildId @returns {EmbedBuilder} */
buildPermissionEmbed(missingKeys, guildId) {
const criticalItems = [];
const optionalItems = [];
@@ -237,11 +182,7 @@ export class MessageHandler {
return embed;
}
/**
* @param {string[]} permissions Permissions to check for.
* @param {FluxerMessage} message The message to reply to in case of missing permissions.
* @returns {Promise<boolean>} If all permissions are given.
*/
/** Check permissions; send a DM or embed if missing. @async @param {string[]} permissions @param {object} message @returns {Promise<boolean>} */
async assertPermissions(permissions, message) {
const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId);
if (guild && !guild.members?.me) {
@@ -275,25 +216,14 @@ export class MessageHandler {
return false;
}
/**
* @callback MessageListener
* @param {Message} message
*/
/**
* Listen for new messages
* @param {MessageListener} listener
*/
/** Register a listener for all incoming messages. @param {Function} listener */
onMessage(listener) {
this.client.on(Events.MessageCreate, (msg) => {
listener(new Message(msg, this));
});
}
/**
* Get a cached message by id.
* @param {string} id
* @returns {Message|null}
*/
/** Get a wrapped Message from cache by ID. @param {string} id @returns {Message|null} */
get(id) {
for (const channel of this.client.channels.values()) {
const msg = channel.messages?.get?.(id) ?? null;
@@ -302,12 +232,7 @@ export class MessageHandler {
return null;
}
/**
* Either gets a message from cache or fetches it.
* @param {string} id message id
* @param {string} channelId channel id
* @returns {Promise<Message>}
*/
/** @async Get a message from cache or fetch it from the API. @param {string} id @param {string} channelId @returns {Promise<Message|null>} */
async getOrFetch(id, channelId) {
const cached = this.get(id);
if (cached) return cached;
@@ -317,20 +242,13 @@ export class MessageHandler {
return raw ? new Message(raw, this) : null;
}
/**
* Get a cached channel by id.
* @param {string} id channel id
* @returns {Channel}
*/
/** Get a wrapped Channel by ID. @param {string} id @returns {Channel} */
getChannel(id) {
const c = this.client.channels.get(id);
return new Channel(c, this);
}
/**
* @param {string} id
* @returns {Promise<Channel>}
*/
/** @async Get a channel from cache or fetch from the API. @param {string} id @returns {Promise<Channel>} */
async getOrFetchChannel(id) {
const c = this.getChannel(id);
if (c?.channel) return c;
@@ -338,6 +256,7 @@ export class MessageHandler {
return new Channel(raw, this);
}
/** Start observing reactions on a message. @param {object} msg @param {string[]} reactions @param {Function} cb @param {object} [user] @returns {string} Observation ID. */
observeReactions(msg, reactions, cb, user) {
this.observedReactions.set(msg.id, {
reactions: reactions,
@@ -347,16 +266,12 @@ export class MessageHandler {
});
return msg.id;
}
/** Stop observing reactions. @param {string} i - Observation ID. @returns {boolean} */
unobserveReactions(i) {
return this.observedReactions.delete(i);
}
/**
* @param {string} userId
* @param {BaseChannel} channel
* @param {MessageListener} callback
* @returns {string}
*/
/** Observe messages from a specific user in a channel. @param {string} userId @param {object} channel @param {Function} callback @returns {string} Observation ID. */
observeUserMessagesChannel(userId, channel, callback) {
const current = (this.observedChannels.get(channel.id) || []);
const nonce = Utils.uid();
@@ -368,6 +283,7 @@ export class MessageHandler {
this.observedChannels.set(channel.id, current);
return userId + ";" + channel.id + ";" + nonce;
}
/** @private Stop observing a user's messages in a channel. @param {string} oid */
unobserveUserMessagesChannel(oid) {
const [userId, channelId, nonce] = oid.split(";");
const current = (this.observedChannels.get(channelId) || []);
@@ -378,6 +294,7 @@ export class MessageHandler {
this.observedChannels.set(channelId, current);
}
/** @private Build an EmbedBuilder from text with optional title, thumbnail, and icon. @param {string} [text=""] @param {object} [options={}] @param {string} [options.color] @param {string} [options.title] @param {string} [options.thumbnail] @param {string} [options.icon_url] @returns {EmbedBuilder} */
#embedify(text = "", options = {}) {
const color = options.color ?? getGlobalColor();
const builder = new EmbedBuilder()
@@ -401,6 +318,7 @@ export class MessageHandler {
return builder;
}
/** @private Create a message payload object with an embed. @param {string} text @param {object} [options={}] @returns {{content: *, embeds: EmbedBuilder[]}} */
#createEmbed(text, options = {}) {
return {
content: options.content ?? undefined,
@@ -408,12 +326,7 @@ export class MessageHandler {
};
}
/**
* @param {FluxerMessage} replyingTo
* @param {string|Object} message
* @param {boolean} mention
* @returns {Promise<Message>}
*/
/** @async Reply to a message with permission checks. @param {object} replyingTo @param {string|object} message @param {boolean} [mention=false] @returns {Promise<Message|null>} */
async reply(replyingTo, message, mention = false) {
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
let opts;
@@ -425,12 +338,7 @@ export class MessageHandler {
return new Message(await replyingTo.reply(opts, { ping: false }), this);
}
/**
* @param {FluxerMessage} replyingTo
* @param {string|Object} message
* @param {Object} options
* @returns {Promise<Message>}
*/
/** @async Reply with an embed. @param {object} replyingTo @param {string|object} message @param {object} [options={}] @returns {Promise<Message|null>} */
async replyEmbed(replyingTo, message, options = {}) {
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
@@ -452,11 +360,7 @@ export class MessageHandler {
return new Message(await replyingTo.reply(payload, { ping: false }), this);
}
/**
* @param {BaseChannel} channel
* @param {string|Object} message
* @returns {Promise<Message>}
*/
/** @async Send a message to a channel. @param {object} channel @param {string|object} message @returns {Promise<Message|null>} */
async sendMessage(channel, message) {
if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) {
logger.warn("[MessageHandler] Missing SendMessages/EmbedLinks permission in channel", channel.id);
@@ -471,12 +375,7 @@ export class MessageHandler {
return new Message(await channel.send(opts), this);
}
/**
* @param {BaseChannel} channel
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
/** @async Send an embed to a channel. @param {object} channel @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
async sendEmbed(channel, content, embedOptions = {}) {
if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) {
return this.sendMessage(channel, typeof content === "string" ? content : content?.embedText ?? "");
@@ -493,12 +392,7 @@ export class MessageHandler {
return new Message(await channel.send(payload), this);
}
/**
* @param {FluxerMessage} message
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
/** @async Edit an existing message embed with retry on 502/503/504. @param {object} message @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
async editEmbed(message, content, embedOptions = {}) {
const RETRYABLE = new Set([502, 503, 504]);
const MAX_ATTEMPTS = 3;
@@ -537,11 +431,7 @@ export class MessageHandler {
}
}
/**
* Initialize paginated messages.
* @param {PageBuilder} builder
* @param {Message} msg
*/
/** @async Create a paginated message with arrow reactions. @param {PageBuilder} builder @param {Message} msg @returns {Promise<void>} */
async initPagination(builder, msg) {
const pages = builder.createPages();
if (pages.length === 0) return;
@@ -572,13 +462,7 @@ export class MessageHandler {
}, 5 * 60 * 1000);
}
/**
* Join a voice channel using the documented VoiceManager.join() API.
* Reference: https://fluxer.js.org/v/latest/guides/voice
*
* @param {string} channelId
* @returns {Promise<import("@fluxerjs/voice").VoiceConnectionLike>}
*/
/** @async Join a voice channel using VoiceManager. @param {string} channelId @returns {Promise<object>} @throws {Error} If channel not found or not a guild channel. */
async joinChannel(channelId) {
const { getVoiceManager } = await import("@fluxerjs/voice");
const channel = await this.client.channels.fetch(channelId).catch(() => null);
@@ -590,57 +474,45 @@ export class MessageHandler {
}
}
/**
* Channel class.
*/
/** @class Channel @description Wrapper around a Discord channel object providing helpers for sending messages and observing users. */
export class Channel {
/**
* The actual underlying fluxer.js channel instance
* @type {import("@fluxerjs/core").BaseChannel}
*/
/** @type {object} The raw channel object. */
channel;
/** @type {MessageHandler} */
handler;
/**
* @param {import("@fluxerjs/core").BaseChannel} channel
* @param {MessageHandler} handler
*/
/** @param {object} channel @param {MessageHandler} handler */
constructor(channel, handler) {
this.channel = channel;
this.handler = handler;
}
/** @type {Guild} */
/** @returns {object|null} The guild this channel belongs to. */
get server() {
return this.channel?.guild ?? null;
}
/** @type {Guild} */
/** @returns {object|null} Alias for server (guild). */
get guild() {
return this.channel?.guild ?? null;
}
/** @type {boolean} */
/** @returns {boolean} Whether this channel is a voice channel. */
get isVoice() {
return this.channel?.isVoiceBased?.() ?? false;
}
/** @type {string} */
/** @returns {string} The channel ID. */
get id() {
return this.channel?.id;
}
/** @type {string} */
/** @returns {string|null} The guild ID. */
get guildId() {
return this.channel?.guildId ?? null;
}
/** @type {string} */
/** @returns {string|null} Alias for guildId. */
get serverId() {
return this.guildId;
}
/**
* @param {MessageListener} callback
* @param {User} user
* @returns {Function}
*/
/** Observe messages from a specific user in this channel. @param {Function} callback @param {object} user @returns {Function} Unobserve function. */
onMessageUser(callback, user) {
const resolvedUserId = user?.id
?? user?._id
@@ -656,92 +528,67 @@ export class Channel {
};
}
/**
* @param {string|Object} content
* @returns {Promise<Message>}
*/
/** Send a message to this channel. @param {string|object} content @returns {Promise<Message|null>} */
sendMessage(content) {
return this.handler.sendMessage(this.channel, content);
}
/**
* @param {string|Object} content
* @returns {Promise<Message>}
*/
/** Alias for sendMessage. @param {string|object} content @returns {Promise<Message|null>} */
send(content) {
return this.handler.sendMessage(this.channel, content);
}
/**
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
/** Send an embed to this channel. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
sendEmbed(content, embedOptions = {}) {
return this.handler.sendEmbed(this.channel, content, embedOptions);
}
/**
* @returns {Promise<import("@fluxerjs/voice").VoiceConnection>}
*/
/** Join this voice channel. @async @returns {Promise<object>} @throws {Error} If not a voice channel. */
join() {
if (!this.isVoice) throw new Error("Cannot join a text channel. Attempting to 'join' into channel `" + this.channel?.id + "`");
return this.handler.joinChannel(this.channel.id);
}
}
/**
* Message class.
*/
/** @class Message @description Wrapper around a Discord message providing helpers for replying, editing, and reaction observation. */
export class Message {
/**
* The actual underlying message instance
* @type {import("@fluxerjs/core").Message}
*/
/** @type {object} */
message;
/** @type {MessageHandler} */
handler;
/**
* @param {import("@fluxerjs/core").Message} message Underlying raw Fluxer.js message instance
* @param {MessageHandler} handler Owning MessageHandler, used for replies, pagination, and reaction observers
*/
/** @param {object} message @param {MessageHandler} handler */
constructor(message, handler) {
this.message = message;
this.handler = handler;
}
/** @type {string} */
/** @returns {string} The raw message content. */
get content() {
return this.message.content;
}
/** @type {string} */
/** @returns {string} The message ID. */
get id() {
return this.message.id;
}
/** @type {User} */
/** @returns {object} The author object. */
get author() {
return this.message.author;
}
/** @type {string} */
/** @returns {string} The author's user ID. */
get authorId() {
return this.message.author?.id;
}
/** @type {GuildMember|null} */
/** @returns {object|null} The guild member, if available. */
get member() {
return this.message.member ?? null;
}
/** @type {Channel} */
/** @returns {Channel} The wrapped channel this message was sent in. */
get channel() {
return this.handler.getChannel(this.message.channelId);
}
/**
* @param {string[]} reactions
* @param {function} callback
* @param {User} [user]
* @returns {function} unobserve
*/
/** Observe reactions on this message. @param {string[]} reactions @param {Function} callback @param {object} [user=null] @returns {Function} Unobserve function. */
onReaction(reactions, callback, user = null) {
const oid = this.handler.observeReactions(this.message, reactions, callback, user);
return () => {
@@ -749,21 +596,12 @@ export class Message {
};
}
/**
* @param {string|Object} content
* @param {boolean} mention
* @returns {Promise<Message>}
*/
/** Reply to this message. @param {string|object} content @param {boolean} [mention=false] @returns {Promise<Message|null>} */
reply(content, mention = false) {
return this.handler.reply(this.message, content, mention);
}
/**
* @param {string|Object} content
* @param {boolean} mention
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
/** Reply to this message with an embed. @param {string|object} content @param {boolean} [mention=false] @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
replyEmbed(content, mention = false, embedOptions = {}) {
return this.handler.replyEmbed(this.message, content, {
mention,
@@ -771,39 +609,31 @@ export class Message {
});
}
/**
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
/** Edit this message's embed. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
editEmbed(content, embedOptions = {}) {
return this.handler.editEmbed(this.message, content, embedOptions);
}
/**
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
/** Alias for editEmbed. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
edit(content, embedOptions = {}) {
return this.handler.editEmbed(this.message, content, embedOptions);
}
}
/**
* PageBuilder class.
*/
/** @class PageBuilder @description Splits content into pages with template-based formatting. */
export class PageBuilder {
/** @type {string} Template form string with $maxPage, $currentPage, $content placeholders. */
form = "";
/** @type {number} Maximum lines per page. */
maxLinesPerPage = 2;
/** @type {string[]} */
/** @type {Array|string[]} Content lines or array items. */
content = [];
/** @type {boolean} Whether pages have been created. */
initiated = false;
/** @type {Array<Array>} Created page arrays. */
pages = [];
/**
* @param {string|string[]} content
*/
/** @param {string|Array} content - String to split by newlines or an array of items. */
constructor(content) {
if (!Array.isArray(content)) {
this.content = content.split("\n");
@@ -812,18 +642,21 @@ export class PageBuilder {
this.content = content;
}
/** Set the template form string with $maxPage, $currentPage, $content placeholders. @param {string} form @returns {PageBuilder} */
setForm(form) {
this.form = form;
this.initiated = false;
return this;
}
/** Set the maximum lines per page. @param {number} [maxLinesPerPage=2] @returns {PageBuilder} */
setMaxLines(maxLinesPerPage = 2) {
this.maxLinesPerPage = maxLinesPerPage;
this.initiated = false;
return this;
}
/** Create page arrays from content. Lazily initialized; returns cached pages if already created. @returns {Array<Array>} */
createPages() {
if (this.initiated) return this.pages;
@@ -840,10 +673,7 @@ export class PageBuilder {
return pages;
}
/**
* @param {number} n
* @returns {string|null}
*/
/** Get a formatted page string by index (0-based). @param {number} n @returns {string|null} */
getPage(n) {
const pages = this.createPages();
if (!pages[n]) return null;
@@ -854,38 +684,22 @@ export class PageBuilder {
.replace(/\$content/gi, pages[n].join("\n"));
}
/**
* @param {number} n
* @returns {string|null}
*/
/** Get raw page content by index (0-based) without template formatting. @param {number} n @returns {string|null} */
getContent(n) {
const pages = this.createPages();
if (!pages[n]) return null;
return pages[n].join("\n");
}
/** @returns {number} */
/** Get the total number of pages. @returns {number} */
size() {
return this.pages.length;
}
}
/**
* RichPaginator — tabbed embed pagination with reaction controls.
*
* Usage:
* new RichPaginator(msg, handler)
* .setTimeout(5 * 60 * 1000)
* .addTab({ emoji: "🏠", title: "Home", header: "Home Page", content: "..." })
* .addTab({ emoji: "🎵", title: "Music", header: "Music Commands", pages: ["page1", "page2"] })
* .setPrevNext("⬅️", "➡️")
* .send();
*/
/** @class RichPaginator @description Multi-tab paginated embed with tab and arrow navigation via reactions. */
export class RichPaginator {
/**
* @param {Message} msg
* @param {MessageHandler} handler
*/
/** @param {Message} msg @param {MessageHandler} handler */
constructor(msg, handler) {
this._msg = msg;
this._handler = handler;
@@ -897,24 +711,19 @@ export class RichPaginator {
this._state = { tab: 0, page: 0 };
}
/** @param {number} ms */
/** Set the session timeout duration. @param {number} ms @returns {RichPaginator} */
setTimeout(ms) { this._timeout = ms; return this; }
/** @param {number} color */
/** Set the embed color. @param {number} color @returns {RichPaginator} */
setColor(color) { this._color = color; return this; }
/** @param {string} startTab index (0-based) */
/** Set the initially selected tab index. @param {number} idx @returns {RichPaginator} */
setStartTab(idx) { this._state.tab = idx; return this; }
/** @param {string} prev @param {string} next */
/** Set the previous/next arrow emoji strings. @param {string} prev @param {string} next @returns {RichPaginator} */
setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; }
/**
* Add a tab.
* @param {{ emoji: string, title: string, header: string, content?: string, pages?: string[] }} tab
* content — single static string (no pagination)
* pages — array of strings, one per page (enables prev/next)
*/
/** Add a tab to the paginator. @param {object} tab @param {string} tab.emoji @param {string} tab.title @param {string} tab.header @param {string} [tab.content] @param {string[]} [tab.pages] @returns {RichPaginator} */
addTab(tab) {
this._tabs.push({
emoji: tab.emoji,
@@ -925,6 +734,7 @@ export class RichPaginator {
return this;
}
/** @private Build an embed for a given tab and sub-page. @param {number} tabIdx @param {number} pageIdx @returns {EmbedBuilder} */
_buildEmbed(tabIdx, pageIdx) {
const tab = this._tabs[tabIdx];
const totalTabs = this._tabs.length;
@@ -943,6 +753,7 @@ export class RichPaginator {
.setFooter({ text: footerParts.join(" ") });
}
/** @async Send the paginated embed and start observing reactions. @returns {Promise<object|null>} The raw sent message. */
async send() {
if (this._tabs.length === 0) return null;
@@ -992,6 +803,7 @@ export class RichPaginator {
rawMsg.edit({ embeds: [buildEmbed(state.tab, state.page)] }).catch(() => {});
});
/** @private Clear all reactions on the paginator message. */
const clearReactions = async () => {
try {
await rawMsg.removeAllReactions();
@@ -1006,6 +818,7 @@ export class RichPaginator {
}
};
/** @private Close the pagination session, update footer, and clear reactions. */
const closeSession = async () => {
unobserve();
const currentEmbed = buildEmbed(state.tab, state.page);
@@ -1017,6 +830,7 @@ export class RichPaginator {
let timer = setTimeout(closeSession, this._timeout);
/** @private Reset the inactivity timer. */
const resetTimer = () => {
clearTimeout(timer);
timer = setTimeout(closeSession, this._timeout);
@@ -1032,23 +846,9 @@ export class RichPaginator {
}
}
/**
* QueuePaginator — rich embed pagination for the queue/list command.
*
* Usage:
* new QueuePaginator(msg, handler, client)
* .setTimeout(30_000)
* .setColor(0xe9196c)
* .send(buildEmbedFn, totalPages, startPage);
*
* buildEmbedFn(page) must return a raw embed object { color, author, title, description, footer }
*/
/** @class QueuePaginator @description Simple two-arrow paginator for queue embeds with page count. */
export class QueuePaginator {
/**
* @param {Message} msg
* @param {MessageHandler} handler
* @param {Client} client
*/
/** @param {Message} msg @param {MessageHandler} handler @param {Client} client */
constructor(msg, handler, client) {
this._msg = msg;
this._handler = handler;
@@ -1058,17 +858,13 @@ export class QueuePaginator {
this._next = "➡️";
}
/** @param {number} ms */
/** Set the session timeout duration. @param {number} ms @returns {QueuePaginator} */
setTimeout(ms) { this._timeout = ms; return this; }
/** @param {string} prev @param {string} next */
/** Set the previous/next arrow emoji strings. @param {string} prev @param {string} next @returns {QueuePaginator} */
setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; }
/**
* @param {function(page: number): object} buildEmbed - returns a raw embed object
* @param {number} totalPages
* @param {number} [startPage=1]
*/
/** @async Send the paginated embed and observe arrow reactions. @param {Function} buildEmbed - Function that takes a page number and returns an EmbedBuilder. @param {number} totalPages @param {number} [startPage=1] @returns {Promise<object|null>} The raw sent message. */
async send(buildEmbed, totalPages, startPage = 1) {
const state = { page: Math.max(1, Math.min(startPage, totalPages)) };
const nativeMsg = this._msg.message ?? this._msg;
@@ -1094,6 +890,7 @@ export class QueuePaginator {
const channelId = rawMsg.channelId ?? rawMsg.channel_id ?? rawMsg.channel?.id;
const msgId = rawMsg.id;
/** @private Clear all reactions on the paginator message. */
const clearReactions = async () => {
try {
await rawMsg.removeAllReactions();
@@ -1106,6 +903,7 @@ export class QueuePaginator {
}
};
/** @private Close the pagination session, update footer, and clear reactions. */
const closeSession = async () => {
unobserve();
const embed = buildEmbed(state.page);
@@ -1120,6 +918,7 @@ export class QueuePaginator {
};
let timer = setTimeout(closeSession, this._timeout);
/** @private Reset the inactivity timer. */
const resetTimer = () => {
clearTimeout(timer);
timer = setTimeout(closeSession, this._timeout);
@@ -1138,7 +937,9 @@ export class QueuePaginator {
}
}
/** @type {number} Maximum commands listed per page in the help paginator. */
const HELP_CMDS_PER_PAGE = 10;
/** @type {number} Help paginator session timeout in milliseconds. */
const HELP_SESSION_MS = 30 * 1000;
const HELP_TABS = [
@@ -1168,6 +969,7 @@ const HELP_TABS = [
},
];
/** @private @param {string} prefix @returns {string} */
function _helpHomeContent(prefix) {
return (
"**Welcome to the Remix help page.**\n\n" +
@@ -1182,6 +984,7 @@ function _helpHomeContent(prefix) {
);
}
/** @private @returns {string} */
function _helpSupportContent() {
return (
"If you need help with anything or encounter any issues, hop over to " +
@@ -1193,6 +996,7 @@ function _helpSupportContent() {
);
}
/** @private Build paginated content for a help category tab. @param {object} tab @param {Array} allCmds @param {string} prefix @returns {string[]} */
function _helpBuildCategoryPages(tab, allCmds, prefix) {
const cmds = allCmds
.filter(cmd => {
@@ -1219,29 +1023,16 @@ function _helpBuildCategoryPages(tab, allCmds, prefix) {
return pages;
}
/**
* HelpCommand class.
*/
/** @class HelpCommand @description Rich paginated help command with tabbed navigation (Home, Music, Utilities, Support). */
export class HelpCommand {
/**
* @param {import("./CommandHandler.mjs").CommandHandler} commandHandler
* @param {MessageHandler} messageHandler
* @param {function(msg: Message): import("./Settings.mjs").SettingsManager} getSettingsFn
* Called with a Message to retrieve that guild's settings.
* In index.mjs this is: (msg) => this.getSettings(msg)
*/
/** @param {CommandHandler} commandHandler @param {MessageHandler} messageHandler @param {Function} getSettingsFn */
constructor(commandHandler, messageHandler, getSettingsFn) {
this._commands = commandHandler;
this._messages = messageHandler;
this._getSettings = getSettingsFn;
}
/**
* Registers the help command with the CommandHandler and intercepts
* incoming messages whose first word is "help", "h", or "commands".
*
* Call once during bot startup, after commands have been loaded.
*/
/** Register the help command, intercept invalid command replies, and intercept help aliases. */
register() {
if (this._registered) return;
this._registered = true;
@@ -1314,6 +1105,7 @@ export class HelpCommand {
});
}
/** @private Handle a help invocation: show command detail or paginated overview. @param {Message} msg @param {string[]} args @param {string} prefix */
_handle(msg, args, prefix) {
const allCmds = this._commands.commands;
const query = (args[0] ?? "").trim();
-301
View File
@@ -1,301 +0,0 @@
/**
* @file MoonlinkManager.mjs — MoonlinkManager — wraps moonlink.js for track search, session management, and voice packet forwarding to NodeLink
* @module src.MoonlinkManager
*/
/**
* MoonlinkManager.mjs
*
* Wraps moonlink.js Manager with a custom connector for Fluxer.
*/
import { Manager } from "moonlink.js";
import { logger, _wsErrorCooldown } from "./constants/Logger.mjs";
import { EventEmitter } from "node:events";
import { Events } from "@fluxerjs/core";
/**
* MoonlinkManager class.
*/
export class MoonlinkManager extends EventEmitter {
/** @type {Manager} */
manager = null;
/** @type {string|null} */
sessionId = null;
/** @type {import("@fluxerjs/core").Client} */
_client = null;
/**
* @param {{ host: string, port: number, password: string, secure?: boolean }} nodeCfg
* @param {import("@fluxerjs/core").Client} client
*/
constructor(nodeCfg, client) {
super();
this.setMaxListeners(50);
this._nodeCfg = nodeCfg;
this._client = client;
this.manager = new Manager({
nodes: [
{
host: nodeCfg.host ?? "localhost",
port: nodeCfg.port ?? 3000,
password: nodeCfg.password ?? "youshallnotpass",
secure: nodeCfg.secure ?? false,
identifier: "main",
}
],
options: {
resume: true,
resumeTimeout: 60_000,
defaultPlayer: {
volume: 100,
selfDeaf: true,
selfMute: false,
autoPlay: false,
autoLeave: false,
},
search: {
defaultPlatform: "ytmsearch",
},
send: (guildId, payload) => this._sendPayload(guildId, payload),
},
});
this._setupVoiceForwarding(client);
this.manager.on("nodeReady", (node) => {
this.sessionId = node.sessionId ?? null;
logger.moonlink(`[Moonlink] Node ready: ${node.identifier} | session: ${this.sessionId}`);
this.emit("ready", this.sessionId);
});
this.manager.on("nodeConnected", (node) => {
logger.moonlink(`[Moonlink] Node connected: ${node.identifier}`);
});
this.manager.on("nodeDisconnect", (node, reason) => {
logger.warn("[Moonlink] Node disconnected:", node.identifier, reason);
});
this.manager.on("nodeError", (node, err) => {
logger.error("[Moonlink] Node error:", node.identifier, err?.message ?? err);
});
this.manager.on("trackStart", (player, track) => {
this.emit("trackStart", player, track);
});
this.manager.on("trackEnd", (player, track, reason) => {
this.emit("trackEnd", player, track, reason);
});
this.manager.on("queueEnd", (player) => {
this.emit("queueEnd", player);
});
this.manager.on("playerDisconnected", (player) => {
this.emit("playerDisconnected", player);
});
}
/**
* Get the current live session ID from the connected node.
* Walks active nodes to find a valid session, fallback to cached.
* @returns {string|null}
*/
getLiveSessionId() {
try {
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
if (node.sessionId) return node.sessionId;
if (node.ws?.sessionId) return node.ws.sessionId;
}
} catch(e) { logger.warn("[Moonlink] getLiveSessionId:", e?.message); }
return this.sessionId;
}
/**
* Send voice payload to Fluxer's WebSocket.
*
* moonlink.js v5 passes the full gateway payload object (with `op` and `d` keys).
* Fluxer's client-level `ws.send()` handles serialization internally, so we
* pass the raw object. The native-WebSocket fallback path (line with
* `JSON.stringify`) is kept for edge cases where only the raw ws is available.
*
* @param {string} guildId
* @param {{ op: number, d: object }} payload
* @private
*/
_sendPayload(guildId, payload) {
try {
if (typeof this._client?.ws?.send === "function") {
this._client.ws.send(0, payload);
return;
}
const shard = this._client?.ws?.shards?.get?.(0);
if (!shard) {
logger.warn("[MoonlinkManager] No WebSocket shard available");
return;
}
if (typeof shard.send === "function") {
shard.send(payload);
} else if (shard.ws?.send) {
shard.ws.send(JSON.stringify(payload));
} else {
logger.warn("[MoonlinkManager] Cannot send - no valid send method found");
}
} catch (e) {
logger.warn("[MoonlinkManager] Send error:", e.message);
}
}
/**
* Forward voice state updates from Fluxer to moonlink.
*
* moonlink.js v5 expects raw gateway payloads via `packetUpdate()`:
* - VOICE_STATE_UPDATE → { op: 0, t: "VOICE_STATE_UPDATE", d: {...} }
* - VOICE_SERVER_UPDATE → { op: 0, t: "VOICE_SERVER_UPDATE", d: {...} }
*
* VOICE_STATE_UPDATE comes from the Fluxer `VoiceStateUpdate` event.
* VOICE_SERVER_UPDATE must be intercepted from the raw WebSocket stream because
* Fluxer does not emit a dedicated event for it.
*
* @param {import("@fluxerjs/core").Client} client
* @private
*/
_setupVoiceForwarding(client) {
client.on(Events.VoiceStateUpdate, (data) => {
try {
const guildId = data.guild_id;
if (!guildId) {
logger.warn("[MoonlinkManager] voiceStateUpdate: No guild_id found in data", data);
return;
}
const payload = {
op: 0,
t: "VOICE_STATE_UPDATE",
d: {
guild_id: guildId,
channel_id: data.channel_id ?? null,
user_id: data.user_id,
session_id: data.session_id ?? "",
deaf: data.deaf ?? false,
mute: data.mute ?? false,
self_deaf: data.self_deaf ?? false,
self_mute: data.self_mute ?? false,
self_stream: data.self_stream ?? false,
self_video: data.self_video ?? false,
suppress: data.suppress ?? false,
member: data.member ?? null,
}
};
this.manager.packetUpdate(payload);
} catch (e) {
logger.warn("[MoonlinkManager] voiceStateUpdate forward error:", e.message);
}
});
const attachRawWs = () => {
try {
const shard0 = client.ws?.shards?.get?.(0);
const wsObj = shard0?.ws ?? null;
if (!wsObj) return;
if (this._rawWsHandler && this._rawWsObj && this._rawWsObj !== wsObj) {
try {
if (typeof this._rawWsObj.removeEventListener === "function") {
this._rawWsObj.removeEventListener("message", this._rawWsMessageListener ?? this._rawWsHandler);
this._rawWsObj.removeEventListener("error", this._rawWsErrorHandler);
} else if (typeof this._rawWsObj.off === "function") {
this._rawWsObj.off("message", this._rawWsMessageListener ?? this._rawWsHandler);
this._rawWsObj.off("error", this._rawWsErrorHandler);
}
} catch(e) { logger.warn("[Moonlink] Raw WS listener cleanup:", e?.message); }
}
if (wsObj === this._rawWsObj) return;
this._rawWsHandler = (rawData) => {
try {
const text = typeof rawData === "string" ? rawData : rawData?.data;
const payload = typeof text === "string" ? JSON.parse(text) : rawData;
if (payload?.t === "VOICE_SERVER_UPDATE") {
if (!payload.d?.guild_id) {
logger.warn("[MoonlinkManager] VOICE_SERVER_UPDATE: Missing guild_id", payload);
return;
}
this.manager.packetUpdate(payload);
}
} catch(e) { logger.warn("[Moonlink] Raw WS message parse error:", e?.message); }
};
this._rawWsErrorHandler = (errOrEvent) => {
if (typeof errOrEvent?.preventDefault === "function") errOrEvent.preventDefault();
const err = errOrEvent?.error ?? errOrEvent?.message ?? errOrEvent;
const now = Date.now();
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
_wsErrorCooldown.lastLogged = now;
logger.warn("[MoonlinkManager] Raw WS socket error (will reconnect):", err?.message ?? err);
};
this._rawWsMessageListener = (event) => this._rawWsHandler(event?.data ?? event);
if (typeof wsObj.addEventListener === "function") {
wsObj.addEventListener("message", this._rawWsMessageListener);
wsObj.addEventListener("error", this._rawWsErrorHandler);
} else if (typeof wsObj.on === "function") {
wsObj.on("message", this._rawWsMessageListener);
wsObj.on("error", this._rawWsErrorHandler);
}
this._rawWsObj = wsObj;
} catch (e) {
logger.warn("[MoonlinkManager] Raw WS setup error:", e.message);
}
};
attachRawWs();
client.on(Events.Ready, attachRawWs);
}
async init(clientId) {
this.setMaxListeners(50);
try { this.manager.setMaxListeners?.(50); } catch(e) { logger.warn("[Moonlink] init setMaxListeners:", e?.message); }
try {
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
const sock = node.socket ?? node.ws ?? null;
if (sock && typeof sock.removeAllListeners === "function") {
sock.removeAllListeners("open");
sock.removeAllListeners("close");
sock.removeAllListeners("error");
sock.removeAllListeners("message");
}
}
} catch(e) { logger.warn("[Moonlink] init socket cleanup:", e?.message); }
await this.manager.init(clientId);
}
search(query, source, requester) {
return this.manager.search({ query, source, requester });
}
createPlayer(opts) {
return this.manager.players.create(opts);
}
getPlayer(guildId) {
return this.manager.players.get(guildId);
}
destroy() {
try {
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
node.socket?.close?.();
}
} catch(e) { logger.warn("[Moonlink] destroy:", e?.message); }
}
}
+601 -1382
View File
File diff suppressed because it is too large. Load diff
+67 -176
View File
@@ -1,14 +1,4 @@
/**
* @file PlayerManager.mjs — PlayerManager — creates, caches, and routes Player instances per voice channel across all guilds
* @module src.PlayerManager
*/
/**
* PlayerManager.mjs — Manages voice channel players across servers
*
* Updated for moonlink.js: passes the MoonlinkManager instance into every
* new Player so it can resolve tracks and retrieve session IDs.
*/
/** @module src/PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */
import Player from "./Player.mjs";
import { Utils, cleanId } from "./Utils.mjs";
@@ -21,6 +11,7 @@ import { Dashboard } from "./dashboard/Dashboard.mjs";
import { hasHumansInChannel, iterateVoiceStates } from "./constants/VoiceStateResolver.mjs";
/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */
function getPlayerGuildId(player, fallbackChannel = null) {
return cleanId(
player?._guildId ??
@@ -31,20 +22,12 @@ function getPlayerGuildId(player, fallbackChannel = null) {
);
}
/** @private @param {Player} player @param {string|null} [fallbackChannelId=null] @returns {string} Cleaned channel ID. */
function getPlayerChannelId(player, fallbackChannelId = null) {
return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId);
}
/**
* Check whether the bot actually has the Connect permission on a specific
* voice channel. This uses @fluxerjs/core's PermissionFlags to test the
* bitfield directly, rather than relying on gateway error messages which
* conflate real permission denials with stale-session 401s.
*
* @param {import('@fluxerjs/core').Client} client
* @param {string} channelId
* @returns {boolean} true if the bot has Connect (and Speak) on the channel
*/
/** @private Check whether the bot has required voice permissions in a channel. @param {object} client @param {string} channelId @returns {boolean} True if the bot can connect, speak, and use VAD. */
function botHasVoicePermissions(client, channelId) {
try {
const channel = client?.channels?.get?.(channelId);
@@ -63,19 +46,7 @@ function botHasVoicePermissions(client, channelId) {
}
}
/**
* Sanitize raw voice-join error messages into user-friendly text.
*
* IMPORTANT: A 401/"permission" error from the gateway does NOT always mean
* the bot lacks the Connect permission. The Fluxer gateway can also return 401
* when the bot's previous voice session hasn't been cleaned up yet (stale
* session race). In that case the bot DOES have Connect — it's a transient
* error, not a real permission denial.
*
* To tell the difference, we check the actual channel permissions using
* botHasVoicePermissions(). If the bot HAS Connect but got 401, it's a
* stale session ("SESSION_RACE"), not a real permission error ("PERMISSION").
*/
/** @private Classify a join error into a known error code for user-facing messages. @param {Error} err @param {object} [client=null] @param {string} [channelId=null] @returns {string|null} Error code ('PERMISSION'|'NOT_FOUND'|'TIMEOUT'|'SESSION_RACE') or null. */
function sanitizeJoinError(err, client = null, channelId = null) {
const msg = String(err?.message ?? err ?? "");
if (msg.includes("401") || msg.includes("Unauthorized")) {
@@ -99,47 +70,49 @@ function sanitizeJoinError(err, client = null, channelId = null) {
return null;
}
/**
* PlayerManager class.
*/
/** @class PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */
export class PlayerManager {
/** @type {SettingsManager} */
/** @type {RemoteSettingsManager} */
settings;
/** @type {CommandHandler} */
commands;
/** @type {Map<string, Player>} Keyed by cleaned channel ID */
/** @type {Map<string, Player>} Player instances keyed by channel ID. */
playerMap = new Map();
/** @type {Map<string, Set<string>>} Reverse index: guildId → Set<channelId> for O(1) guild lookups */
/** @private @type {Map<string, Set<string>>} Guild ID → Set of channel IDs (for fast guild-player lookup). */
_guildPlayerIndex = new Map();
/** @type {Set<string>} Channel IDs currently being joined (not yet in playerMap) */
/** @private @type {Set<string>} Channel IDs currently being joined. */
_pendingJoins = new Set();
/** @type {Map<string, {timer, songUrl, startedAtMs}>} Pending scrobble timers keyed by channel ID.
* Prevents duplicate scrobbles when startplay fires multiple times. */
/** @private @type {Map<string, {timer: setTimeout, songUrl: string, startedAtMs: number}>} */
_pendingScrobbleTimers = new Map();
/** @type {Object} */
/** @type {object} Full bot config. */
config;
/** @type {Object} */
/** @type {object} Player-specific config (lavalink reference). */
playerConfig;
/** @type {import("./constants/Locale.mjs").Locale|null} */
/** @type {Locale|null} */
locale = null;
/** @type {import("./dashboard/Dashboard.mjs").Dashboard|null} */
/** @type {Dashboard|null} */
dashboard = null;
/**
* @param {SettingsManager} settings
* @param {CommandHandler} commands
* @param {Object} config
* @param {Object} config.config - Parsed config.json
* @param {Object} config.player - Config data passed to new Player instances
* Create a new PlayerManager.
* @param {RemoteSettingsManager} settings - The settings manager.
* @param {CommandHandler} commands - The command handler.
* @param {object} config - Configuration object.
* @param {object} config.config - Full bot config.
* @param {object} config.player - Player-specific config (lavalink, etc.).
* @param {Dashboard} [config.dashboard] - Dashboard instance.
* @param {Locale} [config.locale] - Locale manager.
* @param {object} [config.timers] - Timer configuration.
* @param {TrackOptionsManager} [config.trackOptions] - Track options manager.
*/
constructor(settings, commands, config) {
this.commands = commands;
@@ -153,12 +126,7 @@ export class PlayerManager {
this.trackOptions = config.trackOptions ?? null;
}
/**
* Add a channel to the guild→player reverse index.
* Called after a successful player join.
* @param {string} guildId
* @param {string} channelId
*/
/** @private Index a player by guild and channel ID for fast lookups. @param {string} guildId @param {string} channelId */
_indexPlayer(guildId, channelId) {
const gId = cleanId(guildId);
const cId = cleanId(channelId);
@@ -168,12 +136,7 @@ export class PlayerManager {
set.add(cId);
}
/**
* Remove a channel from the guild→player reverse index.
* Called on player leave/destroy.
* @param {string} guildId
* @param {string} channelId
*/
/** @private Remove a player from the guild-player index. @param {string} guildId @param {string} channelId */
_unindexPlayer(guildId, channelId) {
const gId = cleanId(guildId);
const cId = cleanId(channelId);
@@ -185,12 +148,7 @@ export class PlayerManager {
}
}
/**
* Get all [channelId, Player] entries for a guild.
* Uses the reverse index for O(1) guild lookup instead of O(n) scan.
* @param {string} guildId
* @returns {Array<[string, Player]>}
*/
/** Get all active (non-destroyed) players for a guild. @param {string} guildId @returns {Array<[string, Player]>} Array of [channelId, Player] pairs. */
getGuildPlayers(guildId) {
const gId = cleanId(guildId);
const set = this._guildPlayerIndex.get(gId);
@@ -207,12 +165,7 @@ export class PlayerManager {
return result;
}
/**
* Find a player by guildId and channelId using the reverse index.
* @param {string} guildId
* @param {string} channelId
* @returns {Player|null}
*/
/** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */
getPlayerByGuildAndChannel(guildId, channelId) {
const cId = cleanId(channelId);
const players = this.getGuildPlayers(guildId);
@@ -222,11 +175,7 @@ export class PlayerManager {
return null;
}
/**
* Find a player by channelId alone (scans guild index first, then fallback).
* @param {string} channelId
* @returns {Player|null}
*/
/** Find a player by its channel ID across all guilds. @param {string} channelId @returns {Player|null} */
getPlayerByChannelId(channelId) {
const cId = cleanId(channelId);
for (const [, channelSet] of this._guildPlayerIndex) {
@@ -238,22 +187,7 @@ export class PlayerManager {
return null;
}
/**
* Forward player lifecycle/state events to the dashboard pub/sub channels.
*
* IMPORTANT: Events are sent in standard { type, data } format so
* the backend (backend-master) PlayerManager can parse them correctly.
*
* Two channels are used:
* {platform}:players — global, for init/close lifecycle events
* {platform}:player_{id} — per-player, for playback/queue/volume events
*
* @param {Player} player
* @param {Object} [context]
* @param {string|null} [context.channelId]
* @param {string|null} [context.guildId]
* @returns {Player}
*/
/** Bind dashboard update and message-sending events on a player. @param {Player} player @param {object} [context={}] @returns {Player} The same player, with events bound. */
setupEvents(player, context = {}) {
if (!player || player._dashboardEventsBound) return player;
@@ -409,25 +343,14 @@ export class PlayerManager {
return player;
}
/**
* Translate a locale key using the message's guild locale.
* @param {Object} message
* @param {string} key
* @param {Object} [replacements={}]
* @returns {string}
*/
/** @private Translate a locale key for a message context. @param {object} message @param {string} key @param {object} [replacements={}] @returns {string} */
_t(message, key, replacements = {}) {
if (!this.locale) return key;
const guildId = getMessageGuildId(message);
return this.locale.translate(guildId, key, replacements);
}
/**
* Attempt to detect the voice channel a user is currently in.
* @param {Message} message
* @param {Object} [settings]
* @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>}
*/
/** Detect which voice channel the message author is in. @async @param {object} message @param {object} settings @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} */
async checkVoiceChannels(message, settings) {
const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message);
const userId = message?.author?.id ?? message?.member?.user?.id;
@@ -494,14 +417,7 @@ export class PlayerManager {
return { channelId, alreadyInVoice, hasHumans: hasHumansResult };
}
/**
* Get or create a player for the user's voice channel.
* @param {Message} message
* @param {boolean} [promptJoin=true]
* @param {boolean} [verifyUser=true]
* @param {boolean} [shouldJoin=false]
* @returns {Promise<Player|null>}
*/
/** Get or spawn a player for the message's voice channel. @async @param {object} message @param {boolean} [promptJoin=true] @param {boolean} [verifyUser=true] @param {boolean} [shouldJoin=false] @returns {Promise<Player|null>} */
async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) {
const guildId = getMessageGuildId(message);
const cleanGuildId = cleanId(guildId);
@@ -586,11 +502,7 @@ export class PlayerManager {
return null;
}
/**
* Prompt the user to select a voice channel.
* @param {Message} msg
* @returns {Promise<string|false>}
*/
/** Prompt the user to select a voice channel via reactions or text input. @async @param {object} msg @returns {Promise<Player|false>} */
async promptVC(msg) {
const { channelId: autoDetected } = await this.checkVoiceChannels(msg);
if (autoDetected) {
@@ -675,11 +587,7 @@ export class PlayerManager {
});
}
/**
* Make the player leave its current voice channel.
* @param {Message} msg
* @param {string} [cid]
*/
/** Leave a voice channel, destroy the player, and send a confirmation. @async @param {object} msg @param {string} [cid] @returns {Promise<void>} */
async leave(msg, cid) {
if (!cid) {
const guildId = getMessageGuildId(msg);
@@ -714,11 +622,7 @@ export class PlayerManager {
await msg.reply(this._t(msg, "responses._common.successfullyLeft"));
}
/**
* Restore saved volume for a player from server settings.
* @param {Player} player
* @param {string} guildId
*/
/** @private Restore saved volume for a player from guild settings. @param {Player} player @param {string} guildId */
_restorePlayerVolume(player, guildId) {
const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume");
if (savedVol !== undefined && savedVol !== null) {
@@ -727,12 +631,7 @@ export class PlayerManager {
}
}
/**
* Create and register a new Player for the given voice channel.
* @param {Message} message
* @param {string} cid - Voice channel ID
* @returns {Promise<Player|null>}
*/
/** Create a new Player, join the voice channel, and set up events. @async @param {object} message @param {string} cid @returns {Promise<Player|null>} The spawned player, or null on failure. */
async initPlayer(message, cid) {
const channel = this.commands.client?.channels?.get(cid);
@@ -775,9 +674,7 @@ export class PlayerManager {
...this.playerConfig,
client: this.commands.client,
config: this.config,
nodelink: this.config.nodelink,
moonlink: this.playerConfig?.moonlink ?? null,
revoice: this.playerConfig?.revoice ?? null,
lavalink: this.playerConfig?.lavalink ?? null,
settingsMgr: this.settings,
getPrefix: (guildId) => this.commands.getPrefix(guildId),
observedVoiceUsers: this.observedVoiceUsers ?? null,
@@ -818,8 +715,8 @@ export class PlayerManager {
? get247ChannelMode(this.settings.getServer(guildId), matchChannel)
: "off";
if (mode247 === "auto" || mode247 === "on") {
logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 ${mode247} channel ${activeChannelId} (guild ${guildId})`);
if (mode247 === "on") {
logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 channel ${activeChannelId} (guild ${guildId})`);
return;
}
if (player._hasHumansInChannel()) {
@@ -841,17 +738,8 @@ export class PlayerManager {
const prefix = this.commands.getPrefix(guildId);
let desc;
if (mode247 === "on") {
desc = this.locale?.translate(guildId, "responses.join.autoLeave247On", { channel: `<#${activeChannelId}>`, prefix })
?? `Left channel <#${activeChannelId}> because of inactivity.\nI'll rejoin automatically when the bot restarts (${prefix}247 on mode).`;
} else if (mode247 === "auto") {
desc = this.locale?.translate(guildId, "responses.join.autoLeave247Auto", { channel: `<#${activeChannelId}>`, prefix })
?? `Left channel <#${activeChannelId}> — reconnecting automatically (${prefix}247 auto mode)...`;
} else {
desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive247", { channel: `<#${activeChannelId}>`, prefix })
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
}
const desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive", { channel: `<#${activeChannelId}>`, prefix })
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247\``;
if (typeof ch?.send === "function") {
ch.send({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)], allowedMentions: { parse: [] } }).catch(err => {
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
@@ -862,6 +750,18 @@ export class PlayerManager {
});
player.on("message", (m) => {
const isTextChannel = (c) => {
if (!c) return false;
if (c.type === undefined || c.type === null) return false;
const voiceTypes = [2, 13, "GUILD_VOICE", "GUILD_STAGE_VOICE", "STAGE", "voice", "stage"];
if (voiceTypes.includes(c.type)) return false;
if (typeof c.isTextBased === "function") return c.isTextBased();
const textTypes = [0, 5, 10, 11, 12, "GUILD_TEXT", "GUILD_ANNOUNCEMENT", "text"];
if (textTypes.includes(c.type)) return true;
logger.warn(`[PlayerManager] isTextChannel: unknown channel type=${c.type} id=${c.id}, rejecting`);
return false;
};
let ch = player.textChannel;
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
@@ -870,33 +770,35 @@ export class PlayerManager {
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return;
if (!ch || typeof ch.send !== "function") {
if (!isTextChannel(ch)) {
try {
const serverSettings = this.settings.getServer(guildId);
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
if (savedAnnChId) {
ch = this.commands?.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
const resolved = this.commands?.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
if (isTextChannel(resolved)) ch = resolved;
}
} catch(e) {
logger.warn("[PlayerManager] Failed to resolve announcement channel:", e?.message);
}
}
if (!ch || typeof ch.send !== "function") {
if (!isTextChannel(ch)) {
try {
const guild = this.commands?.client?.guilds?.get?.(guildId);
if (guild?.systemChannelId) {
ch = guild.channels?.get?.(guild.systemChannelId) ?? null;
const resolved = guild.channels?.get?.(guild.systemChannelId) ?? null;
if (isTextChannel(resolved)) ch = resolved;
}
} catch(e) {
logger.warn("[PlayerManager] Failed to resolve system channel:", e?.message);
}
}
if (!ch || typeof ch.send !== "function") {
if (!isTextChannel(ch)) {
try {
const guild = this.commands?.client?.guilds?.get?.(guildId);
if (guild?.channels) {
for (const c of (guild.channels.values?.() ?? [])) {
if (c.isTextBased?.() || c.type === 0 || c.type === "GUILD_TEXT") {
if (isTextChannel(c)) {
ch = c;
break;
}
@@ -906,12 +808,12 @@ export class PlayerManager {
logger.warn("[PlayerManager] Failed to find fallback text channel:", e?.message);
}
}
if (!ch || typeof ch.send !== "function") {
logger.warn(`[PlayerManager] Could not resolve any channel to send now-playing announcement (guild ${guildId})`);
if (!isTextChannel(ch)) {
logger.warn(`[PlayerManager] Could not resolve any text channel to send now-playing announcement (guild ${guildId})`);
return;
}
if (!player.textChannel) player.textChannel = ch;
if (!player.textChannel || !isTextChannel(player.textChannel)) player.textChannel = ch;
const payload = typeof m === "object" && Array.isArray(m.embeds)
? { ...m, allowedMentions: { parse: [] } }
@@ -948,10 +850,6 @@ export class PlayerManager {
logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`);
try {
await new Promise(r => setTimeout(r, 2_000));
if (player._revoice && player._channelId) {
try { player._revoice._leaveGateway(player._channelId, player._guildId ?? player._resolveGuildId()); } catch(e) { logger.warn("[PlayerManager] Failed to leave gateway during retry:", e?.message); }
try { player._revoice.deleteConnection(player._channelId); } catch(e) { logger.warn("[PlayerManager] Failed to delete connection during retry:", e?.message); }
}
await player.join(cid);
this.playerMap.set(cleanChannelId, player);
@@ -982,14 +880,7 @@ export class PlayerManager {
}
}
/**
* Handle the "startplay" event for Last.fm: send now-playing notification
* to all linked users in the voice channel, and schedule a deferred scrobble
* after the track has played for long enough (50% duration or 4 min).
*
* @param {Player} player
* @param {Object} song - Track object
*/
/** @private Handle Last.fm now-playing update and schedule scrobble timer. @param {Player} player @param {object} song */
_handleLastFmStartPlay(player, song) {
const lastfm = this._lastfm;
if (!lastfm?.enabled) return;
+281 -119
View File
@@ -1,184 +1,280 @@
/**
* @file Settings.mjs — Settings — abstract base class and RemoteSettingsManager for per-server configuration backed by SQLite
* @module src.Settings
* @module src/Settings
* @description MySQL-backed settings system for per-guild bot configuration.
* Supports debounced writes (80ms), multi-bot via bot_id column, and
* automatic schema migration for legacy tables.
*/
import fs from "node:fs";
import { logger } from "./constants/Logger.mjs";
import mysql from "mysql2";
import { EventEmitter } from "node:events";
import { logger } from "./constants/Logger.mjs";
/**
* Abstract base class for settings managers.
* Provides the interface that all concrete settings managers must implement.
* Base settings manager providing defaults, descriptions, and key utilities.
* Subclassed by RemoteSettingsManager for MySQL-backed persistence.
* @extends {EventEmitter}
*/
export class SettingsManager extends EventEmitter {
/** @abstract @type {Object} */
/** @type {object} Default setting values keyed by setting name. */
defaults;
/** @abstract */
update(server, key) { }
/** @abstract @returns {ServerSettings} */
getServer(id) { }
/** @abstract @returns {boolean} */
hasServer(id) { }
/** @abstract @returns {boolean} */
isOption(key) { }
/** @type {object} Setting descriptions keyed by setting name. */
descriptions;
/** @type {Set<string>} Internal keys hidden from getPublicKeys(). */
internalKeys;
/**
* Mark setting keys as internal (hidden from getPublicKeys).
* @param {...string} keys - Setting key names to mark internal.
*/
markInternal(...keys) {
if (!this.internalKeys) this.internalKeys = new Set();
for (const k of keys) this.internalKeys.add(k);
}
/**
* ServerSettings class.
* Check whether a setting key is internal.
* @param {string} key - The setting key to check.
* @returns {boolean} True if the key is marked internal.
*/
isInternal(key) {
return this.internalKeys?.has(key) ?? false;
}
/**
* Check whether a setting key exists in defaults.
* @param {string} key - The setting key.
* @returns {boolean} True if the key is a known setting.
*/
isOption(key) { return key in this.defaults; }
/**
* Get all non-internal setting keys.
* @returns {string[]} Array of public-facing setting key names.
*/
getPublicKeys() {
return Object.keys(this.defaults).filter(k => !this.isInternal(k));
}
}
/**
* Per-guild settings container. Delegates persistence to a RemoteSettingsManager.
* All mutations call manager.update() which triggers a debounced DB write.
*/
export class ServerSettings {
/** @type {string} The guild ID. */
id;
/** @type {RemoteSettingsManager} The parent settings manager. */
manager;
/** @type {object} Key-value store of current setting values. */
data = {};
/**
* @param {string} id Guild ID these settings belong to
* @param {SettingsManager} mgr Owning settings manager, used for defaults and persistence
* Create a new ServerSettings instance for a guild.
* @param {string} id - The guild ID.
* @param {RemoteSettingsManager} mgr - The parent settings manager.
*/
constructor(id, mgr) {
this.id = id;
this.manager = mgr;
this.loadDefaults();
}
/**
* Set a setting value and trigger a debounced database write.
* @param {string} key - The setting key.
* @param {*} value - The new value.
*/
set(key, value) { this.data[key] = value; this.manager.update(this, key); }
/**
* Get a setting value.
* @param {string} key - The setting key.
* @returns {*} The current value, or undefined if not set.
*/
get(key) { return this.data[key]; }
/**
* Reset a setting to its default value and persist the change.
* @param {string} key - The setting key to reset.
* @returns {*} The default value.
*/
reset(key) { return this.set(key, this.manager.defaults[key]); }
getAll() { return this.data; }
loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } }
checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
/**
* Get a shallow copy of all current setting values.
* @returns {object} Plain object with all key-value pairs.
*/
getAll() { return { ...this.data }; }
deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } }
/**
* Load all default values from the manager into this.data.
*/
loadDefaults() { for (const key in this.manager.defaults) this.data[key] = this.manager.defaults[key]; }
/**
* Fill in any missing keys from a defaults object without overwriting existing values.
* @param {object} d - Defaults object to check against.
*/
checkDefaults(d) { for (const key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
/**
* Restore settings from a parsed JSON object (skips the 'id' field).
* @param {object} json - Key-value pairs to restore.
*/
deserialize(json) { for (const k in json) { if (k === 'id') continue; this.data[k] = json[k]; } }
/**
* Get a serializable copy of settings data including the guild ID.
* @returns {object} Plain object suitable for JSON.stringify.
*/
get serializationData() { return { ...this.data, id: this.id }; }
/** @returns {object} Alias for serializationData. */
serialize() { return this.serializationData; }
/** @returns {object} Alias for serializationData. */
serializeObject() { return this.serializationData; }
}
/**
* RemoteSettingsManager class.
* MySQL-backed settings manager. Loads all guild settings at startup,
* persists changes with an 80ms debounce per guild, and supports multi-bot
* operation via a `bot_id` column.
*
* @extends {SettingsManager}
* @fires SettingsManager#ready - Emitted after the initial DB load completes.
*/
export class RemoteSettingsManager extends SettingsManager {
/** @type {Map<string, ServerSettings>} Cached guild settings keyed by guild ID. */
guilds = new Map();
descriptions = {};
defaults = {};
/** @type {import('mysql2').Pool} MySQL connection pool. */
db = null;
/** @type {string|null} Bot user ID — used to isolate rows per-bot in shared databases */
/** @type {string|null} Current bot user ID for multi-bot support. */
botId = null;
/** @type {boolean} Whether the bot_id column exists in the settings table */
/** @private @type {boolean} Whether the bot_id column has been verified. */
_hasBotIdColumn = false;
/** @private */
_loadAttempts = 0;
/** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */
/** @private @type {Promise|null} Pending initial load promise. */
_loadPromise = null;
/** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */
_debounceTimers = new Map();
/** @private @type {boolean} True after shutdown() is called. */
_shuttingDown = false;
/**
* @param {Object} config MySQL connection config passed to mysql2's createPool
* @param {string} defaultsPath Filesystem path to the JSON file with default guild settings
* @param {string|null} [botId=null] Bot user ID for multi-bot row isolation, or null for single-bot mode
* Create a new RemoteSettingsManager backed by a MySQL pool.
* @param {object} config - mysql2 pool configuration (host, user, password, database).
* @param {string} defaultsPath - Path to a JSON file with default values and descriptions.
* @param {string|null} [botId=null] - The bot user ID for multi-bot support.
*/
constructor(config, defaultsPath, botId = null) {
super();
this.botId = botId;
this.db = mysql.createPool({ connectionLimit: 15, ...config });
this.db.on("error", (err) => {
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
this.db.on('error', (err) => {
logger.error('[DB] MySQL pool error:', err.code ?? err.message);
});
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
this._loadPromise = this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err));
this._loadPromise = this.load().catch(err =>
logger.error('[Settings] Initial load failed:', err?.message ?? err)
);
}
/**
* Check whether the `bot_id` column exists in the settings table AND is
* part of the primary key. If the column is missing, auto-migrate by
* adding it (NOT NULL DEFAULT '') and updating the primary key to (id, bot_id).
* If the column exists but isn't in the PK (previous failed migration),
* fix the NULL values and retry the PK update.
* Stop all pending debounced writes. Call before process exit.
* @returns {Promise<void>}
*/
async shutdown() {
this._shuttingDown = true;
for (const [, timer] of this._debounceTimers) clearTimeout(timer);
this._debounceTimers.clear();
}
/**
* Execute a raw MySQL query and wrap the callback in a promise.
* @param {string} q - SQL query string.
* @returns {Promise<{error: Error|null, results: any[], fields: any}>}
*/
query(q) {
return new Promise(res => {
this.db.query(q, (error, results, fields) => { res({ error, results, fields }); });
});
}
/**
* Ensure the `bot_id` column exists in the settings table and is part of the primary key.
* Auto-migrates legacy tables that lack the column.
* @returns {Promise<void>}
* @private
*/
async _ensureBotIdColumn() {
if (this._hasBotIdColumn) return;
const res = await this.query(
`SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS `
+ `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'`
);
if (res.error) {
logger.error("[Settings] Failed to check bot_id column:", res.error);
logger.error('[Settings] Failed to check bot_id column:', res.error);
return;
}
if (res.results.length === 0) {
logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table...");
const alterRes = await this.query(
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`
);
logger.settings('[Settings] Auto-migrating: adding bot_id column to settings table...');
const alterRes = await this.query(`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`);
if (alterRes.error) {
logger.error("[Settings] Failed to add bot_id column:", alterRes.error);
logger.error('[Settings] Failed to add bot_id column:', alterRes.error);
return;
}
if (this.botId) {
await this.query(
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
);
await this.query(`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`);
}
const pkRes = await this.query(
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
);
const pkRes = await this.query(`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`);
if (pkRes.error) {
logger.error("[Settings] Failed to update primary key:", pkRes.error);
logger.error('[Settings] Failed to update primary key:', pkRes.error);
return;
}
this._hasBotIdColumn = true;
logger.settings("[Settings] Auto-migration complete: bot_id column added.");
logger.settings('[Settings] Auto-migration complete: bot_id column added.');
return;
}
const colInfo = res.results[0];
const isNullable = colInfo.IS_NULLABLE === 'YES';
const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI';
if (isPrimaryKey) {
if (colInfo.COLUMN_KEY === 'PRI') {
this._hasBotIdColumn = true;
return;
}
logger.settings("[Settings] Fixing bot_id column: adding to primary key...");
if (isNullable) {
logger.settings('[Settings] Fixing bot_id column: adding to primary key...');
if (colInfo.IS_NULLABLE === 'YES') {
await this.query(`UPDATE settings SET bot_id = '' WHERE bot_id IS NULL`);
await this.query(`ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`);
}
if (this.botId) {
await this.query(
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
);
await this.query(`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`);
}
const pkRes = await this.query(
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
);
const pkRes = await this.query(`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`);
if (pkRes.error) {
logger.error("[Settings] Failed to update primary key:", pkRes.error);
logger.error('[Settings] Failed to update primary key:', pkRes.error);
return;
}
this._hasBotIdColumn = true;
logger.settings("[Settings] Fix complete: bot_id column added to primary key.");
logger.settings('[Settings] Fix complete: bot_id column added to primary key.');
}
/**
* Set or update the bot ID used for database row isolation.
* Called after login when the bot user ID becomes available.
* @param {string} id
* Set the bot ID and claim any orphaned settings rows (bot_id = '').
* @param {string} id - The bot user ID.
* @returns {Promise<void>}
*/
async setBotId(id) {
const changed = this.botId !== id;
@@ -186,7 +282,6 @@ export class RemoteSettingsManager extends SettingsManager {
if (changed) {
if (this._loadPromise) await this._loadPromise;
await this._ensureBotIdColumn();
if (this._hasBotIdColumn && this.botId) {
const claimRes = await this.query(
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
@@ -195,133 +290,200 @@ export class RemoteSettingsManager extends SettingsManager {
logger.settings(`[Settings] Claimed ${claimRes.results.affectedRows} legacy row(s) for bot ${this.botId}`);
}
}
this.guilds.clear();
this._loadPromise = this.load();
await this._loadPromise;
}
}
/**
* Build a SQL WHERE fragment filtering by the current bot_id.
* @returns {string} SQL fragment (empty string if bot_id not set or column unverified).
* @private
*/
_botIdWhere() {
if (!this.botId || !this._hasBotIdColumn) return "";
if (!this.botId || !this._hasBotIdColumn) return '';
return ` AND bot_id = ${mysql.escape(String(this.botId))}`;
}
/**
* Build SQL column/value fragments for bot_id in INSERT statements.
* @returns {{col: string, val: string}} SQL fragments (empty strings if bot_id not applicable).
* @private
*/
_botIdInsert() {
if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" };
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
if (!this.botId || !this._hasBotIdColumn) return { col: '', val: '' };
return { col: ', bot_id', val: `, ${mysql.escape(String(this.botId))}` };
}
selectGuild(guildId) {
/**
* Fetch the settings row for a single guild.
* @param {string} guildId - The guild ID.
* @returns {Promise<{error: Error|null, results: any[], fields: any}>}
*/
async selectGuild(guildId) {
const escapedId = mysql.escape(String(guildId));
return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`);
}
query(q) {
return new Promise(res => {
this.db.query(q, (error, results, fields) => { res({ error, results, fields }); });
});
}
/**
* Load all guild settings from the database. Retries with exponential backoff on failure.
* Emits 'ready' when complete.
* @returns {Promise<void>}
*/
async load() {
const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`);
if (res.error) {
this._loadAttempts++;
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000);
logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error);
logger.error('[Settings] Init error (attempt', this._loadAttempts, 'retrying in', delay + 'ms):', res.error);
return new Promise((resolve) => { setTimeout(() => { this.load().then(resolve).catch(resolve); }, delay); });
}
this._loadAttempts = 0;
res.results.forEach((r) => {
try {
const server = new ServerSettings(r.id, this);
const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data;
const parsed = (typeof r.data === 'string') ? JSON.parse(r.data) : r.data;
server.deserialize(parsed);
server.checkDefaults(this.defaults);
this.guilds.set(server.id, server);
} catch (e) {
logger.error("[Settings] Failed to parse settings for server", r.id, ":", e.message);
logger.error('[Settings] Failed to parse settings for server', r.id, ':', e.message);
}
});
this.emit("ready");
this.emit('ready');
}
/**
* Persist a single key change via MySQL JSON_SET. Falls back to a full blob save for arrays/objects.
* @param {ServerSettings} server - The guild settings instance.
* @param {string} key - The changed key.
* @returns {Promise<void>}
*/
async remoteUpdate(server, key) {
if (this._shuttingDown) return;
const val = server.data[key];
if (Array.isArray(val) || (typeof val === "object" && val !== null)) {
if (Array.isArray(val) || (typeof val === 'object' && val !== null)) {
return this.remoteSave(server);
}
const escapedPath = mysql.escape(`$.${key}`);
const escapedVal = (typeof val === "boolean" || typeof val === "number")
? mysql.escape(val)
: mysql.escape(String(val));
const jsonVal = JSON.stringify(val);
const escapedVal = mysql.escape(jsonVal);
const escapedId = mysql.escape(server.id);
const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, ${escapedVal}) WHERE id=${escapedId}${this._botIdWhere()}`);
if (r.error) logger.error("[Settings] remoteUpdate error:", r.error);
const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, CAST(${escapedVal} AS JSON)) WHERE id=${escapedId}${this._botIdWhere()}`);
if (r.error) logger.error('[Settings] remoteUpdate error:', r.error);
}
/**
* Persist the entire guild settings blob to the database.
* @param {ServerSettings} server - The guild settings instance.
* @returns {Promise<void>}
*/
async remoteSave(server) {
if (this._shuttingDown) return;
const escapedData = mysql.escape(JSON.stringify(server.data));
const escapedId = mysql.escape(server.id);
const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}`);
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
if (r.error) logger.error('[Settings] remoteSave error:', r.error);
}
/**
* Synchronously load default values and descriptions from a JSON file.
* @param {string} filePath - Path to the JSON file.
*/
loadDefaultsSync(filePath) {
try {
const d = fs.readFileSync(filePath, "utf8");
const d = fs.readFileSync(filePath, 'utf8');
const parsed = JSON.parse(d);
this.descriptions = parsed.descriptions;
this.defaults = parsed.values;
this.descriptions = parsed.descriptions ?? {};
this.defaults = parsed.values ?? {};
if (parsed.internal) this.markInternal(...parsed.internal);
} catch (e) {
logger.error("[Settings] Failed to load defaults from", filePath, ":", e.message);
logger.error('[Settings] Failed to load defaults from', filePath, ':', e.message);
this.descriptions = {};
this.defaults = {};
}
}
/**
* Save all guild settings to the database in parallel.
* @returns {Promise<void>}
*/
async saveAsync() {
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v)));
}
/**
* Insert a new settings row for a guild. Uses INSERT IGNORE to avoid duplicate-key errors.
* @param {string} id - The guild ID.
* @param {ServerSettings} server - The settings instance.
* @returns {Promise<void>}
*/
async create(id, server) {
if (this._shuttingDown) return;
const escapedId = mysql.escape(id);
const escapedData = mysql.escape(JSON.stringify(server.data));
const bi = this._botIdInsert();
const r = await this.query(
`INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})`
);
if (r.error) logger.error("[Settings] create error:", r.error);
if (r.error) logger.error('[Settings] create error:', r.error);
}
/**
* Queue a debounced database write for a single key change (80ms delay per guild).
* If the guild is not yet cached, it is added and a CREATE is issued.
* @param {ServerSettings} server - The guild settings instance.
* @param {string} key - The changed key.
*/
update(server, key) {
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server).catch(e => logger.error("[Settings] create error in update:", e.message)); }
if (this._shuttingDown) return;
if (!this.guilds.has(server.id)) {
this.guilds.set(server.id, server);
this.create(server.id, server).catch(e => logger.error('[Settings] create error in update:', e.message));
}
const s = this.guilds.get(server.id);
s.data[key] = server.data[key];
const existing = this._debounceTimers.get(server.id);
if (existing) clearTimeout(existing);
this._debounceTimers.set(server.id, setTimeout(() => {
this._debounceTimers.delete(server.id);
this.remoteSave(s);
const target = this.guilds.get(server.id);
if (target) this.remoteUpdate(target, key);
}, 80));
}
/**
* Check whether a setting key exists in defaults.
* @param {string} key - The setting key.
* @returns {boolean}
*/
isOption(key) { return key in this.defaults; }
/**
* Check whether a guild has cached settings.
* @param {string} id - The guild ID.
* @returns {boolean}
*/
hasServer(id) { return this.guilds.has(id); }
/**
* Get settings for a guild. Returns a fresh ServerSettings (with defaults) if not cached.
* @param {string} id - The guild ID.
* @returns {ServerSettings}
*/
getServer(id) {
if (!this.guilds.has(id)) {
return new ServerSettings(id, this);
}
if (!this.guilds.has(id)) return new ServerSettings(id, this);
return this.guilds.get(id);
}
/**
* Remove a guild from the cache and cancel any pending debounced writes.
* @param {string} id - The guild ID.
*/
removeServer(id) {
const timer = this._debounceTimers.get(id);
if (timer) {
clearTimeout(timer);
this._debounceTimers.delete(id);
}
if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); }
this.guilds.delete(id);
}
}
+25 -11
View File
@@ -1,29 +1,28 @@
/**
* @file TrackOptionsManager.mjs — TrackOptionsManager — SQLite-backed per-track options storage for auto-seek and end-time timers
* @module src.TrackOptionsManager
*/
/** @module src/TrackOptionsManager @description Per-user track options (start/end timestamps) stored in MySQL. Provides caching, matching, and CRUD for track segments. */
import mysql from "mysql2";
import { logger } from "./constants/Logger.mjs";
const DEFAULT_ALIAS = "default";
const MAX_ALIAS_LEN = 32;
/**
* TrackOptionsManager class.
*/
/** @class TrackOptionsManager @description Manages per-user track options (start/end timestamps, aliases) stored in MySQL. Provides caching, best-match lookup, and CRUD operations. */
export class TrackOptionsManager {
/** @type {import('mysql2').Pool} */
db = null;
/** @type {string|null} */
botId = null;
/** @private */
_hasTable = false;
/** @private */
_ready = false;
/** @private */
_readyPromise = null;
/** @private @type {Map<string, object>} */
_cache = new Map();
/** @private @type {number} */
_cacheMaxSize = 2000;
/**
* @param {Object} mysqlConfig MySQL connection config passed to mysql2's createPool
*/
/** @param {object} mysqlConfig - MySQL connection config. */
constructor(mysqlConfig) {
this.db = mysql.createPool({ connectionLimit: 10, ...mysqlConfig });
this.db.on("error", (err) => {
@@ -32,10 +31,12 @@ export class TrackOptionsManager {
this._readyPromise = this._ensureTable();
}
/** @async Wait for the table to be ready. @returns {Promise<void>} */
async ready() {
await this._readyPromise;
}
/** @private @async Ensure the track_options table exists with proper schema. */
async _ensureTable() {
try {
await this._query(
@@ -62,6 +63,7 @@ export class TrackOptionsManager {
}
}
/** @private @async Migrate from old schema (single unique key) to new (with alias column). */
async _migrateOldTable() {
try {
const cols = await this._query(`SHOW COLUMNS FROM track_options LIKE 'alias'`);
@@ -75,10 +77,12 @@ export class TrackOptionsManager {
}
}
/** @async Set the bot ID for multi-bot isolation. @param {string} id */
async setBotId(id) {
this.botId = id;
}
/** @private Execute a raw SQL query. @param {string} q @returns {Promise<Array>} */
_query(q) {
return new Promise((resolve, reject) => {
this.db.query(q, (error, results) => {
@@ -88,22 +92,26 @@ export class TrackOptionsManager {
});
}
/** @private @returns {string} SQL WHERE clause fragment for bot_id. */
_botIdWhere() {
if (!this.botId) return "";
return ` AND bot_id = ${mysql.escape(String(this.botId))}`;
}
/** @private @returns {{col: string, val: string}} SQL column and value fragments for bot_id INSERT. */
_botIdInsert() {
if (!this.botId) return { col: "", val: "" };
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
}
/** Sanitize an alias to alphanumeric, lowercase, max MAX_ALIAS_LEN chars. @param {*} raw @returns {string} */
static sanitizeAlias(raw) {
if (!raw || typeof raw !== "string") return DEFAULT_ALIAS;
const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, "").toLowerCase().slice(0, MAX_ALIAS_LEN);
return cleaned || DEFAULT_ALIAS;
}
/** Build a unique identifier for a track from its URL or artist-title combination. @param {object} track @returns {string|null} */
static makeTrackIdentifier(track) {
if (!track) return null;
if (track.url) {
@@ -122,6 +130,7 @@ export class TrackOptionsManager {
return null;
}
/** @async Save or update a track option. @param {string} userId @param {object} track @param {number} startMs @param {number} endMs @param {string} [alias] @returns {Promise<{identifier: string, startMs: number, endMs: number, alias: string}|null>} */
async set(userId, track, startMs, endMs, alias = DEFAULT_ALIAS) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
@@ -145,6 +154,7 @@ export class TrackOptionsManager {
}
}
/** @async Get a user's track option for a track. @param {string} userId @param {object} track @param {string} [alias] @returns {Promise<{startMs: number, endMs: number, title: string, alias: string}|null>} */
async get(userId, track, alias = DEFAULT_ALIAS) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
@@ -177,6 +187,7 @@ export class TrackOptionsManager {
}
}
/** @async Get all track options for a track for a user. @param {string} userId @param {object} track @returns {Promise<Array>} */
async getAllForTrack(userId, track) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
@@ -193,6 +204,7 @@ export class TrackOptionsManager {
}
}
/** @async Remove track option(s) for a user. @param {string} userId @param {object} track @param {string|null} [alias] @returns {Promise<boolean>} Whether a row was deleted. */
async remove(userId, track, alias = null) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
@@ -220,6 +232,7 @@ export class TrackOptionsManager {
}
}
/** @async List all track options for a user. @param {string} userId @param {number} [limit=25] @returns {Promise<Array>} */
async list(userId, limit = 25) {
await this.ready();
try {
@@ -233,6 +246,7 @@ export class TrackOptionsManager {
}
}
/** @async Find the first matching track option among a set of users. @param {string[]} userIds @param {object} track @param {string} [alias] @returns {Promise<{startMs: number, endMs: number, title: string, alias: string, userId: string}|null>} */
async getBestMatchForChannel(userIds, track, alias = DEFAULT_ALIAS) {
await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
+72 -92
View File
@@ -1,40 +1,24 @@
/**
* @file Utils.mjs — Utility class with static helpers — text normalization, markdown escaping, duration parsing, and string truncation
* @module src.Utils
*/
/**
* Utils.mjs — Music bot utility functions
* @module Utils
*
* Internal helpers delegate to @fluxerjs/util where available
* (escapeMarkdown, truncate) with additional null-safety guards.
*/
/** @module src/Utils @description General-purpose utility functions for formatting, validation, string manipulation, and ID cleaning. */
import { escapeMarkdown as _escapeMarkdown, truncate as _truncate } from "@fluxerjs/util";
import { logger } from "./constants/Logger.mjs";
/**
* Strip non-digit characters from a value, returning a clean ID string.
* Replaces the inline `String(x).replace(/\D/g, "")` pattern used 97+ times.
* @param {string|number} value
* @returns {string}
* Strip all non-digit characters from a value to extract a Snowflake/numeric ID.
* @param {*} value - The value to clean (string, number, or null/undefined).
* @returns {string} The numeric portion of the value, or empty string if none.
*/
export function cleanId(value) {
return String(value ?? "").replace(/\D/g, "");
}
/**
* @class Utils
* @description Static utility methods for time formatting, array manipulation,
* string processing, and validation used across the music bot.
*/
/** @class Utils @description Collection of static utility methods for formatting, parsing, and string manipulation. */
export class Utils {
/**
* Format milliseconds to human-readable time string (H:MM:SS or M:SS)
* @param {number} milliseconds - Duration in milliseconds
* @returns {string} Formatted time string
* Format a duration in milliseconds to a human-readable string (e.g. "1:23:45").
* @param {number} milliseconds - Duration in milliseconds.
* @returns {string} Formatted duration string.
*/
static prettifyMS(milliseconds) {
if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) {
@@ -54,9 +38,9 @@ export class Utils {
}
/**
* Parse duration string (H:MM:SS or M:SS or raw seconds) to milliseconds.
* @param {string} str - Duration string
* @returns {number} Milliseconds, 0 if invalid
* Parse a duration string (e.g. "1:30", "1:30:00", "90") into milliseconds.
* @param {string} str - Duration string in mm:ss, hh:mm:ss, or plain seconds.
* @returns {number} Duration in milliseconds, or 0 if unparseable.
*/
static parseDuration(str) {
if (!str || typeof str !== "string") return 0;
@@ -78,9 +62,9 @@ export class Utils {
}
/**
* Format seconds to MM:SS (for NodeLink duration compatibility)
* @param {number} seconds - Duration in seconds
* @returns {string} Formatted time
* Format seconds into a human-readable duration string.
* @param {number} seconds - Duration in seconds.
* @returns {string} Formatted duration string.
*/
static formatSeconds(seconds) {
if (!seconds || seconds < 0 || !isFinite(seconds)) return "0:00";
@@ -88,10 +72,9 @@ export class Utils {
}
/**
* Shuffles array in-place using Fisher-Yates algorithm
* @template T
* @param {T[]} array - Array to shuffle
* @returns {T[]} Same array reference (shuffled)
* Fisher-Yates in-place shuffle of an array.
* @param {Array} array - The array to shuffle (mutated in place).
* @returns {Array} The same array, shuffled.
*/
static shuffleArr(array) {
if (!Array.isArray(array) || array.length < 2) return array;
@@ -104,11 +87,11 @@ export class Utils {
}
/**
* Truncate text with ellipsis
* @param {string} str - String to truncate
* @param {number} [maxLen=100] - Maximum length
* @param {string} [suffix="..."] - Suffix to add
* @returns {string} Truncated string
* Truncate a string to a maximum length, appending a suffix if truncated.
* @param {string} str - The string to truncate.
* @param {number} [maxLen=100] - Maximum character length.
* @param {string} [suffix="..."] - Suffix to append when truncated.
* @returns {string} Truncated string.
*/
static truncate(str, maxLen = 100, suffix = "...") {
if (!str || typeof str !== "string") return "";
@@ -118,10 +101,9 @@ export class Utils {
}
/**
* Clean song title by removing common suffixes/prefixes for better matching
* Used for lyrics search and display normalization
* @param {string} title - Raw title
* @returns {string} Cleaned title
* Clean a track title by removing common noise patterns (feat, remix, lyrics, etc.).
* @param {string} title - The raw track title.
* @returns {string} Cleaned title.
*/
static cleanTitle(title) {
if (!title || typeof title !== "string") return "Unknown";
@@ -156,10 +138,9 @@ export class Utils {
}
/**
* Escape markdown formatting characters.
* Delegates to @fluxerjs/util escapeMarkdown.
* @param {string} text - Raw text
* @returns {string} Escaped text
* Escape Discord markdown special characters in text.
* @param {string} text - The text to escape.
* @returns {string} Escaped text, or empty string if falsy.
*/
static escapeMarkdown(text) {
if (!text || typeof text !== "string") return "";
@@ -167,9 +148,9 @@ export class Utils {
}
/**
* Format number with commas (e.g., 1,000,000)
* @param {number} num - Number to format
* @returns {string} Formatted number
* Format a number with locale-aware thousand separators.
* @param {number} num - The number to format.
* @returns {string} Formatted number string.
*/
static formatNumber(num) {
if (num === null || num === undefined || isNaN(num)) return "0";
@@ -177,9 +158,9 @@ export class Utils {
}
/**
* Generate random unique ID
* @param {number} [length=16] - Desired length of ID (8-32 recommended)
* @returns {string} Random ID
* Generate a unique ID string based on timestamp and random characters.
* @param {number} [length=16] - Target length of the ID (clamped 8–32).
* @returns {string} A unique alphanumeric ID.
*/
static uid(length = 16) {
const targetLen = Math.max(8, Math.min(length, 32));
@@ -195,9 +176,9 @@ export class Utils {
}
/**
* Check if a value represents a finite number
* @param {string|number} str
* @returns {boolean}
* Check whether a value is a valid finite number or numeric string.
* @param {*} str - Value to check.
* @returns {boolean} True if the value is a valid number.
*/
static isNumber(str) {
if (str === null || str === undefined || str === "") return false;
@@ -207,10 +188,9 @@ export class Utils {
}
/**
* Check if value is a valid URL
* Used by worker.mjs YTUtils.isValidUrl
* @param {string} str - String to check
* @returns {boolean} True if valid URL
* Check whether a string is a valid URL.
* @param {string} str - String to check.
* @returns {boolean} True if the string is a valid URL.
*/
static isValidUrl(str) {
if (!str || typeof str !== "string") return false;
@@ -223,11 +203,11 @@ export class Utils {
}
/**
* Clamp number between min and max
* @param {number} num - Number to clamp
* @param {number} min - Minimum value
* @param {number} max - Maximum value
* @returns {number} Clamped value
* Clamp a number between a minimum and maximum value.
* @param {number} num - The number to clamp.
* @param {number} min - Minimum value.
* @param {number} max - Maximum value.
* @returns {number} Clamped value.
*/
static clamp(num, min, max) {
if (isNaN(num)) return min;
@@ -235,8 +215,8 @@ export class Utils {
}
/**
* Sleep/delay promise
* @param {number} ms - Milliseconds to sleep
* Return a promise that resolves after a specified delay.
* @param {number} ms - Delay in milliseconds.
* @returns {Promise<void>}
*/
static sleep(ms) {
@@ -244,12 +224,12 @@ export class Utils {
}
/**
* Timeout wrapper for promises
* Wrap a promise with a timeout. Rejects if the promise does not settle in time.
* @template T
* @param {Promise<T>} promise - Promise to wrap
* @param {number} ms - Timeout in milliseconds
* @param {string} [message="Operation timed out"] - Error message
* @returns {Promise<T>}
* @param {Promise<T>} promise - The promise to wrap.
* @param {number} ms - Timeout in milliseconds.
* @param {string} [message="Operation timed out"] - Rejection message.
* @returns {Promise<T>} The original promise result, or rejection on timeout.
*/
static timeout(promise, ms, message = "Operation timed out") {
let timerId;
@@ -260,14 +240,14 @@ export class Utils {
}
/**
* Create progress bar string
* @param {number} current - Current position in ms or 0-1 ratio
* @param {number} [total] - Total duration in ms (if omitted, current is treated as 0-1 ratio)
* @param {number} [length=15] - Bar length in characters
* @param {string} [filledChar="━"] - Filled character
* @param {string} [emptyChar="─"] - Empty character
* @param {string} [indicator="⬤"] - Position indicator
* @returns {string} Progress bar string
* Generate a text-based progress bar.
* @param {number} current - Current progress value or ratio.
* @param {number} [total] - Total value. If omitted, current is treated as a 0–1 ratio.
* @param {number} [length=15] - Bar length in characters.
* @param {string} [filledChar="━"] - Character for the filled portion.
* @param {string} [emptyChar="─"] - Character for the empty portion.
* @param {string} [indicator="⬤"] - Character for the current position indicator.
* @returns {string} The progress bar string.
*/
static progressBar(
current,
@@ -301,10 +281,10 @@ export class Utils {
}
/**
* Format track info for display
* @param {object} track - Track object
* @param {boolean} [includeDuration=true] - Include duration
* @returns {string} Formatted string
* Format a track object into a display string with title, artist, and optional duration.
* @param {object} track - Track object with title, author, and optional duration.
* @param {boolean} [includeDuration=true] - Whether to include the duration.
* @returns {string} Formatted track info string.
*/
static formatTrackInfo(track, includeDuration = true) {
if (!track) return "Unknown Track";
@@ -325,9 +305,9 @@ export class Utils {
}
/**
* Parse YouTube-like ISO duration (PT4M13S) to milliseconds
* @param {string} isoDuration - ISO 8601 duration
* @returns {number} Milliseconds
* Parse an ISO 8601 duration string (e.g. "PT1H30M45S") into milliseconds.
* @param {string} isoDuration - The ISO duration string.
* @returns {number} Duration in milliseconds, or 0 if unparseable.
*/
static parseISODuration(isoDuration) {
if (!isoDuration || typeof isoDuration !== "string") return 0;
@@ -345,11 +325,11 @@ export class Utils {
}
/**
* Normalize text for fuzzy matching: NFKD, strip non-word chars, collapse whitespace, lowercase.
* Replaces the duplicated normalizeMatchText / normalizeTrackText functions.
* @param {string} value - Raw text to normalize
* @param {boolean} [cleanFirst=false] - Run cleanTitle() first (for worker.mjs title matching)
* @returns {string} Normalized text
* Normalize text by stripping non-alphanumeric characters, lowercasing, and trimming.
* Optionally cleans the title first using cleanTitle.
* @param {string} value - The text to normalize.
* @param {boolean} [cleanFirst=false] - Whether to run cleanTitle before normalizing.
* @returns {string} Normalized lowercase text.
*/
static normalizeText(value, cleanFirst = false) {
let text = String(value ?? "");
+34 -42
View File
@@ -1,52 +1,45 @@
/**
* @file API.mjs — API constants — FluxerList API endpoints, authentication headers, pagination defaults, and cache TTL values
* @module src.constants.API
*/
/** @module constants/API */
/**
* API.mjs — Single source of truth for all external API constants.
*
* FLUXERLIST — FluxerList vote-tracking API configuration & endpoints
* FLUXERLIST_AUTH — Authentication header format & key prefix
* FLUXERLIST_LIMITS — Pagination & rate limit defaults
*
* Edit only here; FluxerListManager.mjs and commands/vote.mjs import from this file.
* FluxerList API configuration.
* @namespace FLUXERLIST
*/
export const FLUXERLIST = {
/** Base URL for all FluxerList API v1 endpoints */
/** Base URL for the FluxerList REST API. @type {string} */
BASE_URL: "https://fluxerlist.com/api/v1",
/** FluxerList website base URL (for vote links, profiles, etc.) */
/** Public FluxerList website URL. @type {string} */
SITE_URL: "https://fluxerlist.com",
/** Available endpoint paths — append :id and query params at call time */
/** API endpoint path templates. @type {{ SERVER_VOTERS: string, BOT_VOTERS: string }} */
ENDPOINTS: {
/** GET /api/v1/servers/:id/voters — voters for a server */
SERVER_VOTERS: "/servers/:id/voters",
/** GET /api/v1/bots/:id/voters — voters for a bot */
BOT_VOTERS: "/bots/:id/voters",
},
/** Resource types supported by the API (used in command choices) */
/** Accepted resource type identifiers. @type {string[]} */
RESOURCE_TYPES: ["server", "bot"],
/** Thumbnail image for vote embeds (FluxerList branding) */
/** Thumbnail API base URL. @type {string} */
THUMBNAIL: "https://fluxerlist.com/api/v1",
};
/**
* FluxerList authentication helpers.
* @namespace FLUXERLIST_AUTH
*/
export const FLUXERLIST_AUTH = {
/** Header name for API key authentication */
/** HTTP header name for auth. @type {string} */
HEADER: "Authorization",
/** Prefix prepended to all FluxerList API keys */
/** Required API key prefix. @type {string} */
KEY_PREFIX: "fl_",
/**
* Build the Authorization header value.
* @param {string} apiKey - The raw API key (with or without the fl_ prefix)
* @returns {string} Header value in "Bearer fl_xxx" format
* Format an API key as a Bearer token, prepending the prefix if needed.
* @param {string} apiKey - Raw or prefixed API key.
* @returns {string} `Bearer fl_...` string.
*/
bearer(apiKey) {
const key = apiKey.startsWith(FLUXERLIST_AUTH.KEY_PREFIX)
@@ -56,29 +49,30 @@ export const FLUXERLIST_AUTH = {
},
};
/**
* FluxerList pagination and cache limits.
* @namespace FLUXERLIST_LIMITS
*/
export const FLUXERLIST_LIMITS = {
/** Default page number when none is specified */
/** Default page number. @type {number} */
DEFAULT_PAGE: 1,
/** Default number of results per page */
/** Default items-per-page. @type {number} */
DEFAULT_LIMIT: 50,
/** Maximum number of results per page (API enforced) */
/** Maximum allowed items-per-page. @type {number} */
MAX_LIMIT: 100,
/** Cache TTL in milliseconds for voter list responses (5 min) */
/** Cache time-to-live in milliseconds. @type {number} */
CACHE_TTL_MS: 5 * 60 * 1000,
};
/**
* Build a full FluxerList API URL by replacing :id in the endpoint path.
*
* @param {string} endpoint - One of FLUXERLIST.ENDPOINTS values (e.g. "/servers/:id/voters")
* @param {string} resourceId - The server or bot ID or slug to substitute for :id
* @param {object} [queryParams] - Optional query parameters
* @param {number} [queryParams.page] - Page number (default: 1)
* @param {number} [queryParams.limit] - Results per page, max 100 (default: 50)
* @returns {string} Full URL ready for fetch()
* Build a full FluxerList API URL by substituting `:id` in the endpoint and appending query params.
* @param {string} endpoint - Endpoint template (e.g. `"/servers/:id/voters"`).
* @param {string} resourceId - Value to substitute for `:id`.
* @param {{ page?: number, limit?: number }} [queryParams={}]
* @returns {string} Fully qualified URL.
*/
export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) {
const path = endpoint.replace(":id", encodeURIComponent(resourceId));
@@ -95,12 +89,10 @@ export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) {
}
/**
* Build the vote/profile link for a resource on FluxerList.
* Both vote and profile links share the same URL pattern.
*
* @param {"server"|"bot"} type - Resource type
* @param {string} resourceId - The server or bot ID or slug
* @returns {string} URL to the resource page on FluxerList
* Build a FluxerList vote link for a server or bot.
* @param {"server"|"bot"} type - Resource type.
* @param {string} resourceId - The server/bot ID.
* @returns {string} Absolute URL to the vote page.
*/
export function buildVoteLink(type, resourceId) {
const path = type === "server" ? "servers" : "bots";
-711
View File
@@ -1,711 +0,0 @@
/**
* @file FluxerRevoice.mjs — FluxerRevoice — voice connection adapter that bridges Fluxer gateway with LiveKit rooms, replacing revoice.js API calls
* @module src.constants.FluxerRevoice
*/
/**
* FluxerRevoice.mjs — Revoice-compatible adapter that uses the Fluxer API
*
* This module provides the same interface as revoice.js's `Revoice` class
* but uses the Fluxer gateway (via @fluxerjs/voice) to obtain LiveKit
* credentials instead of POSTing to a third-party REST API.
*
* Why this exists:
* revoice.js internally calls `POST /channels/{id}/join_call` on
* a third-party API with an `X-Bot-Token` header. A Fluxer
* bot token is NOT valid on that API, resulting in a 401.
* Fluxer's voice join flow instead uses the gateway WebSocket:
* 1. Bot sends VOICE_STATE_UPDATE opcode
* 2. Gateway responds with VOICE_STATE_UPDATE (ack)
* 3. Gateway sends VOICE_SERVER_UPDATE with { endpoint, token }
* 4. The endpoint/token are LiveKit credentials
*
* This adapter wraps @fluxerjs/voice's VoiceManager.join() and returns
* a `FluxerVoiceConnection` that is API-compatible with revoice.js's
* `VoiceConnection`, so Player.mjs and MediaPlayer work unchanged.
*
* Reference: https://fluxer.js.org/v/latest/guides/voice
*
* IMPORTANT: @livekit/rtc-node (Node.js SDK) does NOT have `room.state`.
* ✅ room.isConnected — boolean getter (true when connected)
* ✅ room.connectionState — ConnectionState enum getter
* (CONN_DISCONNECTED = 0, CONN_CONNECTED = 1, CONN_RECONNECTING = 2)
* ❌ room.state — does NOT exist (that's the browser SDK API)
*/
import { EventEmitter } from "node:events";
import { getVoiceManager } from "@fluxerjs/voice";
import { cleanId } from "../Utils.mjs";
export const ConnectionState = Object.freeze({
CONN_DISCONNECTED: 0,
CONN_CONNECTED: 1,
CONN_RECONNECTING: 2,
});
export const LKRoomEvent = Object.freeze({
ConnectionStateChanged: "connectionStateChanged",
Disconnected: "disconnected",
ParticipantConnected: "participantConnected",
ParticipantDisconnected:"participantDisconnected",
});
import { logger } from "./Logger.mjs";
/**
* LiveKit log filter — intercepts LiveKit SDK noise without monkey-patching
* console.log or process.stdout globally. Applied per-room by setting
* the room's logger to a filtered version.
*/
const LIVEKIT_LOG_PREFIXES = ["[voice LiveKitRtc]", "lk-rtc"];
const LIVEKIT_NOISY_PATTERNS = [
"Room reconnecting",
"Room reconnected",
"Room disconnected",
"emitting disconnect",
"emitting reconnecting",
"emitting reconnected",
"Connect callback received",
"signal reconnecting",
"signal reconnected",
"resume requested",
"restart requested",
];
let _liveKitLogInstalled = false;
function isLiveKitLogMessage(...args) {
if (args.length === 1 && typeof args[0] === "string") {
if (args[0].startsWith("{")) {
try {
const parsed = JSON.parse(args[0]);
if (parsed.name === "lk-rtc") return true;
} catch (e) { logger.warn("[FluxerRevoice] Error parsing livekit args:", e?.message); }
}
if (LIVEKIT_LOG_PREFIXES.some(p => args[0].includes(p))) return true;
if (LIVEKIT_NOISY_PATTERNS.some(p => args[0].includes(p))) return true;
}
return false;
}
/**
* Install a permanent console.log/info filter that suppresses LiveKit SDK noise.
* Called once on FluxerRevoice construction. Unlike withSuppressedLiveKitLogs
* (which is scoped to a callback), this persists for the lifetime of the process.
*/
function installLiveKitLogFilter() {
if (_liveKitLogInstalled) return;
_liveKitLogInstalled = true;
const origLog = console.log;
const origInfo = console.info;
const filteredLog = function (...args) {
if (isLiveKitLogMessage(...args)) return;
return origLog.apply(console, args);
};
const filteredInfo = function (...args) {
if (isLiveKitLogMessage(...args)) return;
return origInfo.apply(console, args);
};
console.log = filteredLog;
console.info = filteredInfo;
}
/**
* Temporarily suppress LiveKit SDK log noise during room setup.
* Unlike the old global monkey-patch, this is scoped to a callback
* and restores the original console.log when done.
*/
function withSuppressedLiveKitLogs(fn) {
const origLog = console.log;
console.log = function (...args) {
if (isLiveKitLogMessage(...args)) return;
origLog.apply(console, args);
};
try {
return fn();
} finally {
console.log = origLog;
}
}
/** Helper: returns a human-readable label for a ConnectionState value */
function stateLabel(cs) {
if (cs === ConnectionState.CONN_CONNECTED) return "CONN_CONNECTED";
if (cs === ConnectionState.CONN_DISCONNECTED) return "CONN_DISCONNECTED";
if (cs === ConnectionState.CONN_RECONNECTING) return "CONN_RECONNECTING";
if (cs === 1) return "CONN_CONNECTED(1)";
if (cs === 0) return "CONN_DISCONNECTED(0)";
if (cs === 2) return "CONN_RECONNECTING(2)";
return String(cs);
}
/**
* A voice connection that wraps a LiveKit Room obtained via the Fluxer
* gateway. Exposes the same interface as revoice.js's VoiceConnection:
*
* .room — LiveKit Room
* .channelId — the voice channel ID
* .connected — boolean (getter, reads from room.isConnected)
* .users — array (minimal; real tracking is via observedVoiceUsers)
* .disconnect() — tear down the LiveKit connection
* .leave() — alias for disconnect()
* Events: "disconnect", "error", "autoleave"
*/
export class FluxerVoiceConnection extends EventEmitter {
/** @type {any} LiveKit Room instance from @fluxerjs/voice */
room = null;
channelId = null;
_voice = null;
_connected = false;
_users = [];
_destroyed = false;
_nativeConn = null;
/**
* Users currently in this voice channel.
* Derived from the parent FluxerRevoice's unified users map (single source of truth).
* This prevents the old divergence bug where the array and Map could get out of sync.
*/
get users() {
return this._users;
}
set users(val) {
this._users = Array.isArray(val) ? val : [];
}
/**
* @param {string} channelId Voice channel ID this connection is bound to
* @param {FluxerRevoice} voice Parent FluxerRevoice instance that owns the join queue and users map
* @param {Object} [opts={}] Connection options
* @param {any} [opts.room] LiveKit Room instance, if already available at construction time
*/
constructor(channelId, voice, opts = {}) {
super();
this.channelId = channelId;
this._voice = voice;
this.room = opts.room ?? null;
this._nativeConn = opts.nativeConnection ?? null;
this._connected = !!(this.room && this.room.isConnected);
}
/**
* Whether this connection is currently alive.
* Reads from the LiveKit Room's `isConnected` boolean getter,
* which is the correct API in @livekit/rtc-node (Node.js SDK).
*/
get connected() {
if (this._destroyed) return false;
if (this.room) return this.room.isConnected;
return this._connected;
}
set connected(val) {
this._connected = !!val;
}
/**
* Disconnect from the voice channel.
* Tries the @fluxerjs/voice native disconnect first, then falls back
* to closing the LiveKit Room directly.
*/
async disconnect() {
if (this._destroyed) return;
if (this._voice && this.channelId) {
this._voice.markIntentionalDisconnect(this.channelId);
const guildId = this._voice._resolveGuildForChannel?.(this.channelId) ?? null;
this._voice._leaveGateway?.(this.channelId, guildId);
}
this._destroyed = true;
this._connected = false;
if (this.room) {
try {
await this.room.disconnect();
} catch (e) {
logger.warn("[FluxerVoiceConnection] Room disconnect error:", e?.message);
}
}
if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
try {
await this._nativeConn.disconnect();
} catch (e) {
logger.warn("[FluxerVoiceConnection] Native disconnect error:", e?.message);
}
}
this.emit("disconnect");
this.removeAllListeners();
}
/**
* Leave — alias for disconnect (matches revoice.js VoiceConnection API).
*/
async leave() {
return this.disconnect();
}
}
/**
* Revoice-compatible class that uses the Fluxer gateway for voice joins.
*
* Usage (drop-in for `new Revoice(token)`):
*
*
* this.revoice = new Revoice(config.token);
*
*
* this.revoice = new FluxerRevoice(client);
*/
export class FluxerRevoice extends EventEmitter {
/** @type {import("@fluxerjs/core").Client} */
client = null;
connections = new Map();
users = new Map();
/** @type {Map<string, Promise>} */
_guildJoinQueue = new Map();
/** @type {Promise} Global join serializer — only one join at a time across all guilds */
_globalJoinQueue = Promise.resolve();
/** @type {number} Minimum delay between ANY two joins (ms), even across guilds.
* This delay runs AFTER the previous join completes and BEFORE the next
* one starts, giving the Fluxer gateway time to clean up the previous
* voice session. */
_globalJoinDelay = 1500;
/** @type {Set<string>} Channel IDs where disconnect is expected (bot-initiated) */
_intentionalDisconnects = new Set();
/** @type {Map<string, NodeJS.Timeout>} Per-channel timeout tokens for intentional disconnect marks */
_intentionalDisconnectTokens = new Map();
/** @type {FluxerRevoice|null} Singleton instance */
static _instance = null;
/**
* Get or create the singleton FluxerRevoice instance.
* @param {import("@fluxerjs/core").Client} client
* @returns {FluxerRevoice}
*/
static getInstance(client) {
if (!FluxerRevoice._instance) {
FluxerRevoice._instance = new FluxerRevoice(client);
}
return FluxerRevoice._instance;
}
/**
* @param {import("@fluxerjs/core").Client} client Fluxer client used to resolve channels/guilds and send gateway leave signals
*/
constructor(client) {
super();
if (FluxerRevoice._instance && FluxerRevoice._instance !== this) {
logger.warn(
`[FluxerRevoice] Duplicate instance detected! Use FluxerRevoice.getInstance().`
);
}
if (!client) throw new Error("FluxerRevoice requires a Fluxer client instance");
this.client = client;
if (!FluxerRevoice._instance) FluxerRevoice._instance = this;
installLiveKitLogFilter();
logger.player("[FluxerRevoice] Instance created with Fluxer client.");
}
/**
* Mark a channel as expecting an intentional disconnect so the
* LKRoomEvent.Disconnected handler can log it correctly.
* @param {string} channelId
*/
markIntentionalDisconnect(channelId) {
const key = String(channelId);
this._intentionalDisconnects.add(key);
const prev = this._intentionalDisconnectTokens.get(key);
if (prev) clearTimeout(prev);
this._intentionalDisconnectTokens.set(key, setTimeout(() => {
this._intentionalDisconnects.delete(key);
this._intentionalDisconnectTokens.delete(key);
}, 10_000));
const cleanChannelId = cleanId(key);
if (this.client?._remix?.intentionalLeaves && !this.client._remix.intentionalLeaves.has(cleanChannelId)) {
this.client._remix.intentionalLeaves.set(cleanChannelId, setTimeout(() => {
this.client._remix.intentionalLeaves.delete(cleanChannelId);
}, 10_000));
}
}
/**
* Send a channel-specific leave signal to the Fluxer gateway so it
* knows the bot is no longer in the given channel. Without this, the
* gateway may think the bot is still connected and won't send a fresh
* VOICE_SERVER_UPDATE on the next VoiceManager.join() call, causing the
* rejoin to hang or fail.
*
* IMPORTANT: Only uses channel-specific leave (vm.leaveChannel).
* Guild-level leave (vm.leave / vm.updateVoiceState with null channel)
* disconnects ALL voice channels in that guild, which is catastrophic
* for multi-voice setups where the bot is in multiple channels with
* 24/7 enabled. If vm.leaveChannel is unavailable, the gateway leave
* is skipped entirely rather than risk disconnecting other channels.
*
* @param {string} channelId — The channel ID to leave
* @param {string} [guildId] — Unused, kept for API compatibility
*/
_leaveGateway(channelId, guildId = null) {
try {
const vm = getVoiceManager(this.client);
if (!vm) return;
if (typeof vm.leaveChannel === "function") {
try {
vm.leaveChannel(channelId);
logger.player(`[FluxerRevoice] Sent channel-specific gateway leave via vm.leaveChannel() for channel ${channelId}`);
return;
} catch (e) {
logger.warn(`[FluxerRevoice] vm.leaveChannel() failed for channel ${channelId}: ${e?.message}`);
}
}
logger.warn(
`[FluxerRevoice] No channel-specific leave API available for channel ${channelId}. ` +
`Skipping gateway leave to avoid disconnecting other voice channels in the guild.`
);
} catch (e) {
logger.warn(`[FluxerRevoice] Gateway leave signal failed for ${channelId}: ${e?.message}`);
}
}
/**
* Resolve the guild ID for a given channel ID from the client cache.
* @param {string} channelId
* @returns {string|null}
*/
_resolveGuildForChannel(channelId) {
try {
const ch = this.client.channels?.get?.(channelId);
return ch?.guildId ?? ch?.guild?.id ?? null;
} catch (_) {
return null;
}
}
/**
* Fully tear down a stale FluxerVoiceConnection: disconnect the native
* @fluxerjs/voice connection, close the LiveKit room, remove from the
* connections map, and send a gateway leave signal.
*
* @param {string} channelId
* @param {FluxerVoiceConnection} existing
*/
async _destroyStaleConnection(channelId, existing) {
this.connections.delete(channelId);
this.markIntentionalDisconnect(channelId);
const staleGuildId = this._resolveGuildForChannel(channelId);
this._leaveGateway(channelId, staleGuildId);
if (existing.room) {
try {
await existing.room.disconnect();
} catch (e) {
logger.warn("[FluxerRevoice] Stale room disconnect error:", e?.message);
}
}
if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") {
try {
await existing._nativeConn.disconnect();
} catch (e) {
logger.warn(`[FluxerRevoice] Stale native disconnect error for ${channelId}: ${e?.message}`);
}
}
existing._destroyed = true;
existing._connected = false;
try { existing.removeAllListeners(); } catch (e) { logger.warn("[FluxerRevoice] Error removing listeners:", e?.message); }
}
/**
* Join a voice channel using the Fluxer gateway.
*
* This sends a VOICE_STATE_UPDATE through the Fluxer gateway, receives
* VOICE_SERVER_UPDATE with LiveKit credentials, then connects to the
* LiveKit room — the same flow @fluxerjs/voice uses internally.
*
* @param {string} channelId — The voice channel ID to join
* @param {boolean} [_leaveIfEmpty=false] — Not used (compatibility param)
* @returns {Promise<FluxerVoiceConnection>}
*/
async join(channelId, _leaveIfEmpty = false) {
const joinOperation = async () => {
await new Promise(r => setTimeout(r, this._globalJoinDelay));
return await this._joinInternal(channelId, _leaveIfEmpty);
};
const prevQueue = this._globalJoinQueue;
const ourResult = prevQueue.then(() => joinOperation());
this._globalJoinQueue = ourResult.catch((err) => {
logger.warn("[FluxerRevoice] Previous join in queue failed:", err?.message ?? err);
});
return await ourResult;
}
/**
* Internal join implementation — called by join() through the global queue.
* Do NOT call this directly; always use join() to ensure serialization.
*
* @param {string} channelId
* @param {boolean} _leaveIfEmpty
* @returns {Promise<FluxerVoiceConnection>}
*/
async _joinInternal(channelId, _leaveIfEmpty = false) {
let guildId = null;
try {
const ch = this.client.channels?.get?.(channelId);
guildId = ch?.guildId ?? ch?.guild?.id ?? null;
} catch (e) {
logger.debug("[FluxerRevoice] Could not resolve guild for channel:", e?.message);
}
if (this.connections.has(channelId)) {
const existing = this.connections.get(channelId);
if (existing && !existing._destroyed && existing.room && existing.room.isConnected) {
logger.player(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`);
return existing;
}
logger.player(
`[FluxerRevoice] Stale connection for ${channelId} ` +
`(isConnected: ${existing?.room?.isConnected ?? false}, ` +
`destroyed: ${existing?._destroyed ?? true}) — cleaning up and rejoining`
);
await this._destroyStaleConnection(channelId, existing);
}
logger.player(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`);
let channel = this.client.channels?.get?.(channelId);
if (!channel) {
try {
channel = await this.client.channels.fetch(channelId);
} catch (e) {
throw new Error(`Could not fetch channel ${channelId}: ${e.message}`);
}
}
if (!channel) {
throw new Error(`Channel not found: ${channelId}`);
}
const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null;
const vm = getVoiceManager(this.client);
if (!vm) {
throw new Error(`Fluxer voice join failed for ${channelId}: VoiceManager not available — call getVoiceManager(client) before login`);
}
let nativeConnection;
try {
nativeConnection = await vm.join(channel);
} catch (e) {
throw new Error(`Fluxer voice join failed for ${channelId}: ${e.message}`);
}
if (!nativeConnection) {
throw new Error(`Fluxer voice join returned null for ${channelId}`);
}
logger.player(`[FluxerRevoice] Gateway join successful for ${channelId}`);
let room = null;
if (nativeConnection.room) {
room = nativeConnection.room;
logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
}
if (room && typeof room.setLogger === "function") {
try {
room.setLogger({
debug: () => {},
info: () => {},
warn: (...args) => { if (!isLiveKitLogMessage(...args)) logger.warn("[LiveKit]", ...args); },
error: (...args) => logger.error("[LiveKit]", ...args),
});
} catch (e) { logger.warn("[FluxerRevoice] Error creating LiveKit logger adapter:", e?.message); }
}
if (!room) {
try { await nativeConnection.disconnect(); } catch (e) {
logger.warn("[FluxerRevoice] Cleanup disconnect error:", e?.message);
}
throw new Error(
`Fluxer voice connection for ${channelId} does not expose a LiveKit Room. ` +
`Music playback requires a LiveKit-based voice server.`
);
}
const maxWait = 10_000;
const startTime = Date.now();
if (!room.isConnected) {
let eventResolved = false;
const statePromise = new Promise((resolve) => {
const handler = (cs) => {
if (eventResolved) return;
if (cs === ConnectionState.CONN_CONNECTED || cs === 1) {
eventResolved = true;
room.off(LKRoomEvent.ConnectionStateChanged, handler);
resolve();
} else if (cs === ConnectionState.CONN_DISCONNECTED || cs === 0) {
eventResolved = true;
room.off(LKRoomEvent.ConnectionStateChanged, handler);
resolve();
}
};
room.on(LKRoomEvent.ConnectionStateChanged, handler);
});
while (!room.isConnected && (Date.now() - startTime) < maxWait) {
await Promise.race([
statePromise,
new Promise(r => setTimeout(r, 200)),
]);
if (room.isConnected) break;
const cs = room.connectionState;
if (cs === ConnectionState.CONN_DISCONNECTED || cs === 0) break;
}
}
const finalConnected = room.isConnected;
const finalCS = room.connectionState;
if (!finalConnected && (finalCS === ConnectionState.CONN_DISCONNECTED || finalCS === 0)) {
try { await nativeConnection.disconnect(); } catch (e) {
logger.warn("[FluxerRevoice] Cleanup disconnect error:", e?.message);
}
throw new Error(`LiveKit room in disconnected state: ${stateLabel(finalCS)}`);
}
logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
const connection = withSuppressedLiveKitLogs(() => {
const conn = new FluxerVoiceConnection(channelId, this, {
room,
nativeConnection,
});
room.on(LKRoomEvent.ConnectionStateChanged, (cs) => {
if (cs === ConnectionState.CONN_RECONNECTING || cs === 2) {
logger.player(`[FluxerRevoice] Room reconnecting for channel ${channelId}`);
} else if (cs === ConnectionState.CONN_CONNECTED || cs === 1) {
if (conn._destroyed) return;
conn._connected = true;
logger.player(`[FluxerRevoice] Room (re)connected for channel ${channelId}`);
}
});
room.on(LKRoomEvent.Disconnected, (reason) => {
if (conn._destroyed) return;
const isIntentional = this._intentionalDisconnects.has(String(channelId));
const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected");
logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}`);
conn._connected = false;
conn._destroyed = true;
this.connections.delete(channelId);
if (!isIntentional) {
this._leaveGateway(channelId, channelGuildId);
if (nativeConnection && typeof nativeConnection.disconnect === "function") {
try { nativeConnection.disconnect(); } catch (e) {
logger.warn("[FluxerRevoice] Native disconnect error:", e?.message);
}
}
}
if (conn.listenerCount("disconnect") > 0) {
conn.emit("disconnect");
}
});
room.on(LKRoomEvent.ParticipantConnected, (participant) => {
const userId = participant?.identity ?? participant?.sid;
if (userId) {
const uKey = `${channelId}:${userId}`;
this.users.set(uKey, { id: userId, connectedTo: channelId });
conn._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
conn.emit("userjoin", userId);
}
});
room.on(LKRoomEvent.ParticipantDisconnected, (participant) => {
const userId = participant?.identity ?? participant?.sid;
if (userId) {
const uKey = `${channelId}:${userId}`;
this.users.delete(uKey);
conn._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
conn.emit("userleave", userId);
}
});
/*
* Handle the VoiceManager's serverLeave event, which fires when
* the Fluxer/LiveKit server terminates the session server-side.
* Without this handler the bot never learns the session is dead,
* leading to "validate request timed out" on the next join attempt.
*
* Reference: https://fluxer.js.org/v/latest/guides/voice
* "If using LiveKit, the server may emit serverLeave.
* Listen and reconnect if needed."
*/
if (nativeConnection && typeof nativeConnection.on === "function") {
nativeConnection.on("serverLeave", () => {
if (conn._destroyed) return;
logger.player(`[FluxerRevoice] serverLeave received for channel ${channelId} — cleaning up`);
conn._connected = false;
conn._destroyed = true;
this.connections.delete(channelId);
this._leaveGateway(channelId, channelGuildId);
if (room) {
try { room.disconnect().catch(() => {}); } catch (_) { /* already gone */ }
}
if (conn.listenerCount("disconnect") > 0) {
conn.emit("disconnect");
}
});
}
this.connections.set(channelId, conn);
if (_leaveIfEmpty) {
conn.on("userleave", () => {
const remoteCount = room.remoteParticipants?.size ?? 0;
if (remoteCount === 0) {
logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`);
conn.emit("autoleave");
this.connections.delete(channelId);
}
});
}
return conn;
});
return connection;
}
/**
* Delete a connection from the map (called during player leave/cleanup).
* @param {string} channelId
*/
deleteConnection(channelId) {
this.connections.delete(channelId);
}
}
+25 -58
View File
@@ -1,72 +1,39 @@
/** @module constants/Helpers247 */
/**
* @file Helpers247.mjs — Helpers247 — per-channel 24/7 mode management (on/auto/off) with guild-wide backward compatibility
* @module src.constants.Helpers247
* Simplified 24/7 helpers — single mode (on/off), no per-channel modes.
* get247ChannelMode is used by Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, leave.mjs.
* remove247ChannelMode and set247ChannelMode are kept as no-ops for backward compat
* (original files in the zip still import them).
*/
/**
* Shared 24/7 mode helpers.
*
* The per-channel mode map (`stay_247_modes`) stores each channel's 24/7 mode
* independently so a guild can have channel A on "on" and channel B on "auto".
*
* Format in settings:
* stay_247_modes: { "1483577390731942416": "on", "1478011355626209606": "auto" }
*
* For backward compatibility, `stay_247_mode` (guild-wide string) is still
* written when any channel is updated. All reads go through
* `get247ChannelMode()` which prefers the per-channel entry and falls back
* to the guild-wide value.
*/
/**
* Get the 24/7 mode for a specific channel.
*
* @param {{ get: (key: string) => any }} set ServerSettings instance
* @param {string} channelId Clean (digits-only) channel ID
* @returns {"on"|"auto"|"off"}
* Check if a channel has 24/7 enabled.
* @param {object} set - ServerSettings instance
* @param {string} channelId
* @returns {"on"|"off"}
*/
export function get247ChannelMode(set, channelId) {
if (!set?.get) return "off";
const modes = set.get("stay_247_modes");
if (modes && typeof modes === "object" && !Array.isArray(modes)) {
const perChannel = modes[channelId];
if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel;
}
const guildMode = set.get("stay_247_mode") ?? "off";
return guildMode;
const raw = set.get("stay_247");
if (!raw || raw === "none") return "off";
const channels = Array.isArray(raw)
? raw.map(id => String(id).trim()).filter(Boolean)
: [String(raw).trim()];
return channels.includes(channelId) ? "on" : "off";
}
/**
* Set the 24/7 mode for a specific channel.
*
* @param {{ get: (key: string) => any, set: (key: string, value: any) => void }} set
* @param {string} channelId Clean (digits-only) channel ID
* @param {"on"|"auto"|"off"} mode
*/
export function set247ChannelMode(set, channelId, mode) {
let modes = set.get("stay_247_modes");
if (!modes || typeof modes !== "object" || Array.isArray(modes)) modes = {};
modes[channelId] = mode;
set.set("stay_247_modes", modes);
set.set("stay_247_mode", mode);
}
/**
* Remove a channel from the per-channel modes map.
*
* @param {{ get: (key: string) => any, set: (key: string, value: any) => void }} set
* @param {string} channelId Clean channel ID
* @param {Set<string>} currentChannels Current set of all 247 channels for this guild
* No-op: per-channel modes removed. Kept for backward compatibility.
* Original GatewayHandler.mjs and index.mjs still import this.
*/
export function remove247ChannelMode(set, channelId, currentChannels) {
let modes = set.get("stay_247_modes");
if (!modes || typeof modes !== "object" || Array.isArray(modes)) return;
delete modes[channelId];
set.set("stay_247_modes", modes);
if (!currentChannels || currentChannels.size === 0) {
set.set("stay_247_mode", "off");
} else {
const firstChannel = [...currentChannels][0];
set.set("stay_247_mode", modes[firstChannel] ?? "auto");
// No-op: modes no longer exist, stay_247 array is managed directly.
}
/**
* No-op: per-channel modes removed. Kept for backward compatibility.
*/
export function set247ChannelMode(set, channelId, mode) {
// No-op: modes no longer exist.
}
+42 -51
View File
@@ -1,53 +1,46 @@
/**
* @file Locale.mjs — Locale — i18n system loading JSON locale files with per-guild language settings and template variable interpolation
* @module src.constants.Locale
*/
/** @module constants/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");
/**
* Lightweight i18n locale loader.
*
* Loads all JSON files from storage/locales/bot/ at startup and provides
* a `t(guildId, key, replacements?)` translation function.
*
* Usage in commands (where `this` is the Remix bot instance):
* this.t(msg, "responses.play.noResults")
* this.t(msg, "responses.clear.cleared", { count: 5 })
* 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 {
constructor() {
/** @type {Map<string, Object>} locale code → parsed JSON */
this.locales = new Map();
/** @type {Map<string, Object>} guildId → locale JSON (resolved & cached) */
this._resolved = new Map();
/** Default fallback locale */
this.defaultLocale = "en";
/** settingsMgr reference — set after construction via bind() */
this.settingsMgr = null;
/** getPrefix callback — set by CommandHandler so prefix logic lives in one place */
this._getPrefixFn = null;
/** Maximum guild locale cache size */
this._maxResolvedCache = 5000;
/**
* @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 translate() can look up per-guild locale settings.
* @param {object} settingsMgr - RemoteSettingsManager instance
* 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 locale JSON files from the locales directory.
* Call once at startup after config is available.
* Load all `.json` locale files from the locales directory.
* Clears any previously loaded data and the resolved-cache.
*/
load() {
this.locales.clear();
@@ -81,8 +74,7 @@ export class Locale {
}
/**
* Return the set of available locale codes.
* Useful for validation (e.g. the settings command).
* Return the set of loaded locale codes.
* @returns {Set<string>}
*/
availableLocales() {
@@ -90,12 +82,11 @@ export class Locale {
}
/**
* Resolve the locale data for a guild.
* Checks the per-guild "locale" setting from the DB, falls back to English.
* Results are cached per guildId.
*
* 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}
* @returns {object} The locale data object.
*/
_getLocaleData(guildId) {
if (!guildId) return this.locales.get(this.defaultLocale) ?? {};
@@ -126,8 +117,8 @@ export class Locale {
}
/**
* Clear the resolved locale cache (call when locale setting changes).
* @param {string} [guildId] - Specific guild to invalidate, or omit for all.
* Invalidate the resolved-cache for a specific guild or all guilds.
* @param {string} [guildId] - Omit to clear the entire cache.
*/
invalidateCache(guildId) {
if (guildId) {
@@ -138,17 +129,16 @@ export class Locale {
}
/**
* Set the prefix resolver callback. Called once by CommandHandler at startup
* so that all prefix resolution goes through CommandHandler.getPrefix().
* @param {(guildId: string) => string} fn
* Register a custom prefix resolver function.
* @param {function(string): string} fn - Receives `guildId`, returns the prefix string.
*/
setPrefixResolver(fn) {
this._getPrefixFn = fn;
}
/**
* Get the per-guild prefix. Delegates to CommandHandler.getPrefix() when
* available, otherwise falls back to a direct settings lookup.
* Resolve the command prefix for a guild.
* @private
* @param {string} guildId
* @returns {string}
*/
@@ -165,9 +155,10 @@ export class Locale {
}
/**
* Look up a dotted key in a nested object.
* @param {Object} obj
* @param {string} key e.g. "responses.play.noResults"
* 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) {
@@ -181,12 +172,12 @@ export class Locale {
}
/**
* Translate a key with optional {{placeholder}} replacements.
*
* 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 Dotted key, e.g. "responses.play.noResults"
* @param {Object} [replacements={}] e.g. { count: 5, channel: "#general" }
* @returns {string} Translated string, or the key itself if not found
* @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);
+94 -36
View File
@@ -1,87 +1,145 @@
/**
* @file Logger.mjs — Logger — categorized logging (info, warn, error, voice, player) with timestamp formatting and module prefixes
* @module src.constants.Logger
*/
/**
* Logger — configurable console output for Fluxer.
*
* Categories (all under config.logging):
* enabled — master switch; false silences everything except errors and warns
* warn — when enabled=false, set true to keep showing warnings (default: hidden)
* player — voice connect/disconnect, stream start, volume restore
* inactivity — alone-check, inactivity timer, human detection
* aloneCheck — periodic alone-check scan logs (separate from inactivity)
* voice247 — 24/7 rejoin, auto-save channel, intentional leave skip
* voiceState — raw VOICE_STATE_UPDATE events (human join/leave detection)
* voice — checkVoiceChannels debug logs
* mediaplayer — MediaPlayer publish, LiveKit room state, connection recovery
* commands — command load, module load, error IDs
* guild — GuildCreate / GuildDelete lifecycle
* recovery — session save/restore on reboot
* settings — settings DB load, remote update errors
* worker — worker URL cleaning, result logging
* moonlink — moonlink node events
* dashboard — dashboard request handler, player updates
* redis — Redis pub/sub connection events
* errors — always on; console.error calls (cannot be disabled)
*/
/** @module constants/Logger */
/** @private */
let _config = null;
/**
* Call once at startup with the loaded config object.
* @param {object} config
* 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);
}
/**
* Shared cooldown state for WebSocket transport error logging.
* Prevents the same WS close event from being logged by multiple
* listeners (shard handler, GatewayHandler, MoonlinkManager).
* All three share this timestamp so only the first logs.
* Cooldown state for WebSocket error logging to avoid spam.
* @type {{ lastLogged: number, COOLDOWN_MS: number }}
*/
export const _wsErrorCooldown = { lastLogged: 0, COOLDOWN_MS: 15_000 };
/**
* 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) {
console.error(`[${ts()}] ${tag}`, ...args);
},
/**
* 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) { console.warn(`[${ts()}] ${tag}`, ...args); return; }
if (_config.enabled === false && _config.warn !== true) return;
console.warn(`[${ts()}] ${tag}`, ...args);
},
/**
* 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); },
worker(...args) { if (isEnabled("worker")) console.log(`[${ts()}]`, ...args); },
moonlink(...args) { if (isEnabled("moonlink")) 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); },
};
+13 -21
View File
@@ -1,45 +1,37 @@
/**
* @file UI.mjs — UI constants — shared color values, emoji arrays, timeout durations, and volume limits used across commands and embeds
* @module src.constants.UI
*/
/** @module constants/UI */
/**
* UI.mjs — Shared UI constants used across commands and embeds.
*
* Centralises emoji arrays, timeout values, and colour constants
* that were previously duplicated across many command files.
*/
/** Error embed colour — used everywhere instead of hardcoding "#ff0000". */
/** Hex color string for error embeds. @type {string} */
export const ERROR_COLOR = "#ff0000";
/** Warning/highlight colour for diagnostic and debug embeds. */
/** Numeric hex color for warning embeds. @type {number} */
export const WARN_COLOR = 0xFFAA00;
/** Success colour for diagnostic embeds. */
/** Numeric hex color for success embeds. @type {number} */
export const SUCCESS_COLOR = 0x00CC66;
/** Failure/danger colour for diagnostic embeds (same as ERROR_COLOR but numeric). */
/** Numeric hex color for danger/critical embeds. @type {number} */
export const DANGER_COLOR = 0xFF4444;
/** Default timeout (ms) before removing navigation reactions from embeds. */
/** Auto-remove reaction collectors after this many ms. @type {number} */
export const EMOJI_REMOVE_TIMEOUT = 60_000;
/** Default inactivity timeout (ms) for interactive embed sessions. */
/** Session idle timeout in ms. @type {number} */
export const SESSION_TIMEOUT = 30_000;
/** Number emojis for search/radio selection menus. */
/** Number emoji map for selection menus (indices 1-10). @type {string[]} */
export const NUMBER_EMOJIS = [
"1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣",
"6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟",
];
/** Cancel emoji for selection menus. */
/** Emoji used to cancel a selection. @type {string} */
export const CANCEL_EMOJI = "❌";
/** Navigation emojis for paginated embeds. */
/** Emoji for previous-page navigation. @type {string} */
export const PREV_EMOJI = "⬅️";
/** Emoji for next-page navigation. @type {string} */
export const NEXT_EMOJI = "➡️";
/** Maximum allowed volume percentage. */
/** Maximum allowed volume value. @type {number} */
export const MAX_VOLUME = 200;
+79 -130
View File
@@ -1,78 +1,58 @@
/**
* @file VoiceStateCache.mjs — VoiceStateCache — O(1) composite-keyed LRU cache for voice state lookups with dual indexes (user→channel, channel→users)
* @module src.constants.VoiceStateCache
*/
/**
* VoiceStateCache — O(1) voice-state lookups with bounded memory.
*
* Replaces the raw `observedVoiceUsers` / `observedVoiceBots` Maps with a
* composite-keyed, indexed, LRU-evicted cache that supports:
*
* • O(1) lookup: "is anyone in channel X?" → channelMembers.get(guildId, channelId)
* • O(1) lookup: "what channel is user X in?" → userLocations.get(guildId, userId)
* • O(1) lookup: "how many humans in channel X?" → channelMembers.get(...).size
* • Bounded memory via LRU eviction (default 50 000 entries)
* • Composite keys (guildId:userId) so multi-guild users don't overwrite
* • Single update function used by both raw WS and high-level handlers
*
* Data structures:
* userLocations — Map<"guildId:userId", {channelId, guildId, userId}>
* channelMembers — Map<"guildId:channelId", Set<userId>>
* botLocations — Map<"guildId:userId", {channelId, guildId, userId}>
* botChannelMembers — Map<"guildId:channelId", Set<userId>>
* _lruOrder — String[] (most-recently-updated keys, for eviction)
*/
/** @module constants/VoiceStateCache */
import { logger } from "./Logger.mjs";
import { cleanId } from "../Utils.mjs";
/**
* VoiceStateCache class.
* LRU-backed cache mapping users (and bots) to their voice-channel locations.
* Supports O(1) lookups by guild+user or guild+channel and implements the
* Map-like interface (`get`, `set`, `delete`, `has`, `forEach`, `entries`, `keys`, `values`).
* @class
*/
export class VoiceStateCache {
/**
* @param {object} [opts]
* @param {number} [opts.maxUsers=50000] Max human entries before LRU eviction
* @param {number} [opts.maxBots=10000] Max bot entries before LRU eviction
* @param {number} [opts.maxUsers=50000] - Max cached human user entries.
* @param {number} [opts.maxBots=10000] - Max cached bot user entries.
*/
constructor(opts = {}) {
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
this.userLocations = new Map();
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
this.channelMembers = new Map();
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
this.botLocations = new Map();
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
this.botChannelMembers = new Map();
this._maxUsers = opts.maxUsers ?? 50_000;
this._maxBots = opts.maxBots ?? 10_000;
/** @type {string[]} MRU-first list of user location keys */
this._lruUserKeys = [];
/** @type {string[]} MRU-first list of bot location keys */
this._lruBotKeys = [];
}
/** Build composite key "guildId:userId" (both cleaned to digits only) */
/**
* Build a composite user key for storage.
* @param {string} guildId
* @param {string} userId
* @returns {string}
*/
static userKey(guildId, userId) {
return `${cleanId(guildId)}:${cleanId(userId)}`;
}
/** Build composite key "guildId:channelId" (both cleaned to digits only) */
/**
* Build a composite channel key for storage.
* @param {string} guildId
* @param {string} channelId
* @returns {string}
*/
static channelKey(guildId, channelId) {
return `${cleanId(guildId)}:${cleanId(channelId)}`;
}
/**
* Update voice state for a user.
*
* @param {object} params
* @param {string} params.guildId
* @param {string} params.userId
* @param {string|null} params.channelId null = user left voice
* @param {boolean} [params.isBot=false]
* Update (or remove) a user's voice-channel location in the cache.
* When `channelId` is provided the user is added; when `null`/falsy the user is removed.
* Automatically evicts LRU entries when capacity is exceeded.
* @param {{ guildId: string, userId: string, channelId: string|null, isBot?: boolean }} opts
*/
updateUser({ guildId, userId, channelId, isBot = false }) {
const cleanGuild = cleanId(guildId);
@@ -139,9 +119,7 @@ export class VoiceStateCache {
}
/**
* Check if there are any human users in a specific channel.
* O(1) via channelMembers index.
*
* Check whether any human users are cached in the given channel.
* @param {string} guildId
* @param {string} channelId
* @returns {boolean}
@@ -153,9 +131,7 @@ export class VoiceStateCache {
}
/**
* Get the number of human users in a specific channel.
* O(1) via channelMembers index.
*
* Get the count of human users cached in the given channel.
* @param {string} guildId
* @param {string} channelId
* @returns {number}
@@ -167,9 +143,7 @@ export class VoiceStateCache {
}
/**
* Get all human userIds in a specific channel.
* O(1) lookup + Set iteration.
*
* Get the array of human user IDs cached in the given channel.
* @param {string} guildId
* @param {string} channelId
* @returns {string[]}
@@ -181,9 +155,7 @@ export class VoiceStateCache {
}
/**
* Get the channelId a human user is currently in (within a specific guild).
* O(1) via userLocations index.
*
* Get the channel ID a human user is currently in, or `null`.
* @param {string} guildId
* @param {string} userId
* @returns {string|null}
@@ -195,8 +167,7 @@ export class VoiceStateCache {
}
/**
* Check if a human user is tracked in a specific guild.
*
* Check whether a human user exists in the cache for the given guild.
* @param {string} guildId
* @param {string} userId
* @returns {boolean}
@@ -206,8 +177,7 @@ export class VoiceStateCache {
}
/**
* Get user location info (channelId, guildId) for a human user.
*
* Get the full location record for a human user.
* @param {string} guildId
* @param {string} userId
* @returns {{ channelId: string, guildId: string, userId: string }|undefined}
@@ -217,8 +187,7 @@ export class VoiceStateCache {
}
/**
* Seed a user into the cache (only if not already present).
*
* Seed a user into the cache only if not already present.
* @param {string} guildId
* @param {string} userId
* @param {string} channelId
@@ -232,8 +201,7 @@ export class VoiceStateCache {
}
/**
* Remove all entries for a specific guild (used on GuildDelete).
*
* Remove all cached entries (human and bot) for a given guild.
* @param {string} guildId
*/
removeGuild(guildId) {
@@ -283,8 +251,7 @@ export class VoiceStateCache {
}
/**
* Remove a specific channel's index entries (used when a player leaves).
*
* Remove all cached entries (human and bot) for a specific channel.
* @param {string} guildId
* @param {string} channelId
*/
@@ -317,12 +284,10 @@ export class VoiceStateCache {
}
/**
* Selectively remove entries for users whose IDs appear in a given set
* (used during GuildCreate to purge stale entries being replaced).
*
* Remove specific users from a guild's cache.
* @param {string} guildId
* @param {Set<string>} userIds User IDs whose entries should be purged
* @param {boolean} [botsOnly=false] Only purge bot entries
* @param {string[]} userIds
* @param {boolean} [botsOnly=false] - If `true`, only purge bot entries.
*/
purgeUsersInGuild(guildId, userIds, botsOnly = false) {
const cleanGuild = cleanId(guildId);
@@ -353,21 +318,20 @@ export class VoiceStateCache {
}
/**
* Get the "observedVoiceUsers" size (human count).
* Backward-compat with `this.observedVoiceUsers.size`
* Number of cached human users.
* @type {number}
*/
get observedVoiceUsersSize() { return this.userLocations.size; }
/**
* Get the "observedVoiceBots" size.
* Backward-compat with `this.observedVoiceBots.size`
* Number of cached bot users.
* @type {number}
*/
get observedVoiceBotsSize() { return this.botLocations.size; }
/**
* Iterate over all human user locations.
* Yields [compositeKey, {channelId, guildId, userId}] — same shape as Map entries.
* Backward-compat with `for (const [uid, info] of this.observedVoiceUsers)`.
* Iterate over all cached human user entries as `[userId, { channelId, guildId }]` pairs.
* @yields {[string, { channelId: string, guildId: string }]}
*/
*iterateHumanUsers() {
for (const [uKey, loc] of this.userLocations) {
@@ -376,9 +340,8 @@ export class VoiceStateCache {
}
/**
* Iterate over all bot user locations.
* Yields [compositeKey, {channelId, guildId, userId}].
* Backward-compat with `for (const [uid, info] of this.observedVoiceBots)`.
* Iterate over all cached bot user entries as `[compositeKey, { channelId, guildId }]` pairs.
* @yields {[string, { channelId: string, guildId: string }]}
*/
*iterateBotUsers() {
for (const [uKey, loc] of this.botLocations) {
@@ -387,12 +350,9 @@ export class VoiceStateCache {
}
/**
* Get a human user's location by userId and guildId.
* If guildId is provided, uses O(1) composite key.
* If guildId is null, falls back to O(n) scan (legacy compat).
*
* Get the location record for a human user. If `guildId` is omitted, performs a linear scan.
* @param {string} userId
* @param {string|null} [guildId=null]
* @param {string|null} [guildId]
* @returns {{ channelId: string, guildId: string }|undefined}
*/
getHumanUser(userId, guildId = null) {
@@ -407,10 +367,9 @@ export class VoiceStateCache {
}
/**
* Set a human user's location (backward-compat with observedVoiceUsers.set).
*
* Set a human user's voice location via `updateUser`.
* @param {string} userId
* @param {{channelId: string, guildId: string}} info
* @param {{ guildId: string, channelId: string }} info
*/
setHumanUser(userId, info) {
const guildId = info.guildId;
@@ -421,10 +380,9 @@ export class VoiceStateCache {
}
/**
* Set a bot user's location (backward-compat with observedVoiceBots.set).
*
* @param {string} compositeKey "guildId:userId" composite key
* @param {{channelId: string, guildId: string}} info
* Set a bot user's voice location via `updateUser`.
* @param {string} compositeKey - `guildId:userId` composite key.
* @param {{ guildId: string, channelId: string }} info
*/
setBotUser(compositeKey, info) {
const guildId = info.guildId;
@@ -436,11 +394,9 @@ export class VoiceStateCache {
}
/**
* Delete a human user by userId (scans all guilds if no guildId given).
* Backward-compat with observedVoiceUsers.delete(userId).
*
* Remove a human user from the cache. If `guildId` is omitted, scans all entries.
* @param {string} userId
* @param {string|null} [guildId=null]
* @param {string|null} [guildId]
*/
deleteHumanUser(userId, guildId = null) {
if (guildId) {
@@ -456,10 +412,8 @@ export class VoiceStateCache {
}
/**
* Delete a bot user by composite key.
* Backward-compat with observedVoiceBots.delete(compositeKey).
*
* @param {string} compositeKey "guildId:userId"
* Remove a bot user from the cache by its composite key.
* @param {string} compositeKey - `guildId:userId` composite key.
*/
deleteBotUser(compositeKey) {
const parts = compositeKey.split(":");
@@ -471,11 +425,9 @@ export class VoiceStateCache {
}
/**
* Check if a human user exists in the cache.
* Backward-compat with observedVoiceUsers.has(userId).
*
* Check whether a human user exists in the cache. If `guildId` is omitted, scans all entries.
* @param {string} userId
* @param {string|null} [guildId=null]
* @param {string|null} [guildId]
* @returns {boolean}
*/
hasHumanUser(userId, guildId = null) {
@@ -490,10 +442,8 @@ export class VoiceStateCache {
}
/**
* Check if a bot user exists in the cache.
* Backward-compat with observedVoiceBots.has(compositeKey).
*
* @param {string} compositeKey
* Check whether a bot user exists in the cache by composite key.
* @param {string} compositeKey - `guildId:userId` composite key.
* @returns {boolean}
*/
hasBotUser(compositeKey) {
@@ -501,8 +451,8 @@ export class VoiceStateCache {
}
/**
* Default iterator — iterates human users.
* Yields [userId, {channelId, guildId}] — same shape as old observedVoiceUsers Map.
* Implement the iterable protocol over human user entries.
* @yields {[string, { channelId: string, guildId: string }]}
*/
*[Symbol.iterator]() {
for (const [uKey, loc] of this.userLocations) {
@@ -511,15 +461,13 @@ export class VoiceStateCache {
}
/**
* Backward-compat with `observedVoiceUsers.size`.
* Number of cached human users (Map-like `.size`).
* @type {number}
*/
get size() { return this.userLocations.size; }
/**
* Backward-compat with `observedVoiceUsers.has(userId)`.
* If called with a single argument (userId), scans all guilds.
* If called with two arguments (userId, guildId), does O(1) lookup.
*
* Map-like `has` — checks if a human user is cached.
* @param {string} userId
* @param {string} [guildId]
* @returns {boolean}
@@ -536,10 +484,7 @@ export class VoiceStateCache {
}
/**
* Backward-compat with `observedVoiceUsers.get(userId)`.
* If called with a single argument (userId), returns first match across all guilds.
* If called with two arguments (userId, guildId), does O(1) lookup.
*
* Map-like `get` — retrieve a human user's location.
* @param {string} userId
* @param {string} [guildId]
* @returns {{ channelId: string, guildId: string }|undefined}
@@ -557,10 +502,9 @@ export class VoiceStateCache {
}
/**
* Backward-compat with `observedVoiceUsers.set(userId, {channelId, guildId})`.
*
* Map-like `set` — upsert a human user's location.
* @param {string} userId
* @param {{channelId: string, guildId: string}} info
* @param {{ guildId: string, channelId: string }} info
*/
set(userId, info) {
const guildId = info?.guildId;
@@ -571,8 +515,7 @@ export class VoiceStateCache {
}
/**
* Backward-compat with `observedVoiceUsers.delete(userId)`.
*
* Map-like `delete` — remove a human user. If `guildId` is omitted, removes all matching entries.
* @param {string} userId
* @param {string} [guildId]
*/
@@ -592,9 +535,8 @@ export class VoiceStateCache {
}
/**
* Backward-compat with `observedVoiceUsers.forEach(fn)`.
*
* @param {Function} fn callback(userId, info, cache)
* Map-like `forEach` — iterate over human user entries.
* @param {function(string, { channelId: string, guildId: string }, VoiceStateCache): void} fn
*/
forEach(fn) {
for (const [userId, info] of this) {
@@ -603,14 +545,16 @@ export class VoiceStateCache {
}
/**
* Backward-compat with `observedVoiceUsers.entries()`.
* Map-like `entries` iterator.
* @yields {[string, { channelId: string, guildId: string }]}
*/
*entries() {
yield* this;
}
/**
* Backward-compat with `observedVoiceUsers.keys()`.
* Map-like `keys` iterator.
* @yields {string}
*/
*keys() {
for (const [userId] of this) {
@@ -619,7 +563,8 @@ export class VoiceStateCache {
}
/**
* Backward-compat with `observedVoiceUsers.values()`.
* Map-like `values` iterator.
* @yields {{ channelId: string, guildId: string }}
*/
*values() {
for (const [, info] of this) {
@@ -627,6 +572,10 @@ export class VoiceStateCache {
}
}
/**
* Diagnostic statistics for the cache.
* @type {{ humanUsers: number, botUsers: number, humanChannels: number, botChannels: number, lruUserKeysLen: number, lruBotKeysLen: number }}
*/
get stats() {
return {
humanUsers: this.userLocations.size,
+18 -37
View File
@@ -1,26 +1,11 @@
/**
* @file VoiceStateResolver.mjs — VoiceStateResolver — unified voice state enumeration across Map/Array/Object guild voice_states with human-detection fallbacks
* @module src.constants.VoiceStateResolver
*/
/**
* VoiceStateResolver.mjs — Unified voice state enumeration.
*
* Eliminates the 12+ duplicated voice-state-iteration blocks scattered
* across Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, and Dashboard.mjs.
*
* Fluxer's guild.voice_states can be a Map, an Array, or a plain Object
* depending on the client version and cache state. This module normalises
* all three into a single iteration interface.
*/
/** @module constants/VoiceStateResolver */
import { logger } from "./Logger.mjs";
/**
* Iterate over all voice states for a guild, yielding objects with
* { userId, channelId, isBot } regardless of the underlying data structure.
*
* @param {import("@fluxerjs/core").Guild} guild
* Iterate over a guild's voice states, normalising different data shapes.
* Yields objects with `{ userId, channelId, isBot }` for each member in a voice channel.
* @param {object} guild - Discord guild object with a `voice_states` property.
* @yields {{ userId: string, channelId: string, isBot: boolean }}
*/
export function* iterateVoiceStates(guild) {
@@ -59,18 +44,16 @@ export function* iterateVoiceStates(guild) {
}
/**
* Check whether a guild's voice channel contains any non-bot users.
* Uses three fallback strategies: VoiceStateCache, guild.voice_states,
* and LiveKit remote participants.
*
* Check whether any non-bot humans are currently in a voice channel.
* Checks, in order: VoiceStateCache → ObservedVoiceUsers → guild voice_states → LiveKit participants.
* @param {object} opts
* @param {string} opts.guildId - Clean guild ID
* @param {string} opts.channelId - Clean channel ID
* @param {object} [opts.client] - Fluxer client (for guild cache)
* @param {object} [opts.voiceCache] - VoiceStateCache instance
* @param {Map} [opts.observedVoiceUsers] - Observed voice users map
* @param {object} [opts.room] - LiveKit Room (for remote participants)
* @param {string} [opts.botId] - Bot user ID (to exclude from LiveKit check)
* @param {string} opts.guildId
* @param {string} opts.channelId
* @param {object} [opts.client] - Discord client with `guilds`.
* @param {VoiceStateCache} [opts.voiceCache]
* @param {Map} [opts.observedVoiceUsers]
* @param {object} [opts.room] - LiveKit room with `remoteParticipants`.
* @param {string} [opts.botId]
* @returns {boolean}
*/
export function hasHumansInChannel({ guildId, channelId, client, voiceCache, observedVoiceUsers, room, botId }) {
@@ -128,10 +111,9 @@ export function hasHumansInChannel({ guildId, channelId, client, voiceCache, obs
}
/**
* Get all channel IDs that have at least one human user in voice.
*
* @param {import("@fluxerjs/core").Guild} guild
* @returns {Set<string>} Set of channel IDs with human users
* Get the set of channel IDs that contain at least one human user.
* @param {object} guild - Discord guild object.
* @returns {Set<string>}
*/
export function getChannelsWithHumans(guild) {
const channels = new Set();
@@ -142,9 +124,8 @@ export function getChannelsWithHumans(guild) {
}
/**
* Get all user IDs in a specific voice channel (including bots).
*
* @param {import("@fluxerjs/core").Guild} guild
* Get the list of user IDs present in a specific voice channel.
* @param {object} guild - Discord guild object.
* @param {string} channelId
* @returns {string[]}
*/
-102
View File
@@ -1,102 +0,0 @@
/**
* @file StreamMerger.mjs — StreamMerger — Transform stream that mixes multiple audio inputs through FFmpeg amix filter
* @module src.constants.audio.StreamMerger
*/
/**
* StreamMerger extends Transform to mix multiple audio streams into one
* using FFmpeg’s amix filter. Supports dynamic stream addition with
* a tree-based node structure for managing merge slots.
*/
import { logger } from "../Logger.mjs";
import ffmpeg from "ffmpeg-static";
import { Transform } from "node:stream";
import { spawn } from "node:child_process";
class StreamMerger extends Transform {
ffmpegPath = ffmpeg;
ffmpeg = null;
streamTree = [];
/**
* @param {import("node:stream").TransformOptions} streamOptions Options forwarded to the underlying Transform stream
*/
constructor(streamOptions) {
super(streamOptions);
}
_transform(chunk, _enc, cb) {
if (!this.ffmpeg) { this.push(chunk); return cb(); }
if (!this.ffmpeg.stdio?.[3]?.writable) { this.push(chunk); return cb(); }
this.ffmpeg.stdio[3].write(chunk);
cb();
}
pipe(stream) {
return super.pipe(stream);
}
setupBaseFfmpeg() {
this.ffmpeg = this.spawnFfmpeg();
this.ffmpeg.stderr.on("data", (chunk) => { logger.mediaplayer("[ffmpeg]", chunk.toString().trim()); });
this.ffmpeg.stdout.on("data", (chunk) => { this.push(chunk); });
}
spawnFfmpeg() {
const args = [
"-i", "pipe:3",
"-re", "-i", "pipe:4",
"-vn",
"-fflags", "nobuffer",
"-filter_complex", "amix=inputs=2:duration=longest",
"pipe:1",
];
return spawn(this.ffmpegPath, args, {
windowsHide: true,
stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"]
});
}
findOpenNode() {
if (this.streamTree.length === 0) {
this.streamTree.push({ process: this.ffmpeg, pipes: [4], available: true, children: [] });
return this.streamTree[0];
}
const findChild = (node) => {
if (node.available) return node;
for (const child of node.children) {
const c = findChild(child);
if (c) return c;
}
return null;
};
for (const node of this.streamTree) {
const firstChild = findChild(node);
if (firstChild) return firstChild;
}
return null;
}
addStream(s) {
if (!this.ffmpeg) this.setupBaseFfmpeg();
const open = this.findOpenNode();
if (!open) throw new Error("Impossible case detected. No free merge node found.");
const p = this.spawnFfmpeg();
const node = { process: p, pipes: [4], available: true, parent: open, children: [] };
open.children.push(node);
s.pipe(p.stdio[3]);
p.stderr.on("data", (c) => { logger.mediaplayer("[ffmpeg]", c.toString().trim()); });
/* Write initial silence to prime the ffmpeg stdin pipe (required for amix to detect the input). */
p.stdio[4].write(Buffer.alloc(1024, 0));
p.stdout.pipe(open.process.stdio[open.pipes[0]]);
const pipeNumber = open.pipes[0];
open.pipes.splice(0, 1);
if (open.pipes.length === 0) open.available = false;
p.on("exit", () => {
open.pipes.push(pipeNumber);
open.available = true;
const idx = open.children.findIndex(c => c === node);
if (idx === -1) {
logger.warn("[StreamMerger] Damaged node structure — child not found in parent on exit.");
} else {
open.children.splice(idx, 1);
}
});
}
}
export default StreamMerger;
+36 -12
View File
@@ -1,24 +1,30 @@
/**
* @file Tuna.mjs — Tuna — Voicemod Tuna API client for sound effect search and download
* @module src.constants.audio.Tuna
*/
/** @module constants/audio/Tuna */
/**
* Tuna API client for searching and downloading sound effects
* from the Voicemod Tuna service (tuna-api.voicemod.net).
*/
import pkg from "follow-redirects";
const { https } = pkg;
class Tuna {
apiKey = null;
/**
* @param {Object} auth Auth config
* @param {string} auth.key Voicemod Tuna API key
* Client for the Tuna (Voicemod) sound-effect API.
* @class
*/
class Tuna {
/** @private */ apiKey = null;
/**
* @param {{ key: string }} auth - Object containing the API key.
*/
constructor(auth) {
this.apiKey = auth.key;
}
/**
* Perform an authenticated GET request to the Tuna API.
* @private
* @async
* @param {string} path - API path (e.g. `"/v1/sounds/search"`).
* @param {Object<string, *>} [params={}] - Query-string parameters.
* @returns {Promise<object>} Parsed JSON response.
*/
get(path, params = {}) {
return new Promise((resolve, reject) => {
const qs = new URLSearchParams(params).toString();
@@ -49,6 +55,16 @@ class Tuna {
req.end();
});
}
/**
* Search for sound effects. Each result item gains a `download()` method
* that returns the OGG audio stream.
* @async
* @param {string} query - Search term.
* @param {number} [page=1]
* @param {number} [size=10]
* @returns {Promise<object>} Search results with enriched `items` array.
*/
search(query, page = 1, size = 10) {
return this.get("/v1/sounds/search", { size, page, search: query }).then(results => {
results.items = results.items.map(s => {
@@ -65,6 +81,14 @@ class Tuna {
return results;
});
}
/**
* Fetch a single sound effect by ID. The returned object gains a `download()`
* method that returns the OGG audio stream.
* @async
* @param {string} id - Sound ID.
* @returns {Promise<object>} Sound object with `download()` method.
*/
getSound(id) {
return this.get("/v1/sounds/" + id).then(sound => {
const oggPath = sound.oggPath;
+220
View File
@@ -0,0 +1,220 @@
/** @module src/constants/audio/WebMOpusMuxer @description Minimal streaming WebM/Matroska muxer for Opus packets. Produces streams consumable by prism-media's WebmDemuxer (what @fluxerjs/voice uses internally) — no FFmpeg required. */
import { Transform } from "node:stream";
/** @type {number} @description Opus frame duration in milliseconds (20ms = 960 samples @ 48kHz). */
export const OPUS_FRAME_MS = 20;
/** @type {number} @description Blocks per cluster before a new Cluster element is started. */
const BLOCKS_PER_CLUSTER = 250;
/** @type {number} @description Force a cluster flush when buffered blocks exceed this size. */
const CLUSTER_FLUSH_BYTES = 64 * 1024;
/**
* Encode a Matroska variable-length size integer (finite size).
* @param {number} value - Size to encode (must be >= 0).
* @returns {Buffer}
*/
function encodeSizeVint(value) {
let length = 1;
while (value > 2 ** (7 * length) - 1 && length < 8) length++;
const buf = Buffer.alloc(length);
for (let i = length - 1; i >= 0; i--) {
buf[i] = value & 0xff;
value = Math.floor(value / 256);
}
buf[0] |= 1 << (8 - length);
return buf;
}
/**
* Build a single EBML element from an ID hex string and a payload Buffer.
* @param {string} idHex - EBML element ID as hex (e.g. "1a45dfa3").
* @param {Buffer} payload
* @returns {Buffer}
*/
function element(idHex, payload) {
return Buffer.concat([Buffer.from(idHex, "hex"), encodeSizeVint(payload.length), payload]);
}
/**
* Encode an unsigned integer EBML payload using minimal bytes.
* @param {number} value
* @returns {Buffer}
*/
function uintPayload(value) {
let bytes = 1;
while (value >= 2 ** (8 * bytes)) bytes++;
const buf = Buffer.alloc(bytes);
buf.writeUIntBE(value, 0, bytes);
return buf;
}
/**
* Build the OpusHead codec private data (Matroska-embedded OpusHead).
* @param {number} sampleRate - Input sample rate (48000).
* @param {number} channels - Channel count (2).
* @returns {Buffer}
*/
export function buildOpusHead(sampleRate, channels) {
const buf = Buffer.alloc(19);
buf.write("OpusHead", 0, "ascii");
buf.writeUInt8(1, 8); // version
buf.writeUInt8(channels, 9);
buf.writeUInt16LE(0, 10); // pre-skip (we encode ourselves; no trimming)
buf.writeUInt32LE(sampleRate, 12);
buf.writeInt16LE(0, 16); // output gain
buf.writeUInt8(0, 18); // mapping family (mono/stereo)
return buf;
}
/**
* Build the WebM stream header: EBML + Segment start + Info + Tracks.
* The Segment element uses an unknown (streaming) size so clusters can be
* appended indefinitely.
* @param {number} sampleRate
* @param {number} channels
* @returns {Buffer}
*/
function buildHeader(sampleRate, channels) {
const ebml = element("1a45dfa3", Buffer.concat([
element("4286", uintPayload(1)), // EBMLVersion
element("42f7", uintPayload(1)), // EBMLReadVersion
element("42f2", uintPayload(4)), // EBMLMaxIDLength
element("42f3", uintPayload(8)), // EBMLMaxSizeLength
element("4282", Buffer.from("webm", "ascii")), // DocType
element("4287", uintPayload(2)), // DocTypeVersion
element("4285", uintPayload(2)), // DocTypeReadVersion
]));
const info = element("1549a966", Buffer.concat([
element("2ad7b1", uintPayload(1000000)), // TimecodeScale (1ms)
element("4d80", Buffer.from("fluxer-remix", "ascii")),// MuxingApp
element("5741", Buffer.from("fluxer-remix", "ascii")),// WritingApp
]));
const floatBuf = Buffer.alloc(4);
floatBuf.writeFloatBE(sampleRate, 0);
const audio = element("e1", Buffer.concat([
element("b5", floatBuf), // SamplingFrequency
element("9f", uintPayload(channels)), // Channels
]));
const trackEntry = element("ae", Buffer.concat([
element("d7", uintPayload(1)), // TrackNumber (must be 1 — demuxer masks data[0] & 0xF)
element("73c5", uintPayload(1)), // TrackUID
element("83", uintPayload(2)), // TrackType: audio
element("86", Buffer.from("A_OPUS", "ascii")), // CodecID
element("63a2", buildOpusHead(sampleRate, channels)), // CodecPrivate: OpusHead
audio,
]));
const tracks = element("1654ae6b", trackEntry);
// Streaming Segment size: a huge finite vint (0x01 + 7x0xFF = 2^56-1). The
// canonical all-0xFF unknown-size marker is misparsed by prism-media's
// vintLength (it reads 0xFF as a 1-byte vint), so we use this equivalent form.
const segmentStart = Buffer.concat([
Buffer.from("18538067", "hex"),
Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
]);
return Buffer.concat([ebml, segmentStart, info, tracks]);
}
/**
* Build a SimpleBlock element for one Opus packet.
* @param {Buffer} packet - Raw Opus packet.
* @param {number} relTimeMs - Cluster-relative timestamp in ms.
* @returns {Buffer}
*/
function buildSimpleBlock(packet, relTimeMs) {
const clamped = Math.max(-32768, Math.min(32767, relTimeMs));
const header = Buffer.from([0x81, (clamped >> 8) & 0xff, clamped & 0xff, 0x80]);
return element("a3", Buffer.concat([header, packet]));
}
/**
* Streaming WebM muxer: consumes Opus packets (object mode) and emits a
* WebM/Opus byte stream compatible with prism-media's WebmDemuxer — the exact
* format @fluxerjs/voice's VoiceConnection.play() expects as input.
* @extends {Transform}
*/
export class WebMOpusMuxer extends Transform {
/**
* @param {object} [options]
* @param {number} [options.sampleRate=48000]
* @param {number} [options.channels=2]
*/
constructor(options = {}) {
super({ writableObjectMode: true });
this._sampleRate = options.sampleRate ?? 48000;
this._channels = options.channels ?? 2;
this._header = buildHeader(this._sampleRate, this._channels);
this._blocks = [];
this._blocksBytes = 0;
this._blockIndex = 0;
this._clusterIndex = 0;
this._headerSent = false;
}
/**
* Feed one Opus packet into the current cluster.
* @param {Buffer} packet
*/
_addBlock(packet) {
if (!this._headerSent) {
this.push(this._header);
this._headerSent = true;
}
const relTime = (this._blockIndex % BLOCKS_PER_CLUSTER) * OPUS_FRAME_MS;
const block = buildSimpleBlock(packet, relTime);
this._blocks.push(block);
this._blocksBytes += block.length;
this._blockIndex++;
if (this._blocks.length >= BLOCKS_PER_CLUSTER || this._blocksBytes >= CLUSTER_FLUSH_BYTES) {
this._flushCluster();
}
}
/** Emit the current cluster as a complete EBML element. */
_flushCluster() {
if (this._blocks.length === 0) return;
const timecode = element("e7", uintPayload(this._clusterIndex * BLOCKS_PER_CLUSTER * OPUS_FRAME_MS));
const cluster = element("1f43b675", Buffer.concat([timecode, ...this._blocks]));
this._blocks = [];
this._blocksBytes = 0;
this._clusterIndex++;
this.push(cluster);
}
/**
* @param {Buffer} packet
* @param {string} _encoding
* @param {Function} callback
* @protected
*/
_transform(packet, _encoding, callback) {
try {
if (Buffer.isBuffer(packet) && packet.length > 0) {
this._addBlock(packet);
}
callback();
} catch (err) {
callback(err);
}
}
/**
* @param {Function} callback
* @protected
*/
_final(callback) {
try {
this._flushCluster();
callback();
} catch (err) {
callback(err);
}
}
}
+17 -15
View File
@@ -1,18 +1,11 @@
/**
* @file providers.mjs — Music provider definitions — source names, emoji icons, choice lists, and inline provider parsing for search commands
* @module src.constants.providers
*/
/** @module constants/providers */
/**
* providers.mjs — Single source of truth for all provider data.
*
* PROVIDERS — full map: { prefix, label } — used by worker.mjs for search
* PROVIDER_NAMES — derived label-only map — used by Player.mjs for display
* PROVIDER_CHOICES — ordered list of valid keys — used by command option builders
*
* Edit only here; worker.mjs and Player.mjs import from this file.
* Map of provider shorthand keys to their Lavalink search prefix and display label.
* Both short aliases (e.g. `scld`) and full names (e.g. `soundcloud`) map to the same
* prefix/label pair.
* @type {Object<string, { prefix: string, label: string }>}
*/
export const PROVIDERS = {
yt: { prefix: "ytsearch", label: "YouTube" },
ytm: { prefix: "ytmsearch", label: "YouTube Music" },
@@ -71,11 +64,18 @@ export const PROVIDERS = {
ftts: { prefix: "ftts", label: "Flowery TTS" },
};
/** Label-only map — convenience alias for display use (e.g. Player.mjs). */
/**
* Shorthand-to-label lookup derived from {@link PROVIDERS}.
* @type {Object<string, string>}
*/
export const PROVIDER_NAMES = Object.fromEntries(
Object.entries(PROVIDERS).map(([k, v]) => [k, v.label])
);
/**
* Complete list of accepted provider keys for command choices.
* @type {string[]}
*/
export const PROVIDER_CHOICES = [
"ytm", "yt", "scld", "sc",
"sp", "spotify",
@@ -105,8 +105,10 @@ export const PROVIDER_CHOICES = [
];
/**
* Parse an inline provider prefix from a query string (e.g. "sp: song name").
* @param {string} raw
* Parse an inline provider prefix from raw query text (e.g. `"yt: never gonna give you up"`).
* If the prefix is recognised, splits into provider key and remaining query;
* otherwise returns the full string as the query with `provider: null`.
* @param {string} raw - The raw user input string.
* @returns {{ provider: string|null, query: string }}
*/
export function parseInlineProvider(raw) {
+95 -76
View File
@@ -1,6 +1,8 @@
/**
* @file Dashboard.mjs — Dashboard — web dashboard backend with player status API, guild listing, and bot statistics endpoints
* @module src.dashboard.Dashboard
* @module dashboard/Dashboard
* @description Web dashboard backend controller. Manages Redis pub/sub communication
* with the dashboard frontend, handles remote function calls (join, play, pause, etc.),
* and provides static data-conversion helpers for Discord entities.
*/
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
@@ -13,18 +15,23 @@ import { logger } from "../constants/Logger.mjs";
import { iterateVoiceStates } from "../constants/VoiceStateResolver.mjs";
/**
* Dashboard class.
* @class
* @description Orchestrates the web dashboard: wires up Redis request/response handling,
* converts Discord data for the frontend, and exposes remote control functions.
*/
export class Dashboard {
/** @type {boolean} Whether the dashboard is enabled. */
enabled = false;
/** @type {number} Login code expiry time in milliseconds (default 6 hours). */
expiryTime = 1000 * 60 * 60 * 6;
/**
* @param {Remix} remix
* @param {Object} opts
* @param {boolean} opts.enabled Whether the Dashboard is enabled and connections should be attempted
* @param {Object} opts.redis Connection options passed directly to redis createClient
* @param {Object} [opts.mysql] MySQL connection config for login code verification
* Create a new Dashboard instance.
* @param {object} remix - The main bot (Remix) instance.
* @param {object} opts - Dashboard options.
* @param {boolean} [opts.enabled] - Whether the dashboard is enabled.
* @param {object} [opts.redis] - Redis connection options.
* @param {object} [opts.mysql] - MySQL connection options for the dashboard database.
*/
constructor(remix, opts) {
this.enabled = opts?.enabled;
@@ -129,8 +136,8 @@ export class Dashboard {
/**
* Set the bot ID for multi-bot Redis namespace isolation.
* Updates the Redis platform string so each bot uses its own channel namespace.
* Set the bot ID for the Redis platform prefix.
* @param {string} botId - The bot's Discord user ID.
*/
setBotId(botId) {
if (!this.enabled || !this.redis) return;
@@ -139,10 +146,13 @@ export class Dashboard {
/**
* @param {Object} params
* @param {string} params.func
* @param {any} params.data
* @returns {Promise<any>}
* Execute a remote dashboard function (e.g. join, pause, volume).
* @async
* @param {object} params - Function call parameters.
* @param {string} params.func - The function name to execute.
* @param {object} [params.data] - Additional data for the function.
* @param {string} [params.data.user] - The Discord user ID making the request.
* @returns {Promise<object>} Result object with `message` or `error`.
*/
async runFunction(params) {
let user;
@@ -367,10 +377,12 @@ export class Dashboard {
/**
* Check if a user is a bot owner, or is in the same voice channel as the player.
* @param {import("@fluxerjs/core").User|null} user
* @param {Player} player
* @returns {string|null} Error message, or null if authorized
* Verify that the given user is allowed to control the given player.
* Bot owners bypass the check; otherwise the user must be in the same voice channel.
* @private
* @param {object} user - The Discord user attempting to control the player.
* @param {object} player - The Player instance to control.
* @returns {string|null} An error message if unauthorized, or null if authorized.
*/
_authorizePlayerControl(user, player) {
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null;
@@ -400,10 +412,13 @@ export class Dashboard {
}
/**
* Verify the user has permission to perform an action in the target guild.
* @param {import("@fluxerjs/core").User} user
* @param {string} guildId
* @returns {Promise<string|null>} Error message, or null if authorized
* Verify that the given user is a member of the specified guild.
* Bot owners bypass the check.
* @private
* @async
* @param {object} user - The Discord user to verify.
* @param {string} guildId - The guild ID to check membership in.
* @returns {Promise<string|null>} An error message if not a member, or null if authorized.
*/
async _authorizeUserInGuild(user, guildId) {
if (this.remix.handler?.owners?.includes?.(user.id)) return null;
@@ -420,9 +435,10 @@ export class Dashboard {
}
/**
* Find a player by its channel ID (key in playerMap)
* @param {string} id
* @returns {Player|null}
* Look up a player by channel ID, guild ID, or player ID.
* @private
* @param {string} id - Channel ID, guild ID, or player ID.
* @returns {object|null} The matching Player instance, or null.
*/
_getPlayerById(id) {
return this.remix.players.playerMap.get(id)
@@ -434,7 +450,10 @@ export class Dashboard {
/**
* @param {import("@fluxerjs/core").User} user
* Convert a Discord user object to a dashboard-safe plain object.
* @static
* @param {object} user - The Discord user.
* @returns {{ id: string, username: string, displayName: string, avatar: { url: string } }}
*/
static convertUser(user) {
let avatarUrl = "";
@@ -459,7 +478,10 @@ export class Dashboard {
}
/**
* @param {Object} vid Track object stored in the fluxer Queue
* Convert a video/track object to a dashboard-safe plain object.
* @static
* @param {object} vid - The video/track object from the player queue.
* @returns {object|null} Sanitised video data, or null if input is falsy.
*/
static convertVideo(vid) {
if (!vid) return null;
@@ -483,7 +505,11 @@ export class Dashboard {
}
/**
* @param {import("@fluxerjs/core").GuildChannel} channel
* Convert a Discord channel to a dashboard-safe plain object, including
* voice participant info for voice channels.
* @static
* @param {object} channel - The Discord channel.
* @returns {object} Sanitised channel data.
*/
static convertChannel(channel) {
const type = channel.type ?? 0;
@@ -524,7 +550,10 @@ export class Dashboard {
}
/**
* @param {import("@fluxerjs/core").Guild} guild
* Convert a Discord guild (server) to a dashboard-safe plain object with channels.
* @static
* @param {object} guild - The Discord guild.
* @returns {object} Sanitised server data including channels and voice channels.
*/
static convertServer(guild) {
const channelStore = guild.channels;
@@ -558,8 +587,10 @@ export class Dashboard {
}
/**
* Lightweight server summary for player payloads.
* @param {import("@fluxerjs/core").Guild} guild
* Convert a Discord guild to a lightweight summary object (no channels).
* @static
* @param {object} guild - The Discord guild.
* @returns {{ name: string, id: string, icon: string|null, description: string|null, ownerId: string|null }}
*/
static convertServerSummary(guild) {
let iconUrl = null;
@@ -578,7 +609,11 @@ export class Dashboard {
}
/**
* @param {Player} player
* Convert a Player instance to a dashboard-safe serialisable object.
* Includes queue, users, channel, and server info.
* @static
* @param {object} player - The Player instance.
* @returns {object} Sanitised player data.
*/
static convertPlayer(player) {
const channelId = player._channelId;
@@ -648,7 +683,10 @@ export class Dashboard {
}
/**
* @param {Option} opt
* Convert a command option to a dashboard-safe plain object.
* @static
* @param {object} opt - The command option.
* @returns {object} Sanitised option data.
*/
static convertOption(opt) {
return {
@@ -664,8 +702,11 @@ export class Dashboard {
}
/**
* @param {CommandBuilder} com
* @param {CommandHandler} commands
* Convert a command (and its subcommands/options) to a dashboard-safe plain object.
* @static
* @param {object} com - The command object.
* @param {object} commands - The CommandHandler instance (for usage generation).
* @returns {object} Sanitised command data.
*/
static convertCommand(com, commands) {
return {
@@ -684,23 +725,14 @@ export class Dashboard {
}
/** @private */
_playerUpdateTimers = new Map();
/**
* Global player update (broadcast to all dashboard listeners on {platform}:players).
*
* Used for two purposes:
* 1. Lifecycle events: { type: "init" } / { type: "close" } — the backend
* PlayerManager uses these to add/remove Player objects.
* 2. Full state broadcast: any other type — the full serialised player is
* included so dashboard frontends can update their UI.
*
* Debounced: rapid successive calls for the same player are coalesced
* into a single publish every 500ms.
*
* @param {Object} details Must include a `type` field (e.g. "init", "close",
* "startplay", "stopplay", etc.) and may include a `data` field.
* @param {Player} player
* Broadcast a player state update to the dashboard via Redis.
* Debounces non-init/close updates by 500ms.
* @param {object} details - The update payload (e.g. `{ type: 'song' }`).
* @param {object} player - The Player instance that changed.
*/
playerUpdate(details, player) {
if (!this.enabled) return;
@@ -738,20 +770,9 @@ export class Dashboard {
}
/**
* Per-player channel update (sent to {platform}:player_{channelId}).
*
* The backend PlayerManager.setupEvents() expects messages in the format:
* { type: "<eventType>", data: <payload> }
*
* This method accepts details in that standard format directly.
*
* @param {Object} details Must include `type` and optionally `data`.
* Examples:
* { type: "startplay", data: convertVideo(song) }
* { type: "pause", data: { elapsedTime: 12345 } }
* { type: "queue", data: serialisedQueueEvent }
* { type: "join", data: userId }
* @param {Player} player
* Send a lightweight update to the player-specific Redis channel.
* @param {object} details - The update payload.
* @param {object} player - The Player instance.
*/
updatePlayer(details, player) {
if (!this.enabled) return;
@@ -760,9 +781,9 @@ export class Dashboard {
}
/**
* Global user update (sent to {platform}:users).
* @param {Object} details
* @param {import("@fluxerjs/core").User} user
* Broadcast a user update to the global users Redis channel.
* @param {object} details - The update payload.
* @param {object} user - The Discord user.
*/
userUpdate(details, user) {
if (!this.enabled) return;
@@ -774,9 +795,9 @@ export class Dashboard {
}
/**
* Per-user channel update (sent to {platform}:user_{userId}).
* @param {Object} details
* @param {import("@fluxerjs/core").User} user
* Send a lightweight update to the user-specific Redis channel.
* @param {object} details - The update payload.
* @param {object} user - The Discord user.
*/
updateUser(details, user) {
if (!this.enabled) return;
@@ -786,13 +807,11 @@ export class Dashboard {
/**
* Verify a login code submitted by a user via DM.
* The backend stores the code in MySQL; this method compares the supplied
* code against the stored (bcrypt-hashed) value.
*
* @param {string} user User ID
* @param {string} code Plain-text code supplied by the user
* @returns {Promise<string|null>} null on success, error message on failure
* Verify a dashboard login code for a user.
* @async
* @param {string} user - The Discord user ID.
* @param {string} code - The login code to verify.
* @returns {Promise<string|null>} An error message if verification fails, or null on success.
*/
async confirmLogin(user, code) {
if (!this.enabled) return "Dashboard not enabled.";
+26 -19
View File
@@ -1,6 +1,7 @@
/**
* @file DatabaseManager.mjs — DatabaseManager — SQLite database manager for the web dashboard's persistent storage
* @module src.dashboard.DatabaseManager
* @module dashboard/DatabaseManager
* @description MySQL connection pool wrapper for the dashboard. Provides parameterised
* query execution and bcrypt hashing utilities for login code management.
*/
import { compare, genSalt, hash } from "bcryptjs";
@@ -8,12 +9,14 @@ import { createPool } from "mysql2/promise";
import { logger } from "../constants/Logger.mjs";
/**
* DatabaseManager — MySQL pool for dashboard login codes and API tokens.
* Adapted for use with the Fluxer bot.
* @class
* @description Wraps a mysql2 connection pool with convenience methods for
* parameterised queries and bcrypt hash operations.
*/
export class DatabaseManager {
/**
* @param {import("mysql2/promise").PoolOptions} config
* Create a new DatabaseManager.
* @param {object} config - mysql2 pool configuration (host, user, password, database, etc.).
*/
constructor(config) {
this.db = createPool({
@@ -26,19 +29,21 @@ export class DatabaseManager {
}
/**
* Execute a raw SQL query.
* @param {string} query
* @returns {Promise<[import("mysql2/promise").QueryResult, import("mysql2/promise").FieldPacket[]]>}
* Execute a raw SQL query (no parameter binding).
* @async
* @param {string} query - The SQL query string.
* @returns {Promise<Array>} The query result rows and fields.
*/
async query(query) {
return this.db.query(query);
}
/**
* Execute a parameterized SQL query.
* @param {string} query
* @param {any[]} [data]
* @returns {Promise<import("mysql2/promise").QueryResult>}
* Execute a parameterised SQL query.
* @async
* @param {string} query - The SQL query with `?` placeholders.
* @param {Array} data - The values to bind.
* @returns {Promise<Array>} The result rows.
*/
async execute(query, data) {
const [res, _fields] = await this.db.execute(query, data);
@@ -46,9 +51,10 @@ export class DatabaseManager {
}
/**
* Hash a plaintext string using bcrypt.
* @param {string} plain
* @returns {Promise<string>}
* Generate a bcrypt hash of the given plaintext.
* @async
* @param {string} plain - The plaintext string.
* @returns {Promise<string>} The hashed string.
*/
async hash(plain) {
const salt = await genSalt(10);
@@ -57,16 +63,17 @@ export class DatabaseManager {
/**
* Compare a plaintext string against a bcrypt hash.
* @param {string} plain
* @param {string} hashed
* @returns {Promise<boolean>}
* @async
* @param {string} plain - The plaintext string.
* @param {string} hashed - The bcrypt hash.
* @returns {Promise<boolean>} True if the plaintext matches the hash.
*/
async compareHash(plain, hashed) {
return await compare(plain, hashed);
}
/**
* Gracefully close the connection pool.
* Close the underlying MySQL connection pool.
* @returns {Promise<void>}
*/
close() {
+34 -32
View File
@@ -1,15 +1,19 @@
/**
* @file RedisHandler.mjs — RedisHandler — Redis pub/sub handler for cross-process dashboard state synchronization
* @module src.dashboard.RedisHandler
* @module dashboard/RedisHandler
* @description Redis pub/sub handler for the dashboard. Maintains a main publisher client
* and a subscriber client. Receives JSON requests on the "request" channel,
* dispatches them to a user-supplied handler, and publishes results on "response".
*/
import { createClient } from "redis";
import { logger } from "../constants/Logger.mjs";
/**
* Default retry strategy: exponential backoff starting at 500ms, max 5s, max 20 retries.
* @param {Object} options
* @returns {number} Delay in ms before next retry, or an Error to stop retrying
* Default reconnection strategy for Redis sockets.
* @param {object} options - Reconnection options from the Redis client.
* @param {number} options.totalRetryTime - Cumulative retry time so far.
* @param {number} options.attempt - Current retry attempt number.
* @returns {number|Error} Delay in ms before next retry, or an Error to stop retrying.
*/
const DEFAULT_RETRY_STRATEGY = (options) => {
if (options.totalRetryTime > 60_000) {
@@ -19,22 +23,25 @@ const DEFAULT_RETRY_STRATEGY = (options) => {
};
/**
* RedisHandler class.
* @class
* @description Manages dual Redis connections (publisher + subscriber) for real-time
* dashboard communication via pub/sub.
*/
export class RedisHandler {
/** @type {string} Platform prefix used for Redis channel names. */
platform = "fluxer";
/** @type {import("redis").RedisClientType|null} */
/** @type {import('redis').RedisClientType|null} The main (publisher) Redis client. */
client = null;
/** @type {import("redis").RedisClientType|null} */
/** @type {import('redis').RedisClientType|null} The subscriber Redis client. */
subscriber = null;
/** Whether the handler has been explicitly destroyed */
/** @private @type {boolean} Whether the handler has been destroyed. */
_destroyed = false;
/**
* @param {Object} opts
* @param {import("redis").RedisClientOptions} opts Redis client options
* @param {string} [opts.platform] Platform identifier for channel namespacing
* Create a new RedisHandler and immediately begin connecting.
* @param {object} [opts={}] - Redis connection options (passed to `createClient`).
* @param {string} [opts.platform] - Platform prefix for channels.
*/
constructor(opts = {}) {
this.platform = opts.platform ?? "fluxer";
@@ -61,8 +68,10 @@ export class RedisHandler {
}
/**
* Connect both publisher and subscriber with reconnection support.
* Wrapped in a method so it can be called once from the constructor.
* Connect both the publisher and subscriber clients, then subscribe
* to the "request" and "info" channels and start the ping interval.
* @private
* @async
*/
async _connect() {
try {
@@ -113,12 +122,8 @@ export class RedisHandler {
}
/**
* Send the "connected" announcement to the backend.
* Delayed by 5 seconds so the bot has time to initialise players,
* recovery manager, and Moonlink before the backend starts sending
* requests like fetchPlayers. Without this delay the backend's
* initChannels() fires before the bot's playerMap is populated,
* causing "Redis request timed out" errors and a retry loop.
* Send a "connected" info message to the dashboard after a 5-second debounce.
* @returns {void}
*/
readyMessage() {
if (this._destroyed) return;
@@ -135,9 +140,10 @@ export class RedisHandler {
/**
* Publish a message to a Redis channel.
* @param {string} channel
* @param {string} message
* @returns {Promise<number>} Number of subscribers that received the message
* No-op if the handler is destroyed or the client is not ready.
* @param {string} channel - The Redis channel to publish to.
* @param {string} message - The message string to send.
* @returns {Promise<number>} Number of subscribers that received the message.
*/
send(channel, message) {
if (this._destroyed || !this.client?.isReady) return Promise.resolve(0);
@@ -147,24 +153,20 @@ export class RedisHandler {
});
}
/**
* @callback RequestCallback
* @param {Object} data
* @param {string} data.type
* @returns {Promise<Object>}
*/
/** @type {Function|null} The current request handler function. */
handleRequest;
/**
* @param {RequestCallback} handler
* Set the handler function invoked for incoming "request" payloads.
* @param {Function} handler - Async function `(data) => result`.
*/
setRequestHandler(handler) {
this.handleRequest = handler;
}
/**
* Gracefully close both Redis connections.
* Should be called on process shutdown to avoid abrupt connection drops.
* Gracefully close both Redis connections and stop all internal timers.
* @async
* @returns {Promise<void>}
*/
async destroy() {
+9 -4
View File
@@ -1,14 +1,19 @@
/**
* @file probe.mjs — Health probe — monitors NodeLink and LiveKit endpoint availability
* @module src.probe
*/
/** @module src/probe @description Audio probing utilities using ffprobe to extract metadata from media files/streams. */
import ffprobe from "ffprobe-static";
import { spawn } from "node:child_process";
import { logger } from "./constants/Logger.mjs";
/** @type {number} @description Maximum time in milliseconds to wait for ffprobe to complete. */
const PROBE_TIMEOUT_MS = 15_000;
/**
* Probe a media file or stream URL for metadata using ffprobe.
* Extracts album, artist, title, and duration.
* @param {string} file - File path or stream URL to probe.
* @returns {Promise<{album: string, artist: string, title: string, duration: number}>} Parsed metadata.
* @throws {Error} If ffprobe times out, fails to spawn, or produces unparseable output.
*/
export default function probe(file) {
return new Promise((res, rej) => {
const args = [
-757
View File
@@ -1,757 +0,0 @@
/**
* @file worker.mjs — Worker thread module — handles track search jobs via NodeLink REST API with provider fallback chains
* @module src.worker
*/
/**
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
*/
import { workerData, parentPort } from "worker_threads";
import { EventEmitter } from "events";
import http from "http";
import https from "https";
import { Utils } from "./Utils.mjs";
import { PROVIDERS } from "./constants/providers.mjs";
import { logger } from "./constants/Logger.mjs";
const NL_DEFAULT_PASSWORD = "youshallnotpass";
const nl = workerData?.data?.nodelink ?? {};
const NL_HOST = nl.host ?? "localhost";
const NL_PORT = nl.port ?? 3000;
const NL_PASSWORD = nl.password ?? NL_DEFAULT_PASSWORD;
const NL_SESSION_ID = nl.sessionId ?? null;
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
const _sanitizeRegexes = (() => {
const r = [];
if (NL_HOST && NL_HOST !== "localhost") {
const eh = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
r.push({ re: new RegExp(`https?://${eh}(:\\d+)?[^\\s"']*`, "gi"), sub: "[internal]" });
r.push({ re: new RegExp(`${eh}:${NL_PORT}`, "g"), sub: "[internal]" });
}
r.push({ re: new RegExp(`https?://localhost:${NL_PORT}[^\\s"']*`, "gi"), sub: "[internal]" });
if (NL_PASSWORD && NL_PASSWORD !== NL_DEFAULT_PASSWORD) {
const ep = NL_PASSWORD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
r.push({ re: new RegExp(ep, "g"), sub: "[redacted]" });
}
return r;
})();
function sanitizeError(msg) {
if (!msg) return msg;
let s = String(msg);
for (const { re, sub } of _sanitizeRegexes) {
re.lastIndex = 0;
s = s.replace(re, sub);
}
return s;
}
/**
* HTTP GET to NodeLink. Rejects on non-2xx so callers never mistake
* an auth/server error for a legitimate empty-result response.
* @param {string} path
* @param {string} password
* @param {string|null} sessionId
* @param {string|null} guildId
* @returns {Promise<object>}
*/
function nlRequest(path, password, sessionId, guildId) {
return new Promise((resolve, reject) => {
const isHttps = NL_PORT === 443;
const mod = isHttps ? https : http;
const protocol = isHttps ? "https" : "http";
const req = mod.get(
`${protocol}://${NL_HOST}:${NL_PORT}${path}`,
{
headers: {
Authorization: password,
...(sessionId ? { "Session-Id": sessionId } : {}),
...(guildId ? { "Guild-Id": guildId } : {}),
},
},
(res) => {
const chunks = [];
res.on("data", d => chunks.push(d));
res.on("end", () => {
const body = Buffer.concat(chunks).toString();
if (res.statusCode < 200 || res.statusCode >= 300) {
let detail = "";
try {
const parsed = JSON.parse(body);
detail = parsed.error ?? parsed.message ?? "";
} catch (_) {
detail = body.slice(0, 200);
}
return reject(new Error(`NodeLink HTTP ${res.statusCode}${detail ? ": " + detail : ""}`));
}
try {
resolve(JSON.parse(body));
} catch (e) {
reject(new Error(`NodeLink JSON parse error: ${e.message}`));
}
});
},
);
req.on("error", reject);
req.setTimeout(30_000, () => {
req.destroy();
reject(new Error("NodeLink request timeout"));
});
});
}
/** Worker-thread-level NodeLink GET (uses global credentials). */
function nlGet(path) {
return nlRequest(path, NL_PASSWORD, NL_SESSION_ID, NL_GUILD_ID);
}
/**
* Call NodeLink /v4/loadtracks.
* @param {string} identifier
* @param {function} getFn
* @returns {Promise<object>}
*/
async function loadTracks(identifier, getFn = nlGet) {
return getFn(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
}
/**
* Convert a NodeLink track object to the internal video format.
* @param {object} track
* @returns {object|null}
*/
function trackToVideo(track) {
if (!track || typeof track !== "object") return null;
const info = track.info ?? {};
const ms = info.length ?? 0;
return {
videoId: info.identifier ?? "",
encoded: track.encoded ?? "",
sourceName: info.sourceName ?? "unknown",
title: Utils.cleanTitle(info.title ?? "Unknown"),
url: info.uri ?? `https://www.youtube.com/watch?v=${info.identifier}`,
thumbnail: info.artworkUrl ?? null,
spotifyUrl: null,
duration: {
timestamp: Utils.prettifyMS(ms),
seconds: Math.floor(ms / 1000),
},
author: {
name: info.author ?? "Unknown",
url: info.uri ?? null,
},
artists: null,
};
}
function normalizeMatchText(value) {
return Utils.normalizeText(value, true);
}
function tokenizeMatchText(value) {
return normalizeMatchText(value).split(" ").filter(Boolean);
}
/**
* Extract an array of track objects from any NodeLink loadTracks response,
* regardless of loadType. Returns [] for empty/error/unknown responses.
* @param {object} data - NodeLink /v4/loadtracks response
* @returns {object[]}
*/
function extractTracks(data) {
if (!data || !data.loadType) return [];
switch (data.loadType) {
case "track":
return data.data ? [data.data] : [];
case "search":
return Array.isArray(data.data) ? data.data : [];
case "playlist":
return data.data?.tracks ?? [];
case "empty":
case "error":
return [];
default:
return [];
}
}
const TYPE_MODIFIERS = ["track", "playlist", "album", "artist", "channel", "user"];
class YTUtils extends EventEmitter {
constructor() {
super();
}
isValidUrl(str) { return Utils.isValidUrl(str); }
_prefix(p) { return PROVIDERS[p]?.prefix ?? "ytmsearch"; }
_providerLabel(p) { return PROVIDERS[p]?.label ?? "YouTube Music"; }
_isAudioPreferredProvider(p) { return p === "ytm"; }
/**
* Build all identifier variants to try for a given provider + query.
* Different NodeLink source plugins accept different identifier formats.
* Some handle `<prefix>:<query>`, others only handle `<prefix>:track:<query>`.
* We return both variants so the caller can try each in order.
* @param {string} provider
* @param {string} query
* @returns {string[]}
*/
_buildIdentifiers(provider, query) {
const prefix = this._prefix(provider);
const colonIdx = query.indexOf(":");
if (colonIdx !== -1) {
const maybeType = query.slice(0, colonIdx).toLowerCase();
if (TYPE_MODIFIERS.includes(maybeType)) {
return [`${prefix}:${query}`];
}
}
return [
`${prefix}:${query}`,
`${prefix}:track:${query}`,
];
}
_buildRequestContext(query, trackMeta = null) {
let requestedTitle = trackMeta?.name ?? trackMeta?.title ?? query;
let requestedArtist = trackMeta?.artist ?? "";
if (!trackMeta) {
const dashMatch = String(query).match(/^(.+?)\s+[-–—]\s+(.+)$/);
if (dashMatch) {
requestedArtist = dashMatch[1].trim();
requestedTitle = dashMatch[2].trim();
}
}
return {
normalizedTitle: normalizeMatchText(requestedTitle),
normalizedArtist: normalizeMatchText(requestedArtist),
queryTokens: tokenizeMatchText(query),
titleTokens: tokenizeMatchText(requestedTitle),
artistTokens: tokenizeMatchText(requestedArtist),
};
}
/**
* Clean YouTube Radio/Mix URLs to extract just the video ID.
* YouTube Radio URLs (list=RD...) often cause metadata mismatches.
* @param {string} url
* @returns {string}
*/
_cleanYouTubeUrl(url) {
try {
const urlObj = new URL(url);
const list = urlObj.searchParams.get("list");
if (list && list.startsWith("RD")) {
const videoId = urlObj.searchParams.get("v");
if (videoId) {
logger.worker(`[Worker] Cleaned YouTube Radio URL, extracted video: ${videoId}`);
return `https://www.youtube.com/watch?v=${videoId}`;
}
}
if (urlObj.searchParams.has("start_radio")) {
urlObj.searchParams.delete("start_radio");
return urlObj.toString();
}
return url;
} catch (_) {
return url;
}
}
_isPlayableTrack(track) {
const info = track?.info ?? {};
const uri = info.uri || "";
if (uri.includes("/channel/")) return false;
if (uri.includes("/c/") && !uri.includes("/watch")) return false;
if (uri.includes("/playlist?")) return false;
if (uri.includes("/user/")) return false;
if (info.isStream) return false;
if (!info.length || info.length <= 0) return false;
return true;
}
_scoreTrackForAudio(track, provider = "ytm", request = null) {
if (!this._isPlayableTrack(track)) return Number.NEGATIVE_INFINITY;
const info = track?.info ?? {};
const title = String(info.title ?? "").toLowerCase();
const author = String(info.author ?? "").toLowerCase();
const uri = String(info.uri ?? "").toLowerCase();
const source = String(info.sourceName ?? "").toLowerCase();
const text = `${title} ${author} ${uri} ${source}`;
let score = 0;
const positiveHints = [
/\bofficial audio\b/,
/\baudio\b/,
/\bsong\b/,
/\bprovided to youtube by\b/,
/\btopic\b/,
/\bart track\b/,
/\blyrics?\b/,
];
const negativeHints = [
/\bofficial music video\b/,
/\bmusic video\b/,
/\bofficial video\b/,
/\bvideo\b/,
/\bmv\b/,
/\bvisuali[sz]er\b/,
/\blive\b/,
/\bperformance\b/,
/\bconcert\b/,
/\bkaraoke\b/,
/\bsped up\b/,
/\bslowed\b/,
/\breverb\b/,
/\bnightcore\b/,
/\b8d\b/,
/\bremix\b/,
/\bcover\b/,
/\bfan cam\b/,
];
if (this._isAudioPreferredProvider(provider)) {
for (const re of positiveHints) {
if (re.test(text)) score += 3;
}
for (const re of negativeHints) {
if (re.test(text)) score -= 4;
}
if (author.endsWith(" - topic") || author.includes("topic")) score += 4;
if (uri.includes("music.youtube.com")) score += 3;
if (source === "youtube music") score += 3;
}
if (request) {
const normalizedTitle = normalizeMatchText(info.title);
const normalizedAuthor = normalizeMatchText(info.author);
const fullText = `${normalizedTitle} ${normalizedAuthor} ${normalizeMatchText(info.uri)} ${normalizeMatchText(info.sourceName)}`.trim();
if (request.normalizedTitle) {
if (normalizedTitle === request.normalizedTitle) score += 30;
else if (normalizedTitle.includes(request.normalizedTitle)) score += 18;
else score -= 6;
}
if (request.normalizedArtist) {
if (normalizedAuthor === request.normalizedArtist) score += 20;
else if (normalizedAuthor.includes(request.normalizedArtist)) score += 12;
else score -= 8;
}
if (request.queryTokens.length) {
const overlap = request.queryTokens.filter(token => fullText.includes(token)).length;
score += overlap * 2;
}
if (request.titleTokens.length) {
const titleOverlap = request.titleTokens.filter(token => normalizedTitle.includes(token)).length;
score += titleOverlap * 4;
}
if (request.artistTokens.length) {
const artistOverlap = request.artistTokens.filter(token => normalizedAuthor.includes(token)).length;
score += artistOverlap * 5;
}
}
return score;
}
_pickBestTrack(tracks, provider = "ytm", request = null) {
const playable = tracks.filter(track => this._isPlayableTrack(track));
const candidates = playable.length > 0 ? playable : tracks;
if (!candidates.length) return null;
return candidates
.map((track, index) => ({ track, index, score: this._scoreTrackForAudio(track, provider, request) }))
.sort((a, b) => b.score - a.score || a.index - b.index)[0]
?.track ?? null;
}
_rankTracks(tracks, provider = "ytm", request = null) {
const playable = tracks.filter(track => this._isPlayableTrack(track));
const candidates = playable.length > 0 ? playable : tracks;
return candidates
.map((track, index) => ({ track, index, score: this._scoreTrackForAudio(track, provider, request) }))
.sort((a, b) => b.score - a.score || a.index - b.index)
.map(item => item.track);
}
_applyTrackMeta(video, trackMeta = null) {
if (!video || !trackMeta) return video;
return {
...video,
artist: trackMeta.artist ?? video.artist ?? null,
requestedArtist: trackMeta.artist ?? video.requestedArtist ?? null,
requestedTitle: trackMeta.name ?? trackMeta.title ?? video.requestedTitle ?? null,
lastfm: {
source: trackMeta.source ?? "lastfm",
artist: trackMeta.artist ?? null,
name: trackMeta.name ?? trackMeta.title ?? null,
url: trackMeta.url ?? "",
},
};
}
/**
* Return an ordered list of providers to try when searching.
* The requested provider is first; if it returns no results we fall
* back to YouTube Music, then YouTube.
* @param {string} provider
* @returns {string[]}
*/
_getFallbackChain(provider) {
const chain = [provider];
if (provider !== "ytm") chain.push("ytm");
if (provider !== "yt") chain.push("yt");
return chain;
}
/**
* Search a single provider using multiple identifier formats.
* Different NodeLink source plugins accept different identifier formats,
* so we try each variant until one returns results.
* @param {string} provider
* @param {string} query
* @returns {Promise<object[]|null>} Array of tracks, or null if this provider has no results at all.
*/
async _searchProvider(provider, query) {
const identifiers = this._buildIdentifiers(provider, query);
for (const id of identifiers) {
let data;
try {
data = await loadTracks(id, this._nlGet ?? nlGet);
} catch (e) {
logger.worker(`[Worker] _searchProvider: loadTracks failed for ${provider} (${id}): ${e.message}`);
continue;
}
const tracks = extractTracks(data);
if (tracks.length > 0) {
return tracks;
}
}
return null;
}
/**
* Search for multiple results (used by search command).
* @param {string} query
* @param {number} limit
* @param {string} provider
* @param {object|null} trackMeta
* @returns {Promise<{data: object[]}>}
*/
async getResults(query, limit = 5, provider = "ytm", trackMeta = null) {
const request = this._buildRequestContext(query, trackMeta);
const providers = this._getFallbackChain(provider);
for (const prov of providers) {
const id = this.isValidUrl(query) ? query : null;
let tracks;
if (id) {
let data;
try {
data = await loadTracks(id, this._nlGet ?? nlGet);
} catch (e) {
logger.worker("[Worker] getResults loadTracks failed:", e?.message);
continue;
}
tracks = extractTracks(data);
} else {
tracks = await this._searchProvider(prov, query);
}
if (tracks && tracks.length > 0) {
const resultTracks = this._rankTracks(tracks, prov, request);
return { data: resultTracks.slice(0, limit).map(track => this._applyTrackMeta(trackToVideo(track), trackMeta)) };
}
logger.worker(`[Worker] getResults: no results from ${prov}, trying fallback...`);
}
return { data: [] };
}
/**
* Search for a single track (used by play command).
* Tries multiple identifier formats per provider, then falls back
* through the provider chain until a result is found.
* @param {string} query
* @param {string} provider
* @param {object|null} trackMeta
* @returns {Promise<{type: string, data: *, error?: string}>}
*/
async getVideoData(query, provider = "ytm", trackMeta = null) {
const request = this._buildRequestContext(query, trackMeta);
if (this.isValidUrl(query)) {
return this._loadUrl(query, provider, request, trackMeta);
}
return this._searchByQuery(query, provider, request, trackMeta);
}
/**
* Handle URL-based track loading.
* @private
*/
async _loadUrl(query, provider, request, trackMeta) {
this.emit("message", "Loading...");
const cleanedUrl = this._cleanYouTubeUrl(query);
if (cleanedUrl !== query) {
logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`);
}
let data;
try {
data = await loadTracks(cleanedUrl, this._nlGet ?? nlGet);
} catch (e) {
this.emit("message", `**Failed to load that track.**`);
return { type: "error", data: null, error: sanitizeError(e.message) };
}
if (data.loadType === "empty") {
this.emit("message", `**No results found for that URL.**`);
return { type: "error", data: null, error: "No results found (empty)" };
}
if (data.loadType === "track" && data.data) {
const video = this._applyTrackMeta(trackToVideo(data.data), trackMeta);
if (!video) return { type: "error", data: "Failed to parse track data." };
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
if (data.loadType === "playlist") {
const tracks = (data.data?.tracks ?? []).map(track => this._applyTrackMeta(trackToVideo(track), trackMeta));
tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; });
if (tracks.length > 0) {
this.emit("message", `Successfully added **${tracks.length}** songs to the queue.`);
return { type: "list", data: tracks };
}
this.emit("message", `**Playlist was empty.**`);
return { type: "error", data: null, error: "Playlist was empty" };
}
if (data.loadType === "search") {
if (data.data?.length) {
const bestTrack = this._pickBestTrack(data.data, provider, request) ?? data.data[0];
const video = this._applyTrackMeta(trackToVideo(bestTrack), trackMeta);
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
this.emit("message", `**Search returned no results for that URL.**`);
return { type: "error", data: null, error: "Search returned 0 results for URL" };
}
this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`);
return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") };
}
/**
* Handle text-based search across provider fallback chain.
* For each provider, tries all identifier variants before giving up.
* @private
*/
async _searchByQuery(query, provider, request, trackMeta) {
const providers = this._getFallbackChain(provider);
let lastError = null;
for (const prov of providers) {
this.emit("message", `Searching ${this._providerLabel(prov)}...`);
const tracks = await this._searchProvider(prov, query);
if (tracks && tracks.length > 0) {
const trackToUse = this._pickBestTrack(tracks, prov, request) ?? tracks[0];
const video = this._applyTrackMeta(trackToVideo(trackToUse), trackMeta);
if (video) {
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
return { type: "video", data: video };
}
lastError = "Failed to parse track data.";
continue;
}
logger.worker(`[Worker] No results from ${prov}`);
}
this.emit("message", `**No results found for '${query}'.**`);
return { type: "error", data: null, error: lastError ?? "No results found" };
}
}
const jobId = workerData?.jobId;
const data = workerData?.data;
if (workerData?.poolMode) {
const utils = new YTUtils();
const post = (jobKey, event, payload) => {
parentPort.postMessage(JSON.stringify({ jobKey, event, data: payload }));
};
parentPort.on("message", async (raw) => {
let parsed;
try { parsed = typeof raw === "string" ? JSON.parse(raw) : raw; }
catch (_) { return; }
const { jobKey, jobId: jId, data: jData } = parsed;
if (!jobKey || !jId) return;
const nlJob = jData?.nodelink ?? {};
const nlHostJob = nlJob.host ?? "localhost";
const nlPortJob = nlJob.port ?? 3000;
const nlPassJob = nlJob.password ?? NL_DEFAULT_PASSWORD;
const nlSidJob = nlJob.sessionId ?? null;
const nlGidJob = jData?.guildId ?? null;
const nlGetJob = (path) => new Promise((resolve, reject) => {
const isHttps = nlPortJob === 443;
const mod = isHttps ? https : http;
const protocol = isHttps ? "https" : "http";
const req = mod.get(
`${protocol}://${nlHostJob}:${nlPortJob}${path}`,
{
headers: {
Authorization: nlPassJob,
...(nlSidJob ? { "Session-Id": nlSidJob } : {}),
...(nlGidJob ? { "Guild-Id": nlGidJob } : {}),
},
},
(res) => {
const chunks = [];
res.on("data", d => chunks.push(d));
res.on("end", () => {
const body = Buffer.concat(chunks).toString();
if (res.statusCode < 200 || res.statusCode >= 300) {
let detail = "";
try {
const parsed = JSON.parse(body);
detail = parsed.error ?? parsed.message ?? "";
} catch (_) {
detail = body.slice(0, 200);
}
return reject(new Error(`NodeLink HTTP ${res.statusCode}${detail ? ": " + detail : ""}`));
}
try { resolve(JSON.parse(body)); }
catch (e) { reject(new Error(`NodeLink JSON parse error: ${e.message}`)); }
});
},
);
req.on("error", reject);
req.setTimeout(30_000, () => { req.destroy(); reject(new Error("NodeLink request timeout")); });
});
const jobUtils = new YTUtils();
jobUtils._nlGet = nlGetJob;
jobUtils.on("message", (m) => post(jobKey, "message", m));
jobUtils.on("error", (m) => post(jobKey, "error", m));
try {
let result;
switch (jId) {
case "generalQuery":
result = await jobUtils.getVideoData(jData.query, jData.provider, jData.trackMeta);
break;
case "searchResults":
result = await jobUtils.getResults(jData.query, jData.resultCount, jData.provider, jData.trackMeta);
break;
case "search":
result = await jobUtils.getVideoData(jData.query ?? String(jData), "ytm");
result = result?.data ?? null;
break;
default:
post(jobKey, "error", `Unknown jobId: ${jId}`);
return;
}
post(jobKey, "finished", result);
} catch (err) {
post(jobKey, "error", err.message);
} finally {
jobUtils.removeAllListeners();
}
});
} else {
if (!jobId) {
logger.error("No jobId provided to worker");
process.exit(1);
}
const utils = new YTUtils();
const post = (event, payload) => {
parentPort.postMessage(JSON.stringify({ event, data: payload }));
};
utils.on("message", (m) => {
post("message", m);
});
utils.on("error", (m) => {
post("error", m);
});
(async () => {
try {
switch (jobId) {
case "generalQuery": {
const result = await utils.getVideoData(data.query, data.provider, data.trackMeta);
post("finished", result);
break;
}
case "searchResults": {
const result = await utils.getResults(data.query, data.resultCount, data.provider, data.trackMeta);
post("finished", result);
break;
}
case "search": {
const result = await utils.getVideoData(data.query ?? String(data), "ytm");
post("finished", result?.data ?? null);
break;
}
default:
logger.error("Invalid jobId:", jobId);
post("error", `Unknown jobId: ${jobId}`);
}
} catch (err) {
post("error", err.message);
} finally {
process.exit(0);
}
})();
}
+3 -9
View File
@@ -5,20 +5,14 @@
"pfp": "default",
"locale": "en",
"stay_247": "none",
"stay_247_mode": "off",
"stay_247_modes": {},
"volume": 100,
"announcementChannelId": null
"volume": 100
},
"descriptions": {
"songAnnouncements": "Whether the bot should announce every song in a new message when it starts playing. Set to `true` or `1` to enable.",
"prefix": "The prefix used to trigger commands.",
"pfp": "What profile picture the bot should use. Presets: `default | dark | light | mono | <custom url>`.",
"locale": "The preferred language of your server.",
"stay_247": "24/7 saved voice channels for this server. Supports multiple channels and is managed automatically by $prefix247 — do not edit manually.",
"stay_247_mode": "Legacy guild-wide 24/7 mode. Superseded by stay_247_modes (per-channel). Kept for backward compatibility.",
"stay_247_modes": "Per-channel 24/7 mode map. Format: {\"channelId\": \"on\"|\"auto\"|\"off\"}. Managed automatically by $prefix247 — do not edit manually.",
"volume": "The default playback volume for this server (1-200). Saved automatically when you use $prefixvolume. Restored every time the bot joins a channel.",
"announcementChannelId": "The channel where song announcements are sent. Managed automatically — do not edit manually."
"stay_247": "Join a voice channel and use `$prefix247` to toggle 24/7. The bot stays permanently and auto-rejoins if disconnected. Use `$prefix247 off` to disable.",
"volume": "The default playback volume for this server (1-200). Saved automatically when you use $prefixvolume."
}
}
+1
View File
@@ -295,6 +295,7 @@
"specifyChannel": "⚠️ أنت لست في قناة صوتية. أنا أعزف في:\n{{channels}}\n\nاستخدم `{{prefix}}leave <#channel>` لمغادرة قناة محددة.",
"noPlayerInChannel": "⚠️ أنا لا أعزف في <#{{channel}}>. أنا في:\n{{channels}}",
"playerNotInit": "المشغّل غير مهيأ.",
"left": "✅ تم المغادرة بنجاح",
"leftRejoin247": "✅ تم المغادرة بنجاح — سأعيد الانضمام إلى <#{{channel}}> خلال بضع ثوانٍ.\nلتعطيل وضع 24/7 بشكل دائم، استخدم `{{prefix}}247 off`.",
"left247On": "✅ تم المغادرة بنجاح.\nوضع 24/7 **مفعّل** — لن يعود البوت تلقائياً. استخدم `{{prefix}}play` لإعادته، أو `{{prefix}}247 off` لتعطيله بالكامل.\nاستخدم `{{prefix}}247` لعرض جميع القنوات المحفوظة.",
"autoRejoinHint": "⚠️ وضع 24/7 مفعّل (تلقائي) — سأعيد الانضمام إلى <#{{channel}}> خلال بضع ثوانٍ.\nلتتمكن من إزالتي بشكل دائم، عطّل وضع 24/7 أولاً: `{{prefix}}247 off`"
+1
View File
@@ -295,6 +295,7 @@
"specifyChannel": "⚠️ تۆ لە کەناڵێکی دەنگیدا نیت. من پەخش دەکەم لە:\n{{channels}}\n\n`{{prefix}}leave <#channel>` بەکاربهێنە بۆ جێهێشتنی کەناڵێکی دیاریکراو.",
"noPlayerInChannel": "⚠️ من پەخش ناکەم لە <#{{channel}}>. من لە:\n{{channels}}",
"playerNotInit": "پەخشکەرەکە ئامادە نەکراوە.",
"left": "✅ بە سەرکەوتوویی دەرچوو",
"leftRejoin247": "✅ بە سەرکەوتوویی دەرچوو — دووبارە بەشداری <#{{channel}}> دەکەم لە چەند چرکەیەکدا.\nبۆ ناچالاککردنی دۆخی 24/7 بەهەمیشەیی، `{{prefix}}247 off` بەکاربهێنە.",
"left247On": "✅ بە سەرکەوتوویی دەرچوو.\nدۆخی 24/7 **چالاکە** — بۆتەکە دووبارە خۆی ناچێتەوە. `{{prefix}}play` بەکاربهێنە بۆ گەڕاندنی، یان `{{prefix}}247 off` بۆ ناچالاککردنی تەواو.\n`{{prefix}}247` بەکاربهێنە بۆ بینینی هەموو کەناڵە پاشەکەوتکراوەکان.",
"autoRejoinHint": "⚠️ دۆخی 24/7 چالاکە (خۆکار) — دووبارە بەشداری <#{{channel}}> دەکەم لە چەند چرکەیەکدا.\nبۆ لابردنی من بەهەمیشەیی، سەرەتا دۆخی 24/7 ناچالاک بکە: `{{prefix}}247 off`"
+1
View File
@@ -295,6 +295,7 @@
"specifyChannel": "⚠️ Du bist in keinem Sprachkanal. Ich spiele in:\n{{channels}}\n\nNutze `{{prefix}}leave <#channel>` um einen bestimmten Kanal zu verlassen.",
"noPlayerInChannel": "⚠️ Ich spiele nicht in <#{{channel}}>. Ich bin in:\n{{channels}}",
"playerNotInit": "Player nicht initialisiert.",
"left": "✅ Erfolgreich verlassen",
"leftRejoin247": "✅ Erfolgreich verlassen — trete <#{{channel}}> in wenigen Sekunden wieder bei.\nUm den 24/7-Modus dauerhaft zu deaktivieren, nutze `{{prefix}}247 off`.",
"left247On": "✅ Erfolgreich verlassen.\n24/7-Modus ist **aktiv** — Bot wird nicht automatisch wiederkommen. Nutze `{{prefix}}play`, um ihn zurückzuholen, oder `{{prefix}}247 off` zum vollständigen Deaktivieren.\nNutze `{{prefix}}247` um alle gespeicherten Kanäle zu sehen.",
"autoRejoinHint": "⚠️ 24/7-Modus ist aktiviert (auto) — trete <#{{channel}}> in wenigen Sekunden wieder bei.\nUm mich dauerhaft zu entfernen, deaktiviere zuerst den 24/7-Modus: `{{prefix}}247 off`"
+1
View File
@@ -298,6 +298,7 @@
"specifyChannel": "⚠️ You're not in a voice channel. I'm playing in:\n{{channels}}\n\nUse `{{prefix}}leave <#channel>` to leave a specific channel.",
"noPlayerInChannel": "⚠️ I'm not playing in <#{{channel}}>. I'm in:\n{{channels}}",
"playerNotInit": "Player not initialized.",
"left": "✅ Successfully Left",
"leftRejoin247": "✅ Successfully Left — rejoining <#{{channel}}> in a few seconds.\nTo disable 24/7 mode permanently, use `{{prefix}}247 off`.",
"left247On": "✅ Successfully Left.\n24/7 mode is **on** — bot won't rejoin automatically. Use `{{prefix}}play` to bring it back, or `{{prefix}}247 off` to fully disable.\nUse `{{prefix}}247` to view all saved channels.",
"autoRejoinHint": "⚠️ 24/7 mode is enabled (auto) — I'll rejoin <#{{channel}}> in a few seconds.\nTo permanently remove me, disable 24/7 mode first: `{{prefix}}247 off`"
+1
View File
@@ -295,6 +295,7 @@
"specifyChannel": "⚠️ Você não está em um canal de voz. Estou tocando em:\n{{channels}}\n\nUse `{{prefix}}leave <#channel>` para sair de um canal específico.",
"noPlayerInChannel": "⚠️ Não estou tocando em <#{{channel}}>. Estou em:\n{{channels}}",
"playerNotInit": "Player não inicializado.",
"left": "✅ Sai com sucesso",
"leftRejoin247": "✅ Sai com sucesso — reentrando em <#{{channel}}> em alguns segundos.\nPara desativar o modo 24/7 permanentemente, use `{{prefix}}247 off`.",
"left247On": "✅ Sai com sucesso.\nO modo 24/7 está **ativo** — o bot não voltará automaticamente. Use `{{prefix}}play` para trazê-lo de volta ou `{{prefix}}247 off` para desativar completamente.\nUse `{{prefix}}247` para ver todos os canais salvos.",
"autoRejoinHint": "⚠️ O modo 24/7 está ativado (auto) — vou reentrar em <#{{channel}}> em alguns segundos.\nPara me remover permanentemente, desative o modo 24/7 primeiro: `{{prefix}}247 off`"
+1
View File
@@ -295,6 +295,7 @@
"specifyChannel": "⚠️ Bir ses kanalında değilsiniz. Şu kanallardayım:\n{{channels}}\n\nBelirli bir kanaldan ayrılmak için `{{prefix}}leave <#kanal>` kullanın.",
"noPlayerInChannel": "⚠️ <#{{channel}}> kanalında çalmıyorum. Şu kanallardayım:\n{{channels}}",
"playerNotInit": "Oynatıcı başlatılmadı.",
"left": "✅ Başarıyla Ayrıldı",
"leftRejoin247": "✅ Başarıyla Ayrıldı — birkaç saniye içinde <#{{channel}}> kanalına tekrar katılınıyor.\n24/7 modunu kalıcı olarak devre dışı bırakmak için `{{prefix}}247 off` kullanın.",
"left247On": "✅ Başarıyla Ayrıldı.\n24/7 modu **açık** — bot otomatik olarak tekrar katılmayacak. Geri getirmek için `{{prefix}}play` veya tamamen devre dışı bırakmak için `{{prefix}}247 off` kullanın.\nKayıtlı tüm kanalları görüntülemek için `{{prefix}}247` kullanın.",
"autoRejoinHint": "⚠️ 24/7 modu etkin (auto) — birkaç saniye içinde <#{{channel}}> kanalına tekrar katılacağım.\nBeni kalıcı olarak çıkarmak için önce 24/7 modunu devre dışı bırakın: `{{prefix}}247 off`"
+1 -7
View File
@@ -1,7 +1 @@
[
{
"name": "wb-dashboard",
"index": "./dashboard/index.js",
"enabled": false
}
]
[]