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
+5708 -10180

No files matched your search

-10
View File
@@ -3,16 +3,6 @@ storage/data
config.json config.json
settings.json settings.json
remix-settings.json remix-settings.json
cmdUsage.md
bot.js
bin/
test_data/ test_data/
*.code-workspace *.code-workspace
*old.js
.ytcache/
.yt_auth.json
yt_auth.json
visitor_data.json
.moonlink/
storage/recovery.json
.idea/ .idea/
+140 -138
View File
@@ -18,10 +18,10 @@
<p align="center"> <p align="center">
<img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License"> <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/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/Audio-lavalink--client%20%2B%20NodeLink-orange.svg" alt="lavalink-client">
<img src="https://img.shields.io/badge/Voice-revoice.js-9b59b6.svg" alt="revoice.js"> <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/Database-MySQL-4479A1.svg" alt="MySQL">
<img src="https://img.shields.io/badge/Maintained%3F-Yes-green.svg" alt="Maintained"> <img src="https://img.shields.io/badge/Maintained%3F-Yes-green.svg" alt="Maintained">
</p> </p>
@@ -31,6 +31,7 @@
## Table of Contents ## Table of Contents
- [About The Project](#-about-the-project) - [About The Project](#-about-the-project)
- [How Audio Playback Works](#-how-audio-playback-works)
- [Features](#-features) - [Features](#-features)
- [Getting Started (Users)](#-getting-started-users) - [Getting Started (Users)](#-getting-started-users)
- [Commands](#-commands) - [Commands](#-commands)
@@ -49,32 +50,59 @@
## About The Project ## 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.** 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 ## Features
- **High-quality audio playback** via moonlink.js (Lavalink proxy), revoice.js (LiveKit voice + MediaPlayer), and `@fluxerjs/voice` - **High-quality audio playback** — NodeLink streaming with a zero-re-encode WebM/Opus pipeline, published over LiveKit
- **Multi-source search** — YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and direct URL support - **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 auto-recovery on restart - **24/7 mode** — keep the bot in a voice channel permanently, with staggered auto-rejoin on boot and rejoin retries on connection loss
- **Session recovery** — active players and queues survive bot restarts and crash recovery - **Interactive emoji player** — reaction-based control panel with live progress, lyrics viewer, and a filter submenu
- **Interactive emoji player** — reaction-based control panel with play, pause, skip, volume, shuffle, and more - **Lyrics** — synced lyrics via NodeLink
- **Lyrics** — fetch synced lyrics via NodeLink
- **Radio stations** — built-in support for custom radio streams with keyword-based search - **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) - **Autoplay** — automatically play similar tracks when the queue ends (powered by Last.fm)
- **Seek** — jump to a specific position in the current track - **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 - **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 - **Audio filters** — bassboost, speed, nightcore and more (applied server-side by NodeLink)
- **Web dashboard** — optional browser-based control panel with Redis-backed sessions and Fluxer OAuth2 login - **Server settings** — per-guild configuration (prefix, volume, locale, 24/7 channels, …) stored in MySQL
- **Multi-language support** — available in English, Arabic, German, Kurdish (Sorani), and Brazilian Portuguese - **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 - **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 - **Graceful shutdown** — destroys players and closes MySQL/Redis/NodeLink sessions cleanly on SIGINT/SIGTERM/SIGUSR2
- **Module system** — pluggable module architecture for extending bot functionality - **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` | | `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` |
| `support` | Get an invite to the support server | `%support` | `server` | | `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` | | `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` | | | `reload` | Reload commands or modules at runtime (owner) | `%reload` | |
| `servers` | List servers the bot is in (owner) | `%servers` | | | `servers` | List servers the bot is in (owner) | `%servers` | |
| `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | | | `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | |
| `debug` | Debug voice connections and player state (owner) | `%debug voice` | | | `debug` | Debug voice connections and player state (owner) | `%debug voice` | |
| `test` | Show voice channel user counts (owner) | `%test` | | | `test` | Show voice channel user counts (owner) | `%test` | |
---
## Self-Hosting The Bot ## 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)"*). 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 ```bash
git clone https://github.com/remix-bot/fluxer.git git clone https://github.com/remix-bot/fluxer.git
cd fluxer/docker cd fluxer/docker
cp .env.example .env
cp config_example.json config.json 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:** 4. **Start everything:**
```bash ```bash
@@ -170,30 +197,30 @@ The fastest way to self-host Remix is with Docker. Everything — the bot, MySQL
docker compose logs -f bot 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 file structure
``` ```
docker/ docker/
├── Dockerfile # Multi-stage build (Node 22 + FFmpeg + tini) ├── Dockerfile # Multi-stage build (Node 22 + tini, non-root user, healthcheck)
├── docker-entrypoint.sh # Config validation on first boot ├── docker-entrypoint.sh # Writes config.json from CONFIG_JSON env var on first boot
├── docker-compose.yml # bot + MySQL + Redis + NodeLink ├── docker-compose.yml # bot + MySQL + Redis + NodeLink
├── .env.example # Compose env template (MySQL creds, ports, TZ)
├── config_example.json # Docker-friendly config template ├── config_example.json # Docker-friendly config template
├── .env.example # Secrets template
├── nodelink.config.json # NodeLink audio node config
├── config.json # You create this (gitignored) ├── 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 #### Docker services
| Service | Container | Port | Purpose | | Service | Container | Port | Purpose |
| :--- | :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| `bot` | remix-bot | 8080 → 80 | The Remix bot + web dashboard | | `bot` | remix-bot | `${WEB_PORT:-8080}` → 80 | The Remix bot (+ optional dashboard backend) |
| `mysql` | remix-mysql | — | Per-guild settings storage | | `mysql` | remix-mysql | — | Settings, Last.fm users, and track options storage |
| `redis` | remix-redis | — | Dashboard sessions + pub/sub (optional) | | `redis` | remix-redis | — | Dashboard RPC pub/sub (optional) |
| `nodelink` | remix-nodelink | 3000 | Lavalink-compatible audio node | | `nodelink` | remix-nodelink | `${NODELINK_PORT:-3000}` | Lavalink-compatible audio node |
#### Useful Docker commands #### Useful Docker commands
@@ -234,11 +261,10 @@ The entrypoint will write it to `/app/config.json` on first boot if no config fi
#### Prerequisites #### Prerequisites
- **Node.js** >= 22.0.0 (required by moonlink.js v5) - **Node.js** >= 22.13.0
- **MySQL** 8.0+ with JSON column support - **MySQL** 8.0+ with JSON column support
- **[NodeLink](https://github.com/PerformanC/NodeLink)** instance (Lavalink proxy for audio) - **[NodeLink](https://github.com/PerformanC/NodeLink)** instance (Lavalink-compatible audio node)
- **FFmpeg** (installed automatically via `ffmpeg-static`) - **Redis** (optional — required only for the dashboard backend)
- **Redis** (optional, required for the web dashboard)
### Installation ### 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) - `mysql` — your MySQL connection details (host, port, user, password, database)
- `prefix` — the command prefix (default: `%`) - `prefix` — the command prefix (default: `%`)
- `nodelink` — your NodeLink instance connection details - `nodelink` — your NodeLink instance connection details
- `spotify` — (optional) Spotify API credentials for Spotify track support - `lastfm` — (optional) Last.fm API credentials for scrobbling/autoplay features
- `geniusToken` — *(deprecated, unused)* was previously for lyrics; lyrics are now fetched via NodeLink
- `owners` — array of Fluxer user IDs with owner-only command access - `owners` — array of Fluxer user IDs with owner-only command access
4. **Set up the database:** *(See [Database Setup](#-database-setup) below)* 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 ### 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: 1. Create a dedicated database for Remix:
```sql ```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 ```sql
CREATE TABLE `settings` ( CREATE TABLE `settings` (
`id` varchar(70) NOT NULL, `id` varchar(70) NOT NULL,
@@ -306,58 +331,39 @@ Remix requires a MySQL database to store per-guild settings.
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
``` ```
4. Create the track options table (for the `%trackopt` command): 4. Everything else is **auto-created on startup** if missing:
```sql - `track_options` — per-user per-track start/end times (`%trackopt`)
CREATE TABLE IF NOT EXISTS `track_options` ( - `lastfm_users` — Last.fm session keys and scrobble opt-ins
`id` INT AUTO_INCREMENT PRIMARY KEY, - `lastfm_stats` — stored scrobble/link counts
`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.
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 ```bash
npm run migrate npm run migrate
``` ```
### Dashboard Setup (Optional) ### 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 ```json
"dashboard": { "dashboard": {
"enabled": true, "enabled": true,
"redis": { "url": "redis://localhost:6379" }, "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"
}
} }
``` ```
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`: 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.
```json
"ssl": {
"private": "/etc/letsencrypt/live/your.domain/privkey.pem",
"cert": "/etc/letsencrypt/live/your.domain/fullchain.pem",
"useSSL": true,
"httpPort": 80
}
```
### Configuration Reference ---
## Configuration Reference
Key configuration options in `config.json`: Key configuration options in `config.json`:
@@ -367,28 +373,19 @@ Key configuration options in `config.json`:
| `prefix` | string | `%` | Default command prefix | | `prefix` | string | `%` | Default command prefix |
| `embedColor` | string | `0xe9196c` | Hex color for embed messages | | `embedColor` | string | `0xe9196c` | Hex color for embed messages |
| `owners` | string[] | `[]` | User IDs with owner privileges | | `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 | | `customStatsFooter` | string | — | Custom text shown in the `%stats` embed footer |
| `webPort` | number | `80` | Port for the web dashboard | | `presenceInterval` | number | `30000` | Interval in ms for rotating bot presence status |
| `helpCatalog` | bool | `true` | Enable categorized help command | | `presenceContents` | array | `[]` | Presence status messages to cycle through (strings or objects with `text`/`emoji_name`/`emoji_id`/`activity`) |
| `helpPagination` | bool | `true` | Enable paginated help output |
| `mysql` | object | — | **Required.** MySQL connection settings | | `mysql` | object | — | **Required.** MySQL connection settings |
| `nodelink` | object | — | NodeLink connection (`host`, `port`, `password`, `requestTimeout`) | | `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`) | | `lastfm` | object | — | Last.fm integration (`apiKey`, `apiSecret`, `scrobbleThreshold`, `scrobbleMinMs`) |
| `dashboard` | object | — | Dashboard config: `enabled`, `redis`, `fluxer` (OAuth2) | | `fluxerlist` | object | — | FluxerList integration (`apiKey`, `serverId`, `botId`, `serverSlug`, `botSlug`) |
| `dashboardUrl` | string | — | URL the dashboard is accessible from | | `dashboard` | object | — | Dashboard backend: `enabled`, `redis.url` |
| `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`) |
| `radio` | array | `[]` | Custom radio station definitions | | `radio` | array | `[]` | Custom radio station definitions |
| `ssl` | object | — | SSL certificate paths (`private`, `cert`), `useSSL`, `httpPort` | | `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`) |
| `presenceInterval` | number | — | Interval in ms for rotating bot presence status | | `timers` | object | — | Timing values in ms: `inactivityTimeout`, `aloneCheckInterval`, `aloneCheckDebounce`, `rejoin247Delay`, `leave247RejoinDelay`, `playerUpdateInterval`, `searchSessionTimeout`, `playerSessionTimeout`, `intentionalLeaveTTL` |
| `presenceContents` | string[] | `[]` | Presence status messages to cycle through |
| `fluxer.js` | object | — | Fluxer.js REST options (`timeout`, `retries`) | | `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/ 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 ├── config_example.json # Configuration template
├── package.json ├── package.json
├── commands/ # Command modules (one file per command) ├── commands/ # 37 command modules (one file per command)
│ ├── play.mjs # Play a track or playlist │ ├── play.mjs # Play a track or playlist (Last.fm categories, providers)
│ ├── player.mjs # Interactive emoji control panel with live progress │ ├── 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 │ ├── lyrics.mjs # Synced lyrics from NodeLink
│ ├── filter.mjs # Audio filter controls │ ├── filter.mjs # Audio filter controls
│ ├── radio.mjs # Radio station management │ ├── radio.mjs # Radio station management
│ ├── debug.mjs # Voice connection debugger (owner only, paginated) │ ├── debug.mjs # Voice connection debugger (owner only)
│ ├── stats.mjs # Bot stats with live player count │ ├── lastfm.mjs # Last.fm linking, scrobbling, profiles, leaderboards
│ ├── lastfm.mjs # Last.fm account linking, scrobbling, and profile
│ ├── trackopt.mjs # Per-track start/end time options (set/get/remove/list) │ ├── trackopt.mjs # Per-track start/end time options (set/get/remove/list)
│ └── ... # All other commands │ └── ... # All other commands
├── src/ ├── src/
│ ├── CommandHandler.mjs # Command loader, prefix manager, registry │ ├── CommandHandler.mjs # Command framework — builder, options, requirements,
│ ├── MessageHandler.mjs # Message parsing, embed builder, pagination, help │ │ # cooldowns, prefix manager, loader
│ ├── PlayerManager.mjs # Spawns and manages per-channel Player instances │ ├── MessageHandler.mjs # Replies/embeds, reaction observers, pagination, help
│ ├── Player.mjs # Core player — queue, playback, filters, events │ ├── PlayerManager.mjs # Player lifecycle, VC resolution & permission checks,
│ ├── MoonlinkManager.mjs # Moonlink.js (Lavalink) node session manager │ │ # dashboard broadcasts, Last.fm scrobble wiring
│ ├── Settings.mjs # RemoteSettingsManager + ServerSettings export │ ├── Player.mjs # Core per-channel player — queue, playback, filters,
│ ├── GatewayHandler.mjs # Raw WS events, voice-state tracking, presence rotation │ │ # search sessions, autoplay, error circuit breaker
│ ├── RecoveryManager.mjs # Session persistence, crash recovery, 24/7 auto-join │ ├── FluxerAudioBridge.mjs # Audio engine — NodeLink REST streams → sniff/remux/
│ ├── LastFmManager.mjs # Last.fm API client — auth, scrobbling, user data, stored scrobble stats │ │ # encode → LiveKit publishing
│ ├── TrackOptionsManager.mjs # Per-user track start/end time preferences (auto-seek, auto-skip) │ ├── LavalinkManager.mjs # lavalink-client wrapper (NodeLink mode) — search,
│ ├── Utils.mjs # Shared utilities │ │ # voice payload caching, node readiness
│ ├── worker.mjs # Background task worker │ ├── GatewayHandler.mjs # Raw WS events, voice-state routing, guild lifecycle,
│ ├── probe.mjs # FFprobe wrapper for audio stream info │ │ # 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/ │ ├── constants/
│ │ ├── Logger.mjs # Structured logger with per-category control │ │ ├── Logger.mjs # Structured logger with per-category control
│ │ ├── Locale.mjs # i18n translation engine │ │ ├── Locale.mjs # i18n translation engine
│ │ ├── Helpers247.mjs # 24/7 mode helper utilities │ │ ├── Helpers247.mjs # 24/7 mode helpers
│ │ ├── providers.mjs # Audio source provider definitions │ │ ├── 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/ │ │ └── audio/
│ │ ├── StreamMerger.mjs # Audio stream merging utilities │ │ └── WebMOpusMuxer.mjs # Streaming EBML/Matroska muxer (Opus → WebM for LiveKit)
│ │ └── Tuna.mjs # Audio filter/effect processing
│ └── dashboard/ │ └── dashboard/
│ ├── Dashboard.mjs # Web dashboard server (Express + WebSocket) │ ├── Dashboard.mjs # Dashboard backend — Redis RPC, player/user serializers,
│ ├── DatabaseManager.mjs # Dashboard database query manager │ │ # remote-control actions with authorization checks
│ └── RedisHandler.mjs # Redis session and pub/sub handler │ ├── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers
│ └── RedisHandler.mjs # Redis pub/sub RPC transport with reconnect handling
├── settings/ ├── settings/
│ ├── Settings.mjs # Abstract SettingsManager base class │ ├── Settings.mjs # Re-export of src/Settings.mjs classes
│ ├── migrate.mjs # Legacy-to-remote settings migration script │ ├── migrate.mjs # One-shot settings table clone/repair tool
│ ├── runnables.mjs # Runnable task definitions │ ├── runnables.mjs # Setting validators (prefix, pfp, stay_247)
│ └── README.md # Settings system documentation │ └── README.md # Settings system documentation
├── docker/ # Docker self-hosting (Dockerfile, compose, configs) ├── docker/ # Docker self-hosting (Dockerfile, compose, entrypoint,
│ ├── Dockerfile # Multi-stage build (Node 22 + FFmpeg + tini) │ # config templates, .env.example)
│ ├── 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
└── storage/ └── storage/
├── defaults.json # Default per-guild settings template ├── defaults.json # Default per-guild settings template
├── modules.json # Plugin module registry ├── modules.json # Plugin module registry (empty by default)
├── stats.json # Runtime statistics ├── stats.json # Static counters
└── locales/bot/ # Translation files └── locales/bot/ # Translation files
├── en.json ├── en.json
├── ar-SA.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 start` | `node index.mjs` | Start the bot |
| `npm run dev` | `node --inspect index.mjs --trace-warnings` | Start with Node.js inspector | | `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 migrate` | `node settings/migrate.mjs` | Clone/repair the remote settings table |
| `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 |
--- ---
@@ -502,12 +503,13 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the
**Powered by:** **Powered by:**
- [`@fluxerjs/core`](https://github.com/fluxerjs/core) — Fluxer API client - [`@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) — LiveKit voice connections and playback
- [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) — Native voice channel integration - [`lavalink-client`](https://www.npmjs.com/package/lavalink-client) — Lavalink/NodeLink client (search + streaming)
- [`moonlink.js`](https://github.com/Ecliptia/moonlink.js) — Lavalink proxy - [`NodeLink`](https://github.com/PerformanC/NodeLink) — Lavalink-compatible audio node
- [`NodeLink`](https://github.com/PerformanC/NodeLink) — Audio node manager - [`prism-media`](https://github.com/discordjs/prism-media) — Opus encoding and stream demuxing
<p align="center"> <p align="center">
&copy; 2026 Remix. Code licensed under the <a href="LICENSE">MIT License</a>.<br> &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> <em>The Remix name, logo, and branding are proprietary and may not be reused.</em>
</p> </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 * @module commands/autoplay
* @description Toggle autoplay mode — automatically play similar tracks when the queue ends.
*/ */
import { CommandBuilder } from "../src/CommandHandler.mjs"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -8,6 +8,7 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the autoplay command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("autoplay") .setName("autoplay")
.setDescription("Toggle autoplay — automatically play similar tracks when the queue ends.", "commands.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"); .addAliases("ap");
/** /**
* Execute the autoplay command. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Run handler for the autoplay command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { 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 * @module commands/clear
* @description Remove all songs from the playback queue.
*/ */
import { CommandBuilder } from "../src/CommandHandler.mjs"; import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the clear command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("clear") .setName("clear")
.setDescription("Remove all songs from the queue.", "commands.clear") .setDescription("Remove all songs from the queue.", "commands.clear")
@@ -14,9 +18,10 @@ export const command = new CommandBuilder()
.setCategory("music"); .setCategory("music");
/** /**
* Execute the clear command. * Run handler for the clear command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Clears the entire queue and sends a confirmation embed.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(msg) { 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 * @module commands/debug
* @description Owner-only debug command for voice diagnostics, ghost connection detection, and forced rejoin.
*/ */
import { CommandBuilder } from "../src/CommandHandler.mjs"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -15,9 +15,10 @@ const INTENTIONAL_LEAVE_TTL = 30_000;
const MAX_DESC = 4096; const MAX_DESC = 4096;
/** /**
* Return a human-readable label for a voice room's connection state. * Get a human-readable label for a voice room's connection state.
* @param {object} room - The voice room instance * @private
* @returns {string} * @param {object|null} room - The voice room object.
* @returns {string} Connection state label.
*/ */
function roomStateLabel(room) { function roomStateLabel(room) {
if (!room) return "none"; if (!room) return "none";
@@ -33,10 +34,10 @@ function roomStateLabel(room) {
} }
/** /**
* Detect whether a player has a "ghost" connection — the player object exists * Check if a player has a ghost connection (appears in voice but WebSocket is dead).
* but the underlying voice room is disconnected, reconnecting, or absent. * @private
* @param {import("../src/Player.mjs").default} player * @param {object} player - The player instance.
* @returns {boolean} * @returns {boolean} True if the player has a ghost connection.
*/ */
function isGhostConnection(player) { function isGhostConnection(player) {
const conn = player.connection; 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. * Get the bot's voice channel state from the Discord gateway cache.
* @param {object} client - The Fluxer client instance * @private
* @param {string} guildId - The guild ID to look up * @param {object} client - The Discord client instance.
* @returns {{ userId: string, channelId: string } | null} * @param {string} guildId - The guild ID to check.
* @returns {{ userId: string, channelId: string }|null} Bot's voice state or null.
*/ */
function getBotGatewayVoiceState(client, guildId) { function getBotGatewayVoiceState(client, guildId) {
const botId = client.user?.id; 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. * Check if the gateway voice state is stale (mismatches the player's channel).
* @param {object} client - The Fluxer client instance * @private
* @param {import("../src/Player.mjs").default} player * @param {object} client - The Discord client instance.
* @returns {boolean} * @param {object} player - The player instance.
* @returns {boolean} True if the gateway presence is stale.
*/ */
function isStaleGatewayPresence(client, player) { function isStaleGatewayPresence(client, player) {
const guildId = player._guildId ?? player._resolveGuildId?.(); 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. * Build a human-readable label for a player (guild name / #channel name).
* @param {object} client - The Fluxer client * @private
* @param {string} channelId - The channel ID * @param {object} client - The Discord client instance.
* @param {import("../src/Player.mjs").default} player * @param {string} channelId - The voice channel ID.
* @returns {string} * @param {object} player - The player instance.
* @returns {string} Formatted label string.
*/ */
function buildPlayerLabel(client, channelId, player) { function buildPlayerLabel(client, channelId, player) {
const channel = client.channels.get(channelId); 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. * Force a player to leave and rejoin, restoring queue and playback state.
* @param {object} ctx - The bot context (this) * @private
* @param {import("../src/Player.mjs").default} player * @async
* @returns {Promise<{ success: boolean, reason?: string, channelId?: string, roomConnected?: boolean, roomState?: string, resumedPlayback?: boolean }>} * @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) { async function forceRejoinPlayer(ctx, player) {
const channelId = player._channelId ?? player._home247Channel; const channelId = player._channelId ?? player._home247Channel;
@@ -166,7 +172,6 @@ async function forceRejoinPlayer(ctx, player) {
try { try {
ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL); ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL);
ctx.revoice?.markIntentionalDisconnect(cleanChannelId);
ctx.players.playerMap.delete(cleanChannelId); ctx.players.playerMap.delete(cleanChannelId);
ctx.players._unindexPlayer?.(cleanGuildId, cleanChannelId); ctx.players._unindexPlayer?.(cleanGuildId, cleanChannelId);
@@ -188,13 +193,8 @@ async function forceRejoinPlayer(ctx, player) {
ctx.players._pendingJoins?.delete?.(cleanChannelId); ctx.players._pendingJoins?.delete?.(cleanChannelId);
const revoiceConn = ctx.revoice?.connections?.get(cleanChannelId); if (player.connection) {
if (revoiceConn) {
try { await ctx.revoice._destroyStaleConnection(cleanChannelId, revoiceConn); } catch (e) { logger.warn("[Debug] revoice stale destroy:", e?.message); }
} else if (player.connection) {
try { player.connection.removeAllListeners(); } catch (e) { logger.warn("[Debug] connection listener removal:", e?.message); } 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); } 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. * Process a batch of players for force-rejoin, updating a status message with progress.
* @param {object} ctx - The bot context (this) * @private
* @param {Array<[string, import("../src/Player.mjs").default]>} entries - [channelId, player] pairs * @async
* @param {import("../src/MessageHandler.mjs").Message} statusMsg - The status message to edit with progress * @param {object} ctx - The bot (Remix) instance context.
* @param {string} title - The embed title * @param {Array} entries - Array of [channelId, player] tuples.
* @returns {Promise<Array>} Results array * @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) { async function processRejoinBatch(ctx, entries, statusMsg, title) {
const results = []; const results = [];
@@ -286,11 +288,12 @@ async function processRejoinBatch(ctx, entries, statusMsg, title) {
} }
/** /**
* Build the final results embed after a batch rejoin. * Build the final embed summarizing rejoin results.
* @param {Array} results - Results from processRejoinBatch * @private
* @param {string} title - The embed title * @param {object[]} results - Array of rejoin result objects.
* @param {string} noun - "ghost connection(s)" or "24/7 channel(s)" * @param {string} title - The title for the embed.
* @returns {{embeds: [EmbedBuilder]}} * @param {string} noun - The noun describing the rejoin targets.
* @returns {object} Message payload with embed.
*/ */
function buildRejoinResultEmbed(results, title, noun) { function buildRejoinResultEmbed(results, title, noun) {
const resultLines = [ 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))] }; 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() export const command = new CommandBuilder()
.setName("debug") .setName("debug")
.setDescription("A debug command for various purposes.") .setDescription("A debug command for various purposes.")
@@ -336,9 +343,11 @@ export const command = new CommandBuilder()
.setRequired(true)); .setRequired(true));
/** /**
* Execute the debug command. * Run handler for the debug command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Routes to the appropriate debug subcommand based on the target option.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the target option.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { 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. * Run a batch rejoin operation on matching players.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * @private
* @param {string} key - The debug key for log labels * @async
* @param {string} title - The display title * @param {object} msg - The command message wrapper.
* @param {string} noun - What we're rejoining (for result text) * @param {string} key - Identifier key for the rejoin type.
* @param {(player: import("../src/Player.mjs").default) => boolean} filter - Player filter * @param {string} title - Display title for the operation.
* @param {boolean} showHintIfEmpty - Show a hint when no matches found * @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>} * @returns {Promise<void>}
*/ */
async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = false) { 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. * Run a full voice diagnostic, displaying player states and ghost connections.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * @private
* @async
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async function runVoiceDiagnostic(msg) { 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 * @module commands/eval
* @description Owner-only command to evaluate arbitrary JavaScript code and display the result.
*/ */
import { CommandBuilder } from "../src/CommandHandler.mjs"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,10 +10,7 @@ import { logger } from "../src/constants/Logger.mjs";
import { inspect } from "node:util"; import { inspect } from "node:util";
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
/** @private @type {string[]} Property name substrings that indicate sensitive/secret data. */
/**
* Matches any key that *contains* one of these strings (case-insensitive).
*/
const RESTRICTED = [ const RESTRICTED = [
"token", "token",
"config", "config",
@@ -24,21 +21,23 @@ const RESTRICTED = [
"secret", "secret",
"authorization", "authorization",
"mysql", "mysql",
"nodelink", "lavalink",
"_nl", "_nl",
"credential", "credential",
"apikey", "apikey",
"webhook", "webhook",
]; ];
/** @private @type {number} Maximum recursion depth when scanning for sensitive keys. */
const SCAN_DEPTH = 6; const SCAN_DEPTH = 6;
/** /**
* Check whether an object contains sensitive keys at any nesting level. * @private
* @param {object} obj - The object to scan * Recursively check whether an object contains keys matching RESTRICTED substrings.
* @param {number} [level=0] - Current recursion depth * @param {*} obj - The object to scan.
* @param {WeakSet} [visited=new WeakSet()] - Visited object tracker * @param {number} [level=0] - Current recursion depth.
* @returns {boolean} * @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()) { function hasSensitive(obj, level = 0, visited = new WeakSet()) {
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return false; 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]". * @private
* @param {object} obj - The object to scrub * Recursively redact sensitive keys in an object, replacing values with "[REDACTED]".
* @param {number} [level=0] - Current recursion depth * @param {*} obj - The object to clean.
* @param {WeakSet} [visited=new WeakSet()] - Visited object tracker * @param {number} [level=0] - Current recursion depth.
* @returns {object} The scrubbed object (or the original if no changes were needed) * @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()) { function removeSensitive(obj, level = 0, visited = new WeakSet()) {
if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return obj; 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. * @private
* @param {*} value - The value to clean and format * @async
* @returns {Promise<string>} Formatted, safe string representation * 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) { async function clean(value) {
if (value instanceof Promise) value = await 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). * @private
* @param {string} code - The code to inspect * Determine whether a code string is a single expression (vs. statements).
* @returns {boolean} * 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) { function isSingleExpression(code) {
const trimmed = code.trim(); const trimmed = code.trim();
@@ -137,8 +142,12 @@ function isSingleExpression(code) {
} }
/** /**
* Executes the code and returns the raw data instead of a formatted string, * @private
* so we can paginate it inside Embeds later. * @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) { async function runEval(expression, context) {
const start = Date.now(); const start = Date.now();
@@ -163,6 +172,7 @@ async function runEval(expression, context) {
return { output, isError, type, elapsed }; return { output, isError, type, elapsed };
} }
/** @type {CommandBuilder} @description Command definition for the eval command (owner-only). */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("eval") .setName("eval")
.setDescription("Evaluates JavaScript code (Owner Only).") .setDescription("Evaluates JavaScript code (Owner Only).")
@@ -175,9 +185,12 @@ export const command = new CommandBuilder()
); );
/** /**
* Execute the eval command. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Run handler for the eval command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { export async function run(msg, data) {
@@ -204,6 +217,13 @@ export async function run(msg, data) {
const totalPages = chunks.length; const totalPages = chunks.length;
let currentPage = 0; 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 buildPageContent = (pageIdx, expired = false) => {
const title = isError const title = isError
? this.t(msg, "responses.eval.resultTitleError") ? this.t(msg, "responses.eval.resultTitleError")
@@ -239,6 +259,11 @@ export async function run(msg, data) {
await replyMsg.message.react(emoji).catch(() => {}); await replyMsg.message.react(emoji).catch(() => {});
} }
/**
* @private
* Remove all navigation reactions from the eval reply message.
* @returns {Promise<void>}
*/
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await replyMsg.message.removeAllReactions(); 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 = () => { const resetTimer = () => {
clearTimeout(emojiTimeout); clearTimeout(emojiTimeout);
emojiTimeout = setTimeout(async () => { 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 * @module commands/filter
* @description Interactive audio filter picker with emoji-based selection and pagination.
*/ */
import { CommandBuilder } from "../src/CommandHandler.mjs"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -173,10 +173,10 @@ const PAGE_SIZE = 9;
const SESSION_MS = 60_000; const SESSION_MS = 60_000;
/** /**
* Merge multiple active filter payloads into a single Lavalink filters object. * Merge filter payloads for multiple active filter keys into one combined payload.
* Categories that overlap are overwritten by the last filter in the list. * @private
* The special "off" key is skipped — it carries an empty payload and is handled * @param {string[]} keys - Array of active filter keys.
* by clearing activeKeys before this function is called. * @returns {object} Merged Lavalink filter payload.
*/ */
function mergeFilterPayloads(keys) { function mergeFilterPayloads(keys) {
const merged = {}; const merged = {};
@@ -191,6 +191,10 @@ function mergeFilterPayloads(keys) {
return merged; return merged;
} }
/**
* @type {CommandBuilder}
* @description Command definition for the filter command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("filter") .setName("filter")
.setDescription( .setDescription(
@@ -201,13 +205,14 @@ export const command = new CommandBuilder()
.addAliases("filters", "fx", "effect"); .addAliases("filters", "fx", "effect");
/** /**
* Build the embed for a single page of the filter picker. * Build an embed for a page of the filter picker.
* @param {Function} t - Translation function * @private
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * @param {Function} t - Translation function.
* @param {number} page - Current page index (0-based) * @param {object} msg - The command message wrapper.
* @param {string[]} activeKeys - Currently active filter keys * @param {number} page - Current page index (0-based).
* @param {object} [current] - The currently playing track * @param {string[]} activeKeys - Array of currently active filter keys.
* @returns {import("@fluxerjs/core").EmbedBuilder} * @param {object|null} current - The currently playing track, or null.
* @returns {EmbedBuilder} The constructed embed.
*/ */
function buildPageEmbed(t, msg, page, activeKeys, current) { function buildPageEmbed(t, msg, page, activeKeys, current) {
const totalPages = Math.ceil(FILTERS.length / PAGE_SIZE); const totalPages = Math.ceil(FILTERS.length / PAGE_SIZE);
@@ -253,9 +258,10 @@ function buildPageEmbed(t, msg, page, activeKeys, current) {
} }
/** /**
* Execute the filter command. * Run handler for the filter command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Opens an interactive filter picker with emoji reactions.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} msg - The command message wrapper.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(msg) { 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 * @module commands/forceleave
* @description Force the bot to leave a voice channel (requires ManageChannels permission).
*/ */
import { CommandBuilder } from "../src/CommandHandler.mjs"; import { CommandBuilder } from "../src/CommandHandler.mjs";
import { cleanId } from "../src/MessageHandler.mjs"; import { cleanId } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the forceleave command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("forceleave") .setName("forceleave")
.addAliases("fl") .addAliases("fl")
@@ -20,9 +24,11 @@ export const command = new CommandBuilder()
/** /**
* Execute the forceleave command. * Run handler for the forceleave command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Validates the target channel and forces the bot to leave.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the channelId option.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { 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 * @module commands/invite
* @description Display the bot invite link and support server information.
*/ */
import { CommandBuilder } from "../src/CommandHandler.mjs"; import { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the invite command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("invite") .setName("invite")
.setDescription("Get the invite link for Remix and the support server.", "commands.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"); .setCategory("util");
/** /**
* Execute the invite command. * Run handler for the invite command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Sends an embed with the bot invite link and support server info.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} message - The command message wrapper.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(message) { 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 * @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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs"; 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. * @type {CommandBuilder}
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * @description Command definition for the join command.
* @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>}
*/ */
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() export const command = new CommandBuilder()
.setName("join") .setName("join")
.setDescription("Make the bot join your voice channel, or specify one.", "commands.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. * Resolve a user-provided channel string to a channel ID.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Supports <#ID> mentions, raw numeric IDs, and channel name matching.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @returns {Promise<void>} * @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) { export async function run(message, data) {
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null; const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
if (rawArg) { if (rawArg) {
const mentionMatch = rawArg.match(/^<#(\d+)>$/); const resolvedId = resolveChannelId(rawArg, this);
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;
}
if (!resolvedId) { if (!resolvedId) {
const embed = new EmbedBuilder().setColor(getGlobalColor()) const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(this.t(message, "responses.join.voiceChannelNotFound")); .setDescription(this.t(message, "responses.join.voiceChannelNotFound"));
return message.reply({ embeds: [embed] }); return message.reply({ embeds: [embed] });
} }
return this.players.initPlayer(message, resolvedId); return this.players.initPlayer(message, resolvedId);
} }
// No argument — auto-detect the user’s current voice channel
const { channelId: cid } = await this.players.checkVoiceChannels(message); const { channelId: cid } = await this.players.checkVoiceChannels(message);
if (!cid) { if (!cid) {
const prefix = this.handler.getPrefix(getMessageGuildId(message)); const prefix = this.handler.getPrefix(getMessageGuildId(message));
const embed = new EmbedBuilder().setColor(getGlobalColor()) const embed = new EmbedBuilder().setColor(getGlobalColor())
@@ -199,8 +85,3 @@ export async function run(message, data) {
return this.players.initPlayer(message, cid); 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 * @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"; 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"]; const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"];
/**
* @type {CommandBuilder}
* @description Command definition for the lastfm command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("lastfm") .setName("lastfm")
.setDescription("Link your Last.fm account, toggle scrobbling, or view your profile.", "commands.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) .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) { function notConfigured(ctx, msg) {
return { return {
embeds: [new EmbedBuilder() 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) { function notLinked(ctx, msg, prefix) {
return { return {
embeds: [new EmbedBuilder() embeds: [new EmbedBuilder()
@@ -67,6 +87,12 @@ function notLinked(ctx, msg, prefix) {
const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums", "artists"]; 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) { function buildLastFmTrackMeta(track) {
return { return {
source: "lastfm", 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") { async function resolveLastFmTrack(player, track, resolveProvider = "yt") {
const data = await player.workerJob("generalQuery", { const data = await player.workerJob("generalQuery", {
query: track.query, 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. * Extract Last.fm-relevant info from the player's current track.
* @param {object} player * @private
* @returns {{ artist: string|null, name: string|null, album: string|null, track: object|null } | null} * @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) { function extractCurrentTrack(player) {
const track = player?.queue?.getCurrent(); const track = player?.queue?.getCurrent();
@@ -104,9 +140,11 @@ function extractCurrentTrack(player) {
} }
/** /**
* Get all human member IDs from a guild for whoknows lookups. * Get all non-bot user IDs in a guild.
* @param {object} guild * @private
* @returns {Promise<Array<string>>} * @async
* @param {object} guild - The Discord guild object.
* @returns {Promise<string[]>} Array of user ID strings.
*/ */
async function getGuildLinkedUsers(guild) { async function getGuildLinkedUsers(guild) {
const memberIds = []; const memberIds = [];
@@ -124,10 +162,11 @@ async function getGuildLinkedUsers(guild) {
} }
/** /**
* Parse a period string from token option or message content. * Extract a valid time period from command data or message content.
* @param {object} data * @private
* @param {object} msg * @param {object} data - Parsed command data.
* @returns {string} A valid period string * @param {object} msg - The command message wrapper.
* @returns {string} The period string, defaults to "overall".
*/ */
function extractPeriod(data, msg) { function extractPeriod(data, msg) {
let raw = data.get("token")?.value; 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. * Fetch and play tracks from a Last.fm category (loved, top, recent, albums, artists, playlist).
* Shared between `%lastfm play <cat>` and `%play lastfm:<cat>`. * @async
* * @param {object} ctx - The bot (Remix) instance context.
* @param {object} ctx - The command `this` context (has .lastfm, .getPlayer, .handler, .t) * @param {object} msg - The command message wrapper.
* @param {import("../src/MessageHandler.mjs").Message} msg - The message object * @param {string} userId - The Discord user ID.
* @param {string} userId - The Discord user ID * @param {string} category - The Last.fm category to play.
* @param {string} category - "loved", "top", "recent", or "playlist" * @param {object} [options={}] - Additional options.
* @param {object} [options] * @param {string} [options.resolveProvider="yt"] - Provider to resolve tracks with.
* @param {string} [options.period] - Period for top tracks * @param {string} [options.playlistId] - Playlist number for playlist category.
* @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"
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function playLastFmCategory(ctx, msg, userId, category, options = {}) { 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. * Parse play subcommand arguments for category and provider.
* @returns {{ category: string, playlistId?: string|number }} * @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) { function parsePlayArgs(msg, data) {
let raw = data.get("token")?.value; let raw = data.get("token")?.value;
@@ -337,9 +376,11 @@ function parsePlayArgs(msg, data) {
} }
/** /**
* Execute the lastfm command. * Run handler for the lastfm command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Routes to the appropriate subcommand based on the action option.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing action, user, and token options.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { 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 = "%") { function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") {
const lines = tracks.map((t, i) => { const lines = tracks.map((t, i) => {
const num = String(i + 1).padStart(2, " "); 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!` }); .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) { function buildLeaderboardEmbed(lb, pageIdx, prefix) {
const MEDALS = ["🥇", "🥈", "🥉"]; const MEDALS = ["🥇", "🥈", "🥉"];
const startRank = pageIdx * lb.perPage; const startRank = pageIdx * lb.perPage;
@@ -2499,9 +2558,10 @@ function buildLeaderboardEmbed(lb, pageIdx, prefix) {
} }
/** /**
* Format seconds into mm:ss or h:mm:ss. * Format seconds into a human-readable duration string (h:mm:ss or m:ss).
* @param {number} seconds * @private
* @returns {string} * @param {number} seconds - Duration in seconds.
* @returns {string} Formatted duration, or empty string if invalid.
*/ */
function formatDuration(seconds) { function formatDuration(seconds) {
if (!seconds || seconds <= 0) return ""; if (!seconds || seconds <= 0) return "";
+44 -46
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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
import { getGlobalColor, cleanId } from "../src/MessageHandler.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() export const command = new CommandBuilder()
.setName("leave") .setName("leave")
.setDescription("Make the bot leave a voice channel", "commands.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) { function resolvePlayerGuildId(player, mapKey, client) {
const direct = cleanId(player?._guildId); const direct = cleanId(player?._guildId);
if (direct) return direct; if (direct) return direct;
@@ -30,9 +38,11 @@ function resolvePlayerGuildId(player, mapKey, client) {
} }
/** /**
* Execute the leave command. * Run handler for the leave/stop command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Finds the target player, removes 24/7 if enabled, destroys the player,
* @param {Map<string, {value: *}>} data - Slash-command options map * and sends a confirmation message.
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing option values.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { export async function run(msg, data) {
@@ -67,7 +77,7 @@ export async function run(msg, data) {
} }
const channelList = guildPlayers.map(([mapKey, p]) => { const channelList = guildPlayers.map(([mapKey, p]) => {
const id = cleanId(p._channelId ?? mapKey); const id = cleanId(p._channelId ?? mapKey);
return id ? `<#${id}>` : "`unknown`"; return id ? `<#${id}>` : "\`unknown\`";
}); });
return msg.reply( return msg.reply(
this.t(msg, "responses.leave.specifyChannel", { this.t(msg, "responses.leave.specifyChannel", {
@@ -89,7 +99,7 @@ export async function run(msg, data) {
} }
const channelList = guildPlayers.map(([mapKey, p]) => { const channelList = guildPlayers.map(([mapKey, p]) => {
const id = cleanId(p._channelId ?? mapKey); const id = cleanId(p._channelId ?? mapKey);
return id ? `<#${id}>` : "`unknown`"; return id ? `<#${id}>` : "\`unknown\`";
}); });
return msg.reply( return msg.reply(
this.t(msg, "responses.leave.noPlayerInChannel", { this.t(msg, "responses.leave.noPlayerInChannel", {
@@ -104,6 +114,8 @@ export async function run(msg, data) {
const activeChannelId = cleanId(player._channelId) || targetChannelId; const activeChannelId = cleanId(player._channelId) || targetChannelId;
const homeChannelId = cleanId(player._home247Channel) || activeChannelId; 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 set = this.getSettings(msg);
const raw = set?.get("stay_247"); const raw = set?.get("stay_247");
const ch247 = (!raw || raw === "none") const ch247 = (!raw || raw === "none")
@@ -112,44 +124,30 @@ export async function run(msg, data) {
? new Set(raw.map(id => cleanId(id)).filter(Boolean)) ? new Set(raw.map(id => cleanId(id)).filter(Boolean))
: new Set([cleanId(raw)]); : new Set([cleanId(raw)]);
const is247 = ch247.has(activeChannelId) || ch247.has(homeChannelId); const was247 = ch247.has(activeChannelId) || ch247.has(homeChannelId);
if (is247) { if (was247) {
const matchChannel = ch247.has(homeChannelId) ? homeChannelId const target = ch247.has(activeChannelId) ? activeChannelId : homeChannelId;
: ch247.has(activeChannelId) ? activeChannelId ch247.delete(target);
: null; set.set("stay_247", ch247.size > 0 ? [...ch247] : "none");
const mode = matchChannel ? get247ChannelMode(set, matchChannel) : "off";
const prefix = this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id);
this.markIntentionalLeave(activeChannelId);
this.players.playerMap.delete(activeChannelId);
this.players._unindexPlayer(player._guildId, activeChannelId);
if (activeChannelId !== targetChannelId) this.players.playerMap.delete(targetChannelId);
if (homeChannelId !== activeChannelId) this.players.playerMap.delete(homeChannelId);
const pendingScrobble = this.players._pendingScrobbleTimers?.get(activeChannelId);
if (pendingScrobble) {
clearTimeout(pendingScrobble.timer);
this.players._pendingScrobbleTimers.delete(activeChannelId);
}
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);
} }
// 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);
if (activeChannelId !== targetChannelId) this.players.playerMap.delete(targetChannelId);
if (homeChannelId !== activeChannelId) this.players.playerMap.delete(homeChannelId);
const pendingScrobble = this.players._pendingScrobbleTimers?.get(activeChannelId);
if (pendingScrobble) {
clearTimeout(pendingScrobble.timer);
this.players._pendingScrobbleTimers.delete(activeChannelId);
}
await player.leave().catch(() => {});
player.destroy();
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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,6 +10,10 @@ import { EmbedBuilder } from "@fluxerjs/core";
const PAGE_SIZE = 10; const PAGE_SIZE = 10;
const SESSION_MS = 30 * 1000; const SESSION_MS = 30 * 1000;
/**
* @type {CommandBuilder}
* @description Command definition for the list (queue) command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("list") .setName("list")
.setDescription("List the songs in the queue of your current voice channel.", "commands.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. * Run handler for the list command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Displays the current queue with pagination, showing now-playing info and track list.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing the page option.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(message, data) { 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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the loop command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("loop") .setName("loop")
.setDescription("Toggle the looping of your queue/song.", "commands.loop") .setDescription("Toggle the looping of your queue/song.", "commands.loop")
@@ -18,9 +19,11 @@ export const command = new CommandBuilder()
.setRequired(true)); .setRequired(true));
/** /**
* Execute the loop command. * @async
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Run handler for the loop command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(message, data) { 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,18 +10,24 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { Utils } from "../src/Utils.mjs"; import { Utils } from "../src/Utils.mjs";
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
/** @type {CommandBuilder} @description Command definition for the lyrics command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("lyrics") .setName("lyrics")
.setDescription("Display synced lyrics from NodeLink", "commands.lyrics") .setDescription("Display synced lyrics from NodeLink", "commands.lyrics")
.addAliases("lyric", "ly") .addAliases("lyric", "ly")
.setCategory("music"); .setCategory("music");
/** @private @type {string[]} Loading animation frames. */
const LOADING_FRAMES = ["◐", "◓", "◑", "◒"]; const LOADING_FRAMES = ["◐", "◓", "◑", "◒"];
/** @private @type {number} Session timeout in milliseconds (3 minutes). */
const SESSION_MS = 180_000; const SESSION_MS = 180_000;
/** /**
* Execute the lyrics command. * @async
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * 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>} * @returns {Promise<void>}
*/ */
export async function run(message) { export async function run(message) {
@@ -126,6 +132,13 @@ export async function run(message) {
let currentPage = 0; let currentPage = 0;
let emojiRemoveTimeout; 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 buildContent = (pageIdx, expired = false) => {
const headerLine = `by *${artist}*${syncIndicator} • Page ${pageIdx + 1}/${totalPages}`; const headerLine = `by *${artist}*${syncIndicator} • Page ${pageIdx + 1}/${totalPages}`;
const descBody = pages[pageIdx]; const descBody = pages[pageIdx];
@@ -150,6 +163,11 @@ export async function run(message) {
await msg.message.react(emoji).catch(() => {}); await msg.message.react(emoji).catch(() => {});
} }
/**
* @private
* Remove all navigation reactions from the lyrics message.
* @returns {Promise<void>}
*/
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await msg.message.removeAllReactions(); 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 = () => { const resetEmojiTimer = () => {
clearTimeout(emojiRemoveTimeout); clearTimeout(emojiRemoveTimeout);
emojiRemoveTimeout = setTimeout(async () => { 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the move command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("move") .setName("move")
.setDescription("Move a track from one position to another in the queue.", "commands.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. * @async
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Run handler for the move command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(message, data) { 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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the np (now playing) command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("np") .setName("np")
.setDescription("Request the name and url of the currently playing song.", "commands.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. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg) { 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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the pause command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("pause") .setName("pause")
.setDescription("Pause the playback in your voice channel", "commands.pause") .setDescription("Pause the playback in your voice channel", "commands.pause")
.setCategory("music"); .setCategory("music");
/** /**
* Execute the pause command. * @async
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Run handler for the pause command.
* Pauses playback in the user's voice channel.
* @param {object} message - The command message wrapper.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(message) { 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"; 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"]; const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
/** /**
* Parse a lastfm query like "td:top", "sp:loved", "playlist 1", or just "top". * Parse a Last.fm sub-provider string (e.g. "lf:loved", "sp:top").
* Returns { category, resolveProvider } where resolveProvider is the * @private
* search provider to use for resolving tracks (e.g. "td" for Tidal). * @param {string} query - The raw query string to parse.
* @returns {{ category: string, resolveProvider: string|null, invalidCategory?: string }} Parsed components.
*/ */
function parseLastFmSubProvider(query) { function parseLastFmSubProvider(query) {
const value = query.trim(); 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) { function parseLastFmTrackQuery(raw) {
const value = String(raw ?? "").trim(); const value = String(raw ?? "").trim();
if (!value) return null; if (!value) return null;
@@ -86,6 +95,10 @@ function parseLastFmTrackQuery(raw) {
return null; return null;
} }
/**
* @type {CommandBuilder}
* @description Command definition for the play command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("play") .setName("play")
.setId("play") .setId("play")
@@ -125,9 +138,11 @@ export const command = new CommandBuilder()
.addAlias("p"); .addAlias("p");
/** /**
* Execute the play command. * Run handler for the play command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Handles URL detection, Last.fm integration, provider selection, and track searching.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing query and provider options.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(message, data) { 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"; 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 { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the player command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("player") .setName("player")
.setDescription("Create an interactive player control panel with live progress", "commands.player") .setDescription("Create an interactive player control panel with live progress", "commands.player")
.setCategory("music"); .setCategory("music");
/** @private @type {Object.<string, string>} Emoji indicators for player states. */
const STATES = { const STATES = {
playing: "🎵", playing: "🎵",
paused: "⏸️", paused: "⏸️",
@@ -22,6 +25,7 @@ const STATES = {
loading: "⏳" loading: "⏳"
}; };
/** @private @type {Object.<string, {emoji: string, action: string, desc: string}>} Available control button definitions. */
const CONTROLS = { const CONTROLS = {
prev: { emoji: "⏮️", action: "previous", desc: "Previous" }, prev: { emoji: "⏮️", action: "previous", desc: "Previous" },
play: { emoji: "▶️", action: "resume", desc: "Play" }, play: { emoji: "▶️", action: "resume", desc: "Play" },
@@ -37,6 +41,7 @@ const CONTROLS = {
close: { emoji: "❌", action: "close", desc: "Close" } close: { emoji: "❌", action: "close", desc: "Close" }
}; };
/** @private @type {Object.<string, string>} Progress bar character set. */
const PROGRESS = { const PROGRESS = {
filled: "▰", filled: "▰",
empty: "▱", empty: "▱",
@@ -47,8 +52,11 @@ const PROGRESS = {
/** /**
* Execute the player command. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg) { export async function run(msg) {
@@ -65,6 +73,12 @@ export async function run(msg) {
const allControls = controlsLayout.flat(); const allControls = controlsLayout.flat();
const controlEmojis = allControls.map(c => c.emoji); 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 buildEmbed = (state = {}) => {
const current = player.queue.getCurrent(); const current = player.queue.getCurrent();
const isPlaying = !player.paused && current; const isPlaying = !player.paused && current;
@@ -162,6 +176,11 @@ export async function run(msg) {
let lyricsUnobserve = null; let lyricsUnobserve = null;
let lyricsEmojiTimeout = null; let lyricsEmojiTimeout = null;
/**
* @private
* Remove all control reactions from the player panel message.
* @returns {Promise<void>}
*/
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await message.message.removeAllReactions(); 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 = () => { const resetEmojiTimer = () => {
clearTimeout(emojiRemoveTimeout); clearTimeout(emojiRemoveTimeout);
emojiRemoveTimeout = setTimeout(async () => { emojiRemoveTimeout = setTimeout(async () => {
@@ -184,6 +208,12 @@ export async function run(msg) {
}, EMOJI_REMOVE_TIMEOUT); }, 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) => { const clearLyricsReactions = async (lyricsMsg) => {
if (!lyricsMsg?.message) return; if (!lyricsMsg?.message) return;
try { 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 refresh = (extra = {}) => {
const embed = buildEmbed(extra); const embed = buildEmbed(extra);
message.edit({ embeds: [embed] }).catch(() => {}); message.edit({ embeds: [embed] }).catch(() => {});
@@ -205,6 +241,14 @@ export async function run(msg) {
let _sessionClosed = false; 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") => { const closeSession = async (reason = "timeout") => {
if (_sessionClosed) return; if (_sessionClosed) return;
_sessionClosed = true; _sessionClosed = true;
@@ -245,6 +289,11 @@ export async function run(msg) {
}).catch(() => {}); }).catch(() => {});
}; };
/**
* @private
* Reset the session inactivity timeout timer.
* @returns {void}
*/
const resetTimeout = () => { const resetTimeout = () => {
clearTimeout(sessionTimeout); clearTimeout(sessionTimeout);
sessionTimeout = setTimeout(() => closeSession("timeout"), timeout); sessionTimeout = setTimeout(() => closeSession("timeout"), timeout);
@@ -315,7 +364,6 @@ export async function run(msg) {
break; break;
case "stop": case "stop":
await player._stopMediaPlayer();
player.queue.reset(); player.queue.reset();
reply = this.t(msg, "responses.player.stoppedCleared"); reply = this.t(msg, "responses.player.stoppedCleared");
break; 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"; 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"; import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the playnext command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("playnext") .setName("playnext")
.setId("playnext") .setId("playnext")
@@ -34,9 +39,11 @@ export const command = new CommandBuilder()
.addAlias("pn"); .addAlias("pn");
/** /**
* Execute the playnext command. * Run handler for the playnext command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Searches for a track and adds the result to the top of the queue.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing query and provider options.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(message, data) { 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"; 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"; 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() { export const command = function() {
if (!this.config.radio?.length) return null; if (!this.config.radio?.length) return null;
return new CommandBuilder() return new CommandBuilder()
@@ -25,9 +29,11 @@ export const command = function() {
}; };
/** /**
* Execute the radio command. * Run handler for the radio command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Lists stations, plays a named station, or starts the default station.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the station option.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { export async function run(msg, data) {
@@ -131,6 +137,16 @@ export async function run(msg, data) {
return playStation(this, msg, radios[0]); 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) { async function playStation(ctx, msg, radio, editTarget = null) {
const p = await ctx.getPlayer(msg, true, true, true); const p = await ctx.getPlayer(msg, true, true, true);
if (!p) return; 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,6 +10,10 @@ import fs from "node:fs";
import path from "node:path"; import path from "node:path";
import { pathToFileURL } from "node:url"; import { pathToFileURL } from "node:url";
/**
* @type {CommandBuilder}
* @description Command definition for the reload command (owner-only).
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("reload") .setName("reload")
.setDescription("Reload commands, src modules, or audio modules. Leave blank to see all targets.") .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 __dirname = path.dirname(new URL(import.meta.url).pathname);
const ROOT = path.resolve(__dirname, ".."); 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) { async function reloadCommand(ctx, msg, name) {
if (name === "index") if (name === "index")
return { ok: false, msg: ctx.t(msg, "responses.reload.indexNoReload") }; 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 }) }; 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) { async function reloadModule(ctx, msg, filePath, label) {
if (!fs.existsSync(filePath)) if (!fs.existsSync(filePath))
return { ok: false, msg: ctx.t(msg, "responses.reload.fileNotFound", { label }) }; 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) { function allModuleFiles(subdir) {
const dir = path.join(ROOT, subdir); const dir = path.join(ROOT, subdir);
if (!fs.existsSync(dir)) return []; if (!fs.existsSync(dir)) return [];
@@ -80,6 +109,16 @@ function allModuleFiles(subdir) {
.map(f => ({ file: path.join(dir, f), label: `${subdir}/${f}` })); .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) { async function showPaged(msg, title, lines, pageSize = 14) {
const pages = []; const pages = [];
for (let i = 0; i < lines.length; i += pageSize) 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); 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) { async function showResults(msg, results, label) {
const ok = results.filter(r => r.ok).length; const ok = results.filter(r => r.ok).length;
const bad = 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. * Run handler for the reload command.
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Reloads commands, src modules, or audio modules based on the target option.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} msg - The command message wrapper.
* @param {object} data - Parsed command data containing the target option.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the remove command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("remove") .setName("remove")
.setDescription("Remove a specific song from the queue.", "commands.remove") .setDescription("Remove a specific song from the queue.", "commands.remove")
@@ -15,9 +16,11 @@ export const command = new CommandBuilder()
.setRequired(true)); .setRequired(true));
/** /**
* Execute the remove command. * @async
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Run handler for the remove command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(message, data) { 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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the resume command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("resume") .setName("resume")
.setDescription("Resume the playback in your voice channel", "commands.resume") .setDescription("Resume the playback in your voice channel", "commands.resume")
.setCategory("music"); .setCategory("music");
/** /**
* Execute the resume command. * Run handler for the resume command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Resumes playback and sends a confirmation embed.
*
* @param {object} message - The command message wrapper.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(message) { 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"; 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 { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/constants/UI.mjs";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the search command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("search") .setName("search")
.setDescription( .setDescription(
@@ -37,9 +38,12 @@ export const command = new CommandBuilder()
); );
/** /**
* Execute the search command. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Run handler for the search command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { export async function run(msg, data) {
@@ -57,10 +61,12 @@ export async function run(msg, data) {
if (!channel?.send) return; if (!channel?.send) return;
/** /**
* Build a search-result embed using EmbedBuilder. * @private
* @param {string} description * Build a search result embed.
* @param {string} [footerText] * @param {string} description - The embed description text.
* @param {string} [authorLabel] - defaults to `name` (provider name) * @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 makeEmbed = (description, footerText, authorLabel = name) => {
const b = new EmbedBuilder() 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 channelId = rawMsg.channelId ?? rawMsg.channel_id ?? rawMsg.channel?.id;
const msgId = rawMsg.id; const msgId = rawMsg.id;
/**
* @private
* Remove all reactions from the search result message.
* @returns {Promise<void>}
*/
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await rawMsg.removeAllReactions(); 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,6 +9,7 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { Utils } from "../src/Utils.mjs"; import { Utils } from "../src/Utils.mjs";
import { ERROR_COLOR } from "../src/constants/UI.mjs"; import { ERROR_COLOR } from "../src/constants/UI.mjs";
/** @type {CommandBuilder} @description Command definition for the seek command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("seek") .setName("seek")
.setDescription("Seek to a specific position in the current track.", "commands.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. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Run handler for the seek command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { 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"; 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 { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the servers command (owner-only). */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("servers") .setName("servers")
.setDescription("Fetch a list of servers the bot is in") .setDescription("Fetch a list of servers the bot is in")
@@ -17,8 +18,10 @@ export const command = new CommandBuilder()
/** /**
* Execute the servers command. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg) { export async function run(msg) {
@@ -60,6 +63,13 @@ export async function run(msg) {
let currentPage = 0; 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 buildPageContent = (pageIdx, expired = false) => {
const embed = new EmbedBuilder() const embed = new EmbedBuilder()
.setColor(getGlobalColor()) .setColor(getGlobalColor())
@@ -90,6 +100,11 @@ export async function run(msg) {
await replyMsg.message.react(emoji).catch(() => {}); await replyMsg.message.react(emoji).catch(() => {});
} }
/**
* @private
* Remove all navigation reactions from the reply message.
* @returns {Promise<void>}
*/
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await replyMsg.message.removeAllReactions(); await replyMsg.message.removeAllReactions();
@@ -102,6 +117,11 @@ export async function run(msg) {
} }
}; };
/**
* @private
* Reset the emoji removal timeout timer.
* @returns {void}
*/
const resetTimer = () => { const resetTimer = () => {
clearTimeout(emojiTimeout); clearTimeout(emojiTimeout);
emojiTimeout = setTimeout(async () => { emojiTimeout = setTimeout(async () => {
+346 -428
View File
File diff suppressed because it is too large. Load diff
+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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the shuffle command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("shuffle") .setName("shuffle")
.setDescription("Re-orders the queue randomly.", "commands.shuffle") .setDescription("Re-orders the queue randomly.", "commands.shuffle")
.setCategory("music"); .setCategory("music");
/** /**
* Execute the shuffle command. * Run handler for the shuffle command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Shuffles the queue and sends a confirmation embed.
*
* @param {object} message - The command message wrapper.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(message) { 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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the skip command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("skip") .setName("skip")
.setDescription("Skip the current playing song.", "commands.skip") .setDescription("Skip the current playing song.", "commands.skip")
@@ -14,8 +15,10 @@ export const command = new CommandBuilder()
.setCategory("music"); .setCategory("music");
/** /**
* Execute the skip command. * @async
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * 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>} * @returns {Promise<void>}
*/ */
export async function run(message) { 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,6 +9,10 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the stats command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("stats") .setName("stats")
.setDescription("Display stats about the bot like the uptime.", "commands.stats") .setDescription("Display stats about the bot like the uptime.", "commands.stats")
@@ -21,6 +25,13 @@ let cachedUserCount = null;
let cacheExpiresAt = 0; let cacheExpiresAt = 0;
let inflightPromise = null; 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) { async function pool(limit, tasks) {
const results = []; const results = [];
const executing = new Set(); const executing = new Set();
@@ -33,6 +44,13 @@ async function pool(limit, tasks) {
return results; 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) { async function fetchGuildMemberCount(guild) {
try { try {
let after = undefined; 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) { async function refreshUserCount(client) {
const guilds = [...client.guilds.values()]; const guilds = [...client.guilds.values()];
const counts = await pool(10, guilds.map(g => () => fetchGuildMemberCount(g))); const counts = await pool(10, guilds.map(g => () => fetchGuildMemberCount(g)));
@@ -67,12 +92,24 @@ async function refreshUserCount(client) {
return cachedUserCount; 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) { function getUserCount(client) {
if (cachedUserCount !== null && Date.now() < cacheExpiresAt) return Promise.resolve(cachedUserCount); if (cachedUserCount !== null && Date.now() < cacheExpiresAt) return Promise.resolve(cachedUserCount);
if (!inflightPromise) inflightPromise = refreshUserCount(client); if (!inflightPromise) inflightPromise = refreshUserCount(client);
return inflightPromise; 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) { function getLivePlayerCount(playerMap) {
let live = 0; let live = 0;
@@ -101,6 +138,13 @@ function getLivePlayerCount(playerMap) {
let cachedGuildCount = null; let cachedGuildCount = null;
let guildCacheExpiresAt = 0; 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) { async function getGuildCount(client) {
if (cachedGuildCount !== null && Date.now() < guildCacheExpiresAt) { if (cachedGuildCount !== null && Date.now() < guildCacheExpiresAt) {
return cachedGuildCount; 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 }) { function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) {
const num = (v) => Utils.formatNumber(v); const num = (v) => Utils.formatNumber(v);
const ld = (v) => loading ? "..." : v; const ld = (v) => loading ? "..." : v;
@@ -171,8 +236,11 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount,
} }
/** /**
* Execute the stats command. * Run handler for the stats command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * 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>} * @returns {Promise<void>}
*/ */
export async function run(message) { 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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the support command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("support") .setName("support")
.setDescription("The support server for Remix. Feel free to ask help, report bugs or just chat :)", "commands.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"); .setCategory("util");
/** /**
* run function. * Run handler for the support command.
* @param {object} msg * Sends an embed with the support server link.
* @param {object} msg - The command message wrapper.
* @returns {void} * @returns {void}
*/ */
export function run(msg) { 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -8,15 +8,19 @@ import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the test command (owner-only). */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("test") .setName("test")
.setDescription("Shows how many people are in each voice channel.") .setDescription("Shows how many people are in each voice channel.")
.setCategory("util")
.setRequirement(r => r.setOwnerOnly(true)); .setRequirement(r => r.setOwnerOnly(true));
/** /**
* Execute the test command. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Run handler for the test command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { export async function run(msg, data) {
@@ -54,6 +58,13 @@ export async function run(msg, data) {
return msg.reply({ embeds: [embed] }); 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 getChannelName = async (channelId) => {
const cached = this.client.channels.get(channelId); const cached = this.client.channels.get(channelId);
if (cached?.name) return cached.name; 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 { CommandBuilder } from "../src/CommandHandler.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../src/MessageHandler.mjs"; import { getGlobalColor } from "../src/MessageHandler.mjs";
/** @type {CommandBuilder} @description Command definition for the thumbnail command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("thumbnail") .setName("thumbnail")
.setDescription("Request the thumbnail of the currently playing song.", "commands.thumbnail") .setDescription("Request the thumbnail of the currently playing song.", "commands.thumbnail")
@@ -14,8 +15,10 @@ export const command = new CommandBuilder()
.setCategory("music"); .setCategory("music");
/** /**
* Execute the thumbnail command. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg) { 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -10,8 +10,10 @@ import { Utils } from "../src/Utils.mjs";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
import { ERROR_COLOR } from "../src/constants/UI.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"; const DEFAULT_ALIAS = "default";
/** @type {CommandBuilder} @description Command definition for the trackopt command with subcommands. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("trackopt") .setName("trackopt")
.setDescription("Set custom start/end times for tracks. Supports named aliases — save multiple trims per track for different sections.", "commands.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"); .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) { function extractAlias(parts) {
for (let i = 0; i < parts.length; i++) { for (let i = 0; i < parts.length; i++) {
if (parts[i].toLowerCase().startsWith("alias:")) { if (parts[i].toLowerCase().startsWith("alias:")) {
@@ -70,9 +78,11 @@ function extractAlias(parts) {
} }
/** /**
* Execute the trackopt command. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Run handler for the trackopt command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,6 +9,10 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { MAX_VOLUME } from "../src/constants/UI.mjs"; import { MAX_VOLUME } from "../src/constants/UI.mjs";
/**
* @type {CommandBuilder}
* @description Command definition for the volume command.
*/
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("volume") .setName("volume")
.setDescription("Get or change the current volume.", "commands.volume") .setDescription("Get or change the current volume.", "commands.volume")
@@ -21,9 +25,11 @@ export const command = new CommandBuilder()
.addAliases("v", "vol"); .addAliases("v", "vol");
/** /**
* Execute the volume command. * Run handler for the volume command.
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Displays the current volume or sets it to a new value.
* @param {Map<string, {value: *}>} data - Slash-command options map *
* @param {object} message - The command message wrapper.
* @param {object} data - Parsed command data containing the volume option.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
export async function run(message, data) { 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"; import { CommandBuilder } from "../src/CommandHandler.mjs";
@@ -9,7 +9,7 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { PermissionFlags } from "@fluxerjs/core"; import { PermissionFlags } from "@fluxerjs/core";
import { MAX_VOLUME } from "../src/constants/UI.mjs"; import { MAX_VOLUME } from "../src/constants/UI.mjs";
/** @type {CommandBuilder} @description Command definition for the volumedefault command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("volumedefault") .setName("volumedefault")
.setDescription("View or set the server default volume. (Requires Manage Server to set)", "commands.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"); .addAliases("vd");
/** /**
* Execute the volumedefault command. * @async
* @param {import("../src/MessageHandler.mjs").Message} message - The incoming message * Run handler for the volumedefault command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(message, data) { 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"; 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 { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
/** @type {CommandBuilder} @description Command definition for the vote command. */
export const command = new CommandBuilder() export const command = new CommandBuilder()
.setName("vote") .setName("vote")
.setDescription("View voting info or check voters for your server/bot on FluxerList", "commands.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) .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) { function notConfigured(t, guildId) {
return { return {
embeds: [new EmbedBuilder() 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) { function noResourceId(type, prefix, t, guildId) {
return { return {
embeds: [new EmbedBuilder() embeds: [new EmbedBuilder()
@@ -57,15 +73,18 @@ function noResourceId(type, prefix, t, guildId) {
} }
/** /**
* Build a paginated voter list embed. * @private
* @param {Array<{ username: string, fluxerId: number, votedAt: string }>} voters * Build a paginated voters embed with ranked voter list.
* @param {number} total * @param {Array<object>} voters - Array of voter objects.
* @param {number} page * @param {number} total - Total number of voters across all pages.
* @param {number} limit * @param {number} page - Current page number (1-based).
* @param {"server"|"bot"} type * @param {number} limit - Voters per page.
* @param {string} resourceId * @param {string} type - Resource type ("server" or "bot").
* @param {boolean} expired - Whether the navigation controls have expired * @param {string} resourceId - The server or bot ID.
* @returns {object} Embed payload * @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) { function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired = false, t, guildId) {
const totalPages = Math.max(1, Math.ceil(total / limit)); 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. * @async
* @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message * Run handler for the vote command.
* @param {Map<string, {value: *}>} data - Slash-command options map * 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>} * @returns {Promise<void>}
*/ */
export async function run(msg, data) { export async function run(msg, data) {
@@ -191,6 +212,14 @@ export async function run(msg, data) {
let currentPage = voterData.page; 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) => { const buildPage = (pageIdx, data, expired = false) => {
return buildVotersEmbed(data.voters, data.total, pageIdx, 20, resolvedType, id, expired, t, guildId); 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(() => {}); await replyMsg.message.react(emoji).catch(() => {});
} }
/**
* @private
* Remove all navigation reactions from the voter list message.
* @returns {Promise<void>}
*/
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await replyMsg.message.removeAllReactions(); await replyMsg.message.removeAllReactions();
@@ -214,6 +248,11 @@ export async function run(msg, data) {
}; };
let emojiTimeout = null; let emojiTimeout = null;
/**
* @private
* Reset the emoji removal timeout timer for the voter pagination session.
* @returns {void}
*/
const resetTimer = () => { const resetTimer = () => {
clearTimeout(emojiTimeout); clearTimeout(emojiTimeout);
emojiTimeout = setTimeout(async () => { emojiTimeout = setTimeout(async () => {
+6 -25
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", "token": "your bot token",
"fluxer.js": { "fluxer.js": {
"rest": { "rest": {
@@ -8,9 +8,6 @@
"retries": 3 "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 %)", "prefix": "your desired prefix (such as %)",
"presenceInterval": null, "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.", "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 } "activity": { "name": "RedTech & NoLogicAlan", "type": 2 }
} }
], ],
"spotify": {
"clientId": "your spotify client id",
"clientSecret": "your spotify client secret"
},
"nodelink": { "nodelink": {
"host": "localhost", "host": "localhost",
"port": 3000, "port": 3000,
"password": "youshallnotpass", "password": "youshallnotpass",
"requestTimeout": 60000, "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": { "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:", "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": [], "radio": [],
"helpCatalog": true,
"helpPagination": true,
"mysql": { "mysql": {
"host": "your-mysql-host.com", "host": "your-mysql-host.com",
"port": 3306, "port": 3306,
@@ -68,22 +59,13 @@
"password": "password of your user", "password": "password of your user",
"database": "name of the target database" "database": "name of the target database"
}, },
"webPort": 80,
"dashboard": { "dashboard": {
"enabled": false, "enabled": false,
"redis": { "redis": {
"url": "redis://localhost:6379" "url": "redis://localhost:6379"
} },
"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."
}, },
"dashboardUrl": "The url the dashboard is accessible with.",
"ssl": {
"private": "path-to-private-key.pem",
"cert": "path-to-certificate.pem",
"useSSL": false,
"httpPort": 80
},
"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": { "lastfm": {
"Comment": "Last.fm integration: auto-scrobble songs, play loved/top/recent tracks. Register at https://www.last.fm/api/account/create", "Comment": "Last.fm integration: auto-scrobble songs, play loved/top/recent tracks. Register at https://www.last.fm/api/account/create",
"enabled": true, "enabled": true,
@@ -102,7 +84,7 @@
}, },
"owners": ["user id for owner-only commands", "another user id"], "owners": ["user id for owner-only commands", "another user id"],
"playerAFKTimeout": 60000, "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.", "customStatsFooter": "Text shown in the footer of the $prefixstats embed; optional.",
"embedColor": "0xe9196c", "embedColor": "0xe9196c",
"logging": { "logging": {
@@ -119,8 +101,7 @@
"guild": true, "guild": true,
"recovery": false, "recovery": false,
"settings": true, "settings": true,
"worker": false, "lavalink": true,
"moonlink": false,
"dashboard": false, "dashboard": false,
"redis": false "redis": false
}, },
+12 -17
View File
@@ -1,26 +1,21 @@
# Bot token from https://fluxer.app/developers # Docker Compose environment for Remix.
BOT_TOKEN=your_bot_token_here # Copy this file to docker/.env (same folder as docker-compose.yml) and edit.
# MySQL credentials # --- MySQL (used by the mysql service; reference the same values in config.json) ---
MYSQL_ROOT_PASSWORD=change_me_root MYSQL_ROOT_PASSWORD=remix_root_pw
MYSQL_DATABASE=remix MYSQL_DATABASE=remix
MYSQL_USER=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 WEB_PORT=8080
# Port exposed on the host for NodeLink (audio node)
# NodeLink port mapping
NODELINK_PORT=3000 NODELINK_PORT=3000
# Timezone # --- Timezone applied to all containers ---
TZ=UTC TZ=UTC
# Optional: paste your entire config.json as a single line (base64 or raw JSON) # --- Optional: raw JSON config written to /app/config.json on first boot ---
# If set, the entrypoint will write it to /app/config.json on first boot. # Takes precedence over docker/config_example.json when no config.json is mounted.
# CONFIG_JSON={"token":"...","mysql":{...}} # CONFIG_JSON={"token":"YOUR_TOKEN","mysql":{"host":"mysql","port":3306,"user":"remix","password":"remix_pw","database":"remix"},"nodelink":{"host":"nodelink","port":3000,"password":"youshallnotpass"}}
# Fluxer OAuth2 (for dashboard)
FLUXER_OAUTH_ID=
FLUXER_OAUTH_SECRET=
FLUXER_OAUTH_REDIRECT_URI=
+1 -12
View File
@@ -16,10 +16,6 @@
"password": "youshallnotpass", "password": "youshallnotpass",
"requestTimeout": 60000 "requestTimeout": 60000
}, },
"spotify": {
"clientId": "",
"clientSecret": ""
},
"lastfm": { "lastfm": {
"apiKey": "", "apiKey": "",
"apiSecret": "", "apiSecret": "",
@@ -30,14 +26,8 @@
"enabled": false, "enabled": false,
"redis": { "redis": {
"url": "redis://redis:6379" "url": "redis://redis:6379"
},
"fluxer": {
"id": "",
"secret": "",
"redirectUri": ""
} }
}, },
"webPort": 80,
"logging": { "logging": {
"enabled": true, "enabled": true,
"warn": true, "warn": true,
@@ -52,8 +42,7 @@
"guild": true, "guild": true,
"recovery": true, "recovery": true,
"settings": true, "settings": true,
"worker": false, "lavalink": true,
"moonlink": true,
"dashboard": false, "dashboard": false,
"redis": 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 * @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"; import * as fs from "fs";
@@ -15,8 +16,7 @@ import { RemoteSettingsManager } from "./src/Settings.mjs";
import { PlayerManager } from "./src/PlayerManager.mjs"; import { PlayerManager } from "./src/PlayerManager.mjs";
import childProcess from "node:child_process"; import childProcess from "node:child_process";
import { getVoiceManager } from "@fluxerjs/voice"; import { getVoiceManager } from "@fluxerjs/voice";
import { FluxerRevoice } from "./src/constants/FluxerRevoice.mjs"; import { LavalinkManager } from "./src/LavalinkManager.mjs";
import { MoonlinkManager } from "./src/MoonlinkManager.mjs";
import { Dashboard } from "./src/dashboard/Dashboard.mjs"; import { Dashboard } from "./src/dashboard/Dashboard.mjs";
import { Locale } from "./src/constants/Locale.mjs"; import { Locale } from "./src/constants/Locale.mjs";
import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs"; import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs";
@@ -26,13 +26,11 @@ import { FluxerListManager } from "./src/FluxerListManager.mjs";
import { TrackOptionsManager } from "./src/TrackOptionsManager.mjs"; import { TrackOptionsManager } from "./src/TrackOptionsManager.mjs";
/** /**
* Create a backward-compatible "bot view" wrapper around VoiceStateCache. * Create a Map-like view object that proxies bot voice-state lookups
* * through the VoiceStateCache's bot-specific methods.
* The old code used separate Maps for observedVoiceUsers and observedVoiceBots. * @param {object} voiceCache - The {@link VoiceStateCache} instance.
* VoiceStateCache merged both into one object, but the default iterator/size * @returns {Map} A Map-like object with `size`, `get`, `set`, `has`, `delete`,
* only exposes human users. This wrapper provides the Map-like interface that * `forEach`, and iterator methods backed by the voice cache.
* iterates BOT entries instead, so code that does `for (const [k, v] of observedVoiceBots)`
* still gets bot data, not human data.
*/ */
function createBotView(voiceCache) { function createBotView(voiceCache) {
return { 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 { 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() { constructor() {
let config; let config;
try { try {
@@ -77,7 +82,7 @@ export class Remix {
setGlobalColor(config.embedColor); setGlobalColor(config.embedColor);
this.locale = new Locale(); this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
this.locale.load(); this.locale.load();
this.dashboard = new Dashboard(this, { this.dashboard = new Dashboard(this, {
@@ -214,8 +219,8 @@ export class Remix {
}; };
commands.owners = config.owners ?? []; commands.owners = config.owners ?? [];
this.moonlink = null; this.lavalink = null;
let moonlinkInitialised = false; let lavalinkInitialised = false;
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 }); this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
@@ -252,32 +257,24 @@ export class Remix {
const cleaned = rawArr const cleaned = rawArr
.map(id => cleanId(id)) .map(id => cleanId(id))
.filter(id => id.length >= 15 && id.length <= 22); .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); const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val);
if (needsSave || !Array.isArray(val)) { if (needsSave || !Array.isArray(val)) {
const newVal = cleaned.length > 0 ? cleaned : "none"; const newVal = cleaned.length > 0 ? cleaned : "none";
serverSettings.set("stay_247", newVal); serverSettings.set("stay_247", newVal);
if (cleaned.length === 0 && (val && val !== "none")) {
serverSettings.set("stay_247_mode", "off");
}
logger.settings( logger.settings(
`[settings] Cleaned stay_247 for guild ${guildId}: ${JSON.stringify(val)} → ${JSON.stringify(newVal)}` `[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.dashboard.setBotId(botId);
this.trackOptions.setBotId(botId); this.trackOptions.setBotId(botId);
if (!moonlinkInitialised) { if (!lavalinkInitialised) {
moonlinkInitialised = true; lavalinkInitialised = true;
this.moonlink = new MoonlinkManager(config.nodelink ?? {}, client); this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" });
this.lavalink.on("ready", () => {
this.moonlink.on("ready", (sessionId) => { logger.lavalink("[Lavalink] Session ready");
logger.moonlink(`[Moonlink] Session ready: ${sessionId}`);
for (const player of this.players?.playerMap?.values() ?? []) {
player._nl.sessionId = sessionId;
}
this.playerContext.moonlink = this.moonlink;
}); });
await this.lavalink.init();
try { this.playerContext.lavalink = this.lavalink;
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);
}
} }
this.gatewayHandler.onReady(); this.gatewayHandler.onReady();
@@ -348,15 +329,12 @@ export class Remix {
} }
}); });
this.revoice = FluxerRevoice.getInstance(client);
client._remix = this; client._remix = this;
this.playerContext = { this.playerContext = {
client: this.client, client: this.client,
config, config,
nodelink: config.nodelink, lavalink: null,
moonlink: null,
revoice: this.revoice,
}; };
this.players = new PlayerManager(settings, commands, { this.players = new PlayerManager(settings, commands, {
config, config,
@@ -616,18 +594,9 @@ export class Remix {
} }
/** /**
* Attach error handlers on all @fluxerjs/ws shard WebSockets. * Attach proactive error handlers to WebSocket sockets/shards to prevent
* * unhandled crashes from WebSocket transport errors. Re-armed periodically.
* When the Fluxer gateway's underlying WebSocket closes (e.g. network * @private
* 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.
*/ */
_attachWsErrorHandlers() { _attachWsErrorHandlers() {
try { 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) { markIntentionalLeave(channelId, ttlMs = null) {
const cleanChId = cleanId(channelId); const cleanChId = cleanId(channelId);
if (!cleanChId) return; if (!cleanChId) return;
@@ -716,12 +691,12 @@ export class Remix {
} }
/** /**
* Spawn a player for a voice channel without requiring a user message. * Spawn a new Player for a channel. Used by 24/7 boot recovery and enable247.
* Used by the 24/7 settings command and the leave command's auto-rejoin. * Guards against duplicate players, missing channels, and pending joins.
* * @param {string} guildId - The guild ID.
* @param {string} guildId — The guild ID * @param {string} channelId - The target voice channel ID.
* @param {string} channelId — The voice channel ID to join * @returns {Promise<Player>} The spawned and connected player.
* @returns {Promise<Player>} The created player * @throws {Error} If channel not found, not a voice channel, or join fails.
*/ */
async _spawnPlayer(guildId, channelId) { async _spawnPlayer(guildId, channelId) {
const cleanGuildId = cleanId(guildId); const cleanGuildId = cleanId(guildId);
@@ -733,7 +708,7 @@ export class Remix {
?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId); ?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId);
if (existing) return existing; 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); const channel = this.client?.channels?.get?.(cleanChannelId);
if (!channel) throw new Error("Channel not found"); if (!channel) throw new Error("Channel not found");
@@ -748,9 +723,7 @@ export class Remix {
const player = new Player(this.config.token, { const player = new Player(this.config.token, {
client: this.client, client: this.client,
config: this.config, config: this.config,
nodelink: this.config.nodelink, lavalink: this.lavalink ?? null,
moonlink: this.moonlink ?? null,
revoice: this.revoice ?? null,
settingsMgr: this.settingsMgr ?? this.settings ?? null, settingsMgr: this.settingsMgr ?? this.settings ?? null,
getPrefix: (guildId) => this.handler.getPrefix(guildId), getPrefix: (guildId) => this.handler.getPrefix(guildId),
observedVoiceUsers: this.observedVoiceUsers ?? null, observedVoiceUsers: this.observedVoiceUsers ?? null,
@@ -768,8 +741,8 @@ export class Remix {
player.on("autoleave", () => { player.on("autoleave", () => {
const mode = player._get247Mode(); const mode = player._get247Mode();
if (mode === "auto" || mode === "on") { if (mode === "on") {
logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 ${mode} channel ${cleanChannelId} (guild ${cleanGuildId})`); logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 channel ${cleanChannelId} (guild ${cleanGuildId})`);
return; return;
} }
if (player._hasHumansInChannel()) { 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) { async leaveChannel(channelId, guildId, message, force = false) {
const cleanChId = cleanId(channelId); const cleanChId = cleanId(channelId);
const cleanGuildId = cleanId(guildId); const cleanGuildId = cleanId(guildId);
@@ -887,24 +869,6 @@ export class Remix {
? new Set(raw.map(id => cleanId(id)).filter(Boolean)) ? new Set(raw.map(id => cleanId(id)).filter(Boolean))
: new Set([cleanId(raw)]); : 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)) { if (channels.has(cleanChId)) {
channels.delete(cleanChId); channels.delete(cleanChId);
set.set("stay_247", channels.size > 0 ? [...channels] : "none"); set.set("stay_247", channels.size > 0 ? [...channels] : "none");
@@ -931,18 +895,22 @@ export class Remix {
return true; 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) { getSettings(message) {
const guildId = message?.channel?.channel?.guildId ?? message?.guildId ?? null; const guildId = message?.channel?.channel?.guildId ?? message?.guildId ?? null;
return this.settingsMgr.getServer(guildId); return this.settingsMgr.getServer(guildId);
} }
/** /**
* Translate a key for the guild of the given message. * Shorthand to translate a locale key for the guild of a given message.
* @param {import("./src/MessageHandler.mjs").Message} message * @param {object} message - The message wrapper (used to resolve guild ID).
* @param {string} key * @param {string} key - The locale key.
* @param {Object} [data={}] * @param {object} [data={}] - Interpolation data.
* @returns {string} * @returns {string} The localised string.
*/ */
t(message, key, data = {}) { t(message, key, data = {}) {
const guildId = message?.channel?.channel?.guildId const guildId = message?.channel?.channel?.guildId
@@ -952,18 +920,25 @@ export class Remix {
return this.locale.translate(guildId, key, data); 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) { getPlayer(message, promptJoin, verifyUser, shouldJoin) {
return this.players.getPlayer(message, promptJoin, verifyUser, shouldJoin); return this.players.getPlayer(message, promptJoin, verifyUser, shouldJoin);
} }
/** /**
* Return all guilds the given user shares with this bot. * Get all servers the bot and the given user share (i.e. the user is a member).
* No longer gated behind settingsMgr — works with or without MySQL. * Used by the dashboard to determine which servers a user can manage.
* Uses cached members first, falls back to observedVoiceUsers, then * @async
* an async REST fetch for large guilds where the member cache is incomplete. * @param {object} user - The Discord user.
* * @returns {Promise<Array<object>>} Array of server summary objects with channels.
* @param {import("@fluxerjs/core").User} user
* @returns {Promise<Array<{name:string,id:string,icon:string|null,voiceChannels:Array}>>}
*/ */
async getSharedServers(user) { async getSharedServers(user) {
if (!user) return []; if (!user) return [];
@@ -1017,6 +992,13 @@ export class Remix {
return shared; 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) { pagination(form, content, msg, linesPerPage) {
this.messages.initPagination( this.messages.initPagination(
new PageBuilder(content).setForm(form).setMaxLines(linesPerPage), new PageBuilder(content).setForm(form).setMaxLines(linesPerPage),
@@ -1028,6 +1010,12 @@ export class Remix {
const remix = new 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 isIgnorableWsCrash = (err) => {
const message = String(err?.message ?? err ?? ""); const message = String(err?.message ?? err ?? "");
const stack = String(err?.stack ?? ""); const stack = String(err?.stack ?? "");
@@ -1065,8 +1053,31 @@ process.on("uncaughtExceptionMonitor", (err, origin) => {
logger.error("Error:", 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 () => { const saveAndExit = async () => {
logger.recovery("\n[Shutdown] Cleaning up before exit..."); 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 { try {
if (remix.dashboard?.redis?.destroy) { if (remix.dashboard?.redis?.destroy) {
await remix.dashboard.redis.destroy(); await remix.dashboard.redis.destroy();
+367 -3436
View File
File diff suppressed because it is too large. Load diff
+9 -8
View File
@@ -5,21 +5,22 @@
}, },
"dependencies": { "dependencies": {
"@fluxerjs/core": "^2.2.0", "@fluxerjs/core": "^2.2.0",
"@fluxerjs/util": "^2.2.0",
"@fluxerjs/voice": "^2.2.0", "@fluxerjs/voice": "^2.2.0",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"ffmpeg-static": "^5.3.0",
"ffprobe-static": "^3.1.0", "ffprobe-static": "^3.1.0",
"follow-redirects": "^1.16.0", "lavalink-client": "^2.10.3",
"moonlink.js": "^5.2.0",
"mysql2": "^3.9.0", "mysql2": "^3.9.0",
"redis": "^5.12.1", "opusscript": "^0.0.8",
"revoice.js": "^0.2.1696" "prism-media": "^1.3.5",
}, "redis": "^5.12.1"
},w
"scripts": { "scripts": {
"dev": "node --inspect index.mjs --trace-warnings", "dev": "node --inspect index.mjs --trace-warnings",
"start": "node index.mjs", "start": "node index.mjs",
"commands": "node index.mjs usage",
"defaultsSync": "node index.mjs sreload",
"migrate": "node settings/migrate.mjs" "migrate": "node settings/migrate.mjs"
},
"optionalDependencies": {
"@discordjs/opus": "^0.10.0"
} }
} }
+32 -31
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: ```sql
```MySQL CREATE TABLE `settings` (
CREATE TABLE `ksiTokens` ( `id` varchar(70) NOT NULL,
`user` varchar(26) NOT NULL, `data` json NOT NULL
`id` varchar(50) NOT NULL, ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
`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
) 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: ## Files
- NoLogicAlan
- ophx | File | Purpose |
- ShadowLp174 | :--- | :--- |
- Fantic | `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
* @module settings.Settings * @description Re-exports the core Settings classes from `src/Settings.mjs`.
*/
/**
* Re-exports from src/Settings.mjs for backward compatibility.
* The canonical definitions now live in src/Settings.mjs.
*/ */
export { SettingsManager, ServerSettings, RemoteSettingsManager } 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"; import { RemoteSettingsManager } from "../src/Settings.mjs";
+28 -29
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.
*/ */
/**
* Validate a prefix setting value.
* @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.
*/
export default { export default {
/** prefix(value) {
* Validate a prefix setting value. if (!value || typeof value !== 'string') return 'Prefix must be a non-empty string.';
* @param {string} value - The proposed prefix if (value.length > 5) return 'Prefix must be 5 characters or fewer.';
* @param {object} _data - Additional context (reserved for future use) if (/\s/.test(value)) return 'Prefix must not contain whitespace.';
* @returns {true|string} True if valid, error message string if invalid return null;
*/
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;
}, },
/** /**
* Validate a profile picture setting value. * Validate a pfp (profile picture) setting value.
* @param {string} value - The proposed pfp value * Only 'default' is accepted on Fluxer.
* @param {object} _data - Additional context (reserved for future use) * @param {*} value - The value to validate.
* @returns {true|string} True if valid, error message string if invalid * @returns {string|null} Error message if invalid, or null if valid.
*/ */
pfp(value, _data) { pfp(value) {
if (value !== "default") { if (value !== 'default') {
return "Profile picture customisation is not supported on Fluxer."; return 'Profile picture customisation is not supported on Fluxer.';
} }
return true; return null;
}, },
/** /**
* Validate the 24/7 stay mode setting. * Validate stay_247 setting. Always valid — the 24/7 system manages
* @param {string|boolean} value - The proposed stay_247 value * this value internally via the toggle command.
* @param {object} _data - Additional context (reserved for future use) * @param {*} value - The value (ignored).
* @returns {true|string} True if valid, error message string if invalid * @returns {string|null} Always null (no error).
*/ */
stay_247(value, _data) { stay_247(value) {
if (value === true || value === false || value === "true" || value === "false") return true; return null;
if (typeof value === "string" && value.length > 0) return true;
return "Invalid value for 24/7 mode.";
}, },
}; };
+105 -99
View File
@@ -1,8 +1,4 @@
/** /** @module src/CommandHandler @description Command registration, loading, parsing, and execution framework with builder pattern, subcommands, and flags. */
* @file CommandHandler.mjs — CommandHandler — registers, resolves, and dispatches slash and prefix commands with option parsing and requirements
* @module src.CommandHandler
*/
import { pathToFileURL } from "node:url"; import { pathToFileURL } from "node:url";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
import { Utils } from "./Utils.mjs"; import { Utils } from "./Utils.mjs";
@@ -13,20 +9,16 @@ import { SettingsManager } from "./Settings.mjs";
import path from "node:path"; import path from "node:path";
import * as fs from "node:fs"; import * as fs from "node:fs";
/** /** @class CommandBuilder @description Fluent builder for constructing command definitions with name, description, options, subcommands, aliases, and requirements. */
* CommandBuilder class.
*/
export class CommandBuilder { export class CommandBuilder {
/** Create a new CommandBuilder with default empty state. */
constructor() { constructor() {
this.name = null; this.name = null;
this.description = null; this.description = null;
this.id = null; this.id = null;
this.aliases = []; this.aliases = [];
/** @type {CommandBuilder[]} */
this.subcommands = []; this.subcommands = [];
/** @type {Option[]} */
this.options = []; this.options = [];
/** @type {CommandRequirement[]} */
this.requirements = []; this.requirements = [];
this.category = "default"; this.category = "default";
this.examples = []; this.examples = [];
@@ -34,59 +26,78 @@ export class CommandBuilder {
this.uid = Utils.uid(); this.uid = Utils.uid();
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`"; this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
/** @type {CommandBuilder} */
this.parent = null; 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; } 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; } setDescription(d) { this.description = d; return this; }
/** Set the command ID. @param {string} id @returns {CommandBuilder} */
setId(id) { this.id = id; return this; } 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; } 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; } 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; } 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; } 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; } 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; } 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; } 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; } 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) { addTextOption(config) {
if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option."); 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"))); this.options.push(config(new Option("text")));
return this; 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; } 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; } 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; } 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; } setCategory(cat) { this.category = cat; return this; }
/** Add usage examples. @param {...string} examples @returns {CommandBuilder} */
addExamples(...examples) { this.examples.push(...examples); return this; } addExamples(...examples) { this.examples.push(...examples); return this; }
} }
/** /** @class CommandRequirement @description Defines permission and owner-only requirements for commands. */
* CommandRequirement class.
*/
export class CommandRequirement { export class CommandRequirement {
/** @type {boolean} Whether the command is restricted to bot owners. */
ownerOnly = false; ownerOnly = false;
/** Create a new CommandRequirement. */
constructor() { constructor() {
this.permissions = []; this.permissions = [];
this.permissionError = "You don't have the needed permissions to run this command!"; this.permissionError = "You don't have the needed permissions to run this command!";
return this; return this;
} }
/** @param {boolean} bool @returns {CommandRequirement} */
setOwnerOnly(bool) { this.ownerOnly = bool; return this; } setOwnerOnly(bool) { this.ownerOnly = bool; return this; }
/** /** @param {string} p @returns {CommandRequirement} */
* @param {string} p Fluxer permission string (ManageChannels", "ManageGuild")
*/
addPermission(p) { this.permissions.push(p); return this; } addPermission(p) { this.permissions.push(p); return this; }
/** @param {...string} p @returns {CommandRequirement} */
addPermissions(...p) { this.permissions.push(...p); return this; } addPermissions(...p) { this.permissions.push(...p); return this; }
/** @returns {string[]} */
getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; } getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; }
/** @param {string} e @returns {CommandRequirement} */
setPermissionError(e) { this.permissionError = e; return this; } setPermissionError(e) { this.permissionError = e; return this; }
} }
/** /** @class Option @description Represents a command option (string, number, boolean, channel, choice, flag) with validation and formatting. */
* Option class.
*/
export class Option { export class Option {
/** @type {number} @description Maximum choices before switching to compact format. */
static THRESHOLD = 10; static THRESHOLD = 10;
/** @type {number} @description Number of choice columns per line in compact format. */
static COLS_PER_LINE = 5; 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) { static formatChoicesCompact(choices, perLine = Option.COLS_PER_LINE) {
const lines = []; const lines = [];
for (let i = 0; i < choices.length; i += perLine) { for (let i = 0; i < choices.length; i += perLine) {
@@ -95,6 +106,7 @@ export class Option {
return lines.join('\n'); return lines.join('\n');
} }
/** Format choice values inline, switching to compact layout above the threshold. @param {string[]} choices @returns {string} */
static formatChoicesInline(choices) { static formatChoicesInline(choices) {
if (choices.length <= Option.THRESHOLD) { if (choices.length <= Option.THRESHOLD) {
return '`' + choices.join('`, `') + '`'; return '`' + choices.join('`, `') + '`';
@@ -102,6 +114,7 @@ export class Option {
return Option.formatChoicesCompact(choices, 6); 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) { static formatChoicesUsage(choices, max = 6) {
if (choices.length <= max) return choices.join(' | '); if (choices.length <= max) return choices.join(' | ');
return choices.slice(0, max).join(' | ') + ' | ...'; return choices.slice(0, max).join(' | ') + ' | ...';
@@ -110,12 +123,10 @@ export class Option {
userRegex = /^<@!?(?<id>\d+)>/; userRegex = /^<@!?(?<id>\d+)>/;
idRegex = /^(?<id>\d+)/; idRegex = /^(?<id>\d+)/;
/** @type {Function} */ /** @type {Function|null} Dynamic default value resolver. */
dynamicDefault; dynamicDefault;
/** /** Create a new Option. @param {string} [type="string"] */
* @param {string} [type="string"] Option value type — "string", "number", "boolean", "channel", "user", or "text"
*/
constructor(type = "string") { constructor(type = "string") {
this.name = null; this.name = null;
this.description = null; this.description = null;
@@ -131,33 +142,39 @@ export class Option {
this.dynamicDefault = null; 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) { static create(type, flag = false) {
return (!flag) ? new Option(type) : new Flag(type); 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; } 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; } 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; } setRequired(r) { this.required = r; return this; }
/** Set the option ID. @param {string} id @returns {Option} */
setId(id) { this.id = id; return this; } setId(id) { this.id = id; return this; }
/** Set the option type. @param {string} t @returns {Option} */
setType(t) { this.type = t; return this; } 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; } 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; } 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; } 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; } 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; } setDynamicDefault(callback) { this.dynamicDefault = callback; return this; }
/** Check whether a value is considered empty/omitted. @param {*} i @returns {boolean} */
empty(i) { empty(i) {
if (i === undefined || i === null) return true; if (i === undefined || i === null) return true;
return (!i && !(String(i).includes("0"))); return (!i && !(String(i).includes("0")));
} }
/** /** Validate an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {boolean} */
* @param {string} i
* @param {Client} client
* @param {import("@fluxerjs/core").Message} msg
* @param {string} [type]
* @returns {boolean}
*/
validateInput(i, client, msg, type) { validateInput(i, client, msg, type) {
switch (type || this.type) { switch (type || this.type) {
case "text": case "text":
@@ -189,13 +206,7 @@ export class Option {
} }
} }
/** /** Format/parse an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {*} */
* @param {string} i
* @param {Client} client
* @param {import("@fluxerjs/core").Message} msg
* @param {string} [type]
* @returns {string|number|boolean}
*/
formatInput(i, client, msg, type) { formatInput(i, client, msg, type) {
switch (type || this.type) { switch (type || this.type) {
case "text": case "text":
@@ -227,6 +238,7 @@ export class Option {
} }
} }
/** Generate a type-error message for this option. @returns {string} */
get typeError() { get typeError() {
if (this.tError) return this.tError; if (this.tError) return this.tError;
switch (this.type) { 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 + ">`"; 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; } set typeError(e) { this.tError = e; }
} }
/** /** @class Flag @description A flag-type option that cannot be text. Extends Option. */
* Flag class.
*/
export class Flag extends Option { export class Flag extends Option {
/** /** Create a Flag (non-text option). @param {string} [type="string"] */
* @param {string} [type="string"] Flag value type — anything Option supports except "text"
*/
constructor(type = "string") { constructor(type = "string") {
if (type === "text") throw new Error("Flags can't be of type 'text'!"); if (type === "text") throw new Error("Flags can't be of type 'text'!");
super(type); super(type);
} }
} }
/** /** @class PrefixManager @description Manages per-guild command prefixes (falling back to config or default). */
* PrefixManager class.
*/
export class PrefixManager { export class PrefixManager {
/** @type {SettingsManager} */ /** @type {RemoteSettingsManager} */
settings; settings;
/** @type {string|null} Prefix from config.json — used as fallback when DB has no value */ /** @type {string|null} */
configPrefix; configPrefix;
/** /** @param {RemoteSettingsManager} settings @param {string|null} [configPrefix=null] */
* @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
*/
constructor(settings, configPrefix = null) { this.settings = settings; this.configPrefix = configPrefix; } constructor(settings, configPrefix = null) { this.settings = settings; this.configPrefix = configPrefix; }
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
getPrefix(guildId) { getPrefix(guildId) {
const serverPrefix = this.settings.getServer(guildId).get("prefix"); const serverPrefix = this.settings.getServer(guildId).get("prefix");
return serverPrefix ?? this.configPrefix ?? "%"; return serverPrefix ?? this.configPrefix ?? "%";
} }
} }
/** /** @class HelpHandler @description Generates paginated help text for commands. */
* HelpHandler class.
*/
export class HelpHandler { export class HelpHandler {
/** @type {CommandHandler} */ /** @type {CommandHandler} */
commands; commands;
/** @type {number} Commands per help page. */
commandsPerPage = 5; 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) => { paginationHandler = (msg, helpHandler, cmds) => {
const guildId = msg.message.guildId; const guildId = msg.message.guildId;
let form = this.commands.t(guildId, "cmdHandler.help.pageStructure"); let form = this.commands.t(guildId, "cmdHandler.help.pageStructure");
@@ -302,35 +307,39 @@ export class HelpHandler {
return null; return null;
} }
/** @type {Function|null} Custom help handler function override. */
customHelpHandler = null; customHelpHandler = null;
/** /** @param {CommandHandler} commands */
* @param {CommandBuilder[]} commands Loaded command list to generate help pages from
*/
constructor(commands) { this.commands = commands; } constructor(commands) { this.commands = commands; }
/** @param {string} string @returns {string} Capitalised first letter. */
static capitalise(string) { static capitalise(string) {
if (string.length < 1) return string; if (string.length < 1) return string;
if (string.length === 1) return string.toUpperCase(); if (string.length === 1) return string.toUpperCase();
return string.charAt(0).toUpperCase() + string.slice(1); return string.charAt(0).toUpperCase() + string.slice(1);
} }
/** @param {Array} [cmds] @returns {Array} Non-owner-only commands. */
userCommands(cmds) { userCommands(cmds) {
return (cmds || this.commands.commands).filter(c => return (cmds || this.commands.commands).filter(c =>
c.requirements.findIndex(r => r.ownerOnly) === -1 c.requirements.findIndex(r => r.ownerOnly) === -1
); );
} }
/** @returns {number} Total number of help pages. */
pageNumber() { pageNumber() {
return Math.ceil(this.commands.commands.length / this.commandsPerPage); return Math.ceil(this.commands.commands.length / this.commandsPerPage);
} }
/** @param {object} message @returns {string|null} */
help(message) { help(message) {
if (this.customHelpHandler) return this.customHelpHandler(message); if (this.customHelpHandler) return this.customHelpHandler(message);
if (this.paginationHandler) return this.genHelp(null, message, true); if (this.paginationHandler) return this.genHelp(null, message, true);
return this.getHelpPage(0, message); return this.getHelpPage(0, message);
} }
/** @param {number} n @param {object} msg @param {Array} [cmds=null] @returns {string} */
getHelpPage(n, msg, cmds = null) { getHelpPage(n, msg, cmds = null) {
if (!cmds) cmds = this.commands.commands; if (!cmds) cmds = this.commands.commands;
if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds); 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); 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) { genHelp(page, msg, paginate = false, cmds = null) {
cmds = this.userCommands(cmds); cmds = this.userCommands(cmds);
if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, 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); return this.commands.format(content, guildId);
} }
/** Get the description of a command. @param {CommandBuilder} command @returns {string} */
commandDescription(command) { return command.description; } 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) { commandUsage(cmd, msg) {
if (cmd.subcommands.length > 0) { if (cmd.subcommands.length > 0) {
return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]"; 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(); return options.trim();
} }
/** Generate detailed help for a single command. @param {object} command @param {object} msg @returns {string} */
getCommandHelp(command, msg) { getCommandHelp(command, msg) {
const guildId = msg.message.guildId; const guildId = msg.message.guildId;
let content = `${HelpHandler.capitalise(command.name)}\n`; let content = `${HelpHandler.capitalise(command.name)}\n`;
@@ -420,39 +433,33 @@ export class HelpHandler {
} }
} }
/** /** @class CommandHandler @description Main command dispatcher. Parses incoming messages, matches commands, validates arguments, checks permissions, and emits run events. @extends {EventEmitter} */
* CommandHandler class.
*/
export class CommandHandler extends EventEmitter { export class CommandHandler extends EventEmitter {
/** @type {Function|null} Custom handler when the bot is pinged. */
onPing = null; onPing = null;
/** @type {boolean} Whether the bot responds to pings as a prefix. */
pingPrefix = true; pingPrefix = true;
/** @type {string[]} Bot owner user IDs. */
owners = []; owners = [];
/** @type {MessageHandler} */
messages; messages;
/** @type {Client} */
client; client;
/** @type {PrefixManager} */
prefixes; prefixes;
/** @type {HelpHandler} */
helpHandler; helpHandler;
commandNames = []; commandNames = [];
/** @type {CommandBuilder[]} */
commands = []; commands = [];
/** @type {import('./constants/Locale.mjs').Locale|null} */
locale = null; locale = null;
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`"; 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."; 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(); _cmdCooldowns = new Map();
/** @private @type {number} Cooldown duration in milliseconds between commands per non-owner user. */
_cmdCooldownMs = 1500; _cmdCooldownMs = 1500;
/** /** @param {MessageHandler} handler - The message handler instance. @param {string} [prefix="%"] - Default command prefix. */
* @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
*/
constructor(handler, prefix = "%") { constructor(handler, prefix = "%") {
super(); super();
this.messages = handler; this.messages = handler;
@@ -466,25 +473,24 @@ export class CommandHandler extends EventEmitter {
this.messages.onMessage(this.messageHandler.bind(this)); 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); } getPrefix(guildId) { return this.prefixes.getPrefix(guildId); }
/** Enable or disable ping-as-prefix. @param {boolean} bool */
setPingPrefix(bool) { this.pingPrefix = bool; } setPingPrefix(bool) { this.pingPrefix = bool; }
/** Set the prefix manager instance. @param {PrefixManager} manager */
setPrefixManager(manager) { this.prefixes = manager; } setPrefixManager(manager) { this.prefixes = manager; }
/** Set a custom help handler. @param {HelpHandler} handler */
setHelpHandler(handler) { this.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; } setLocale(locale) { this.locale = locale; }
/** /** Translate a locale key. @param {string} guildId @param {string} key @param {object} [replacements={}] @returns {string} */
* Translate a locale key for a given guild.
* @param {string} guildId
* @param {string} key
* @param {Object} [replacements={}]
* @returns {string}
*/
t(guildId, key, replacements = {}) { t(guildId, key, replacements = {}) {
if (!this.locale) return key; if (!this.locale) return key;
return this.locale.translate(guildId, key, replacements); 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) { format(text, guildId) {
const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId); const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId);
return text return text
@@ -492,6 +498,7 @@ export class CommandHandler extends EventEmitter {
.replace(/\$helpCmd/gi, this.helpCommand); .replace(/\$helpCmd/gi, this.helpCommand);
} }
/** Remove a command from the registry. @param {CommandBuilder} command */
removeCommand(command) { removeCommand(command) {
command.aliases.forEach(a => { command.aliases.forEach(a => {
const idx = this.commandNames.indexOf(a); const idx = this.commandNames.indexOf(a);
@@ -501,6 +508,7 @@ export class CommandHandler extends EventEmitter {
if (idx !== -1) this.commands.splice(idx, 1); if (idx !== -1) this.commands.splice(idx, 1);
} }
/** @private Handle an incoming message and route to command processing. @param {Message} msg */
messageHandler(msg) { messageHandler(msg) {
if (!msg || !msg.content) return; if (!msg || !msg.content) return;
const trimmed = msg.content.trim(); 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); 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) { processCommand(cmd, args, msg, previous = false, external = false) {
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy."); if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
@@ -619,6 +628,7 @@ export class CommandHandler extends EventEmitter {
const opts = []; const opts = [];
const texts = []; 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 collectArguments = (index, currVal, as) => {
const lastChar = currVal.charAt(currVal.length - 1); const lastChar = currVal.charAt(currVal.length - 1);
if (lastChar === '"') return { args: as, index }; if (lastChar === '"') return { args: as, index };
@@ -733,9 +743,7 @@ export class CommandHandler extends EventEmitter {
return commandRunData; return commandRunData;
} }
/** /** Check whether the message author meets all command requirements (owner, permissions). @param {CommandBuilder} cmd @param {Message} msg @returns {boolean} */
* Checks requirements using fluxerjs permission API.
*/
assertRequirements(cmd, msg) { assertRequirements(cmd, msg) {
const authorId = msg.message?.author?.id; const authorId = msg.message?.author?.id;
const isOwner = this.owners.includes(authorId); const isOwner = this.owners.includes(authorId);
@@ -781,9 +789,12 @@ export class CommandHandler extends EventEmitter {
return true; 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); } 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); } 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) { _optionTypeError(guildId, option, value, previous) {
if (option.tError) { if (option.tError) {
return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value); return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
@@ -802,10 +813,12 @@ export class CommandHandler extends EventEmitter {
}).replace(/\$previousCmd/gi, previous); }).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) { _textWrapErrorMsg(guildId, value, quote) {
return this.t(guildId, 'cmdHandler.textWrapError', { $value: value, $quote: 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) { addCommand(builder) {
this.commandNames.push(...builder.aliases); this.commandNames.push(...builder.aliases);
this.commands.push(builder); this.commands.push(builder);
@@ -818,22 +831,18 @@ export class CommandHandler extends EventEmitter {
} }
} }
/** /** @class CommandLoader @description Dynamically loads command files from a directory, registers builders, and binds run handlers. */
* CommandLoader class.
*/
export class CommandLoader { export class CommandLoader {
/** @type {CommandHandler} */ /** @type {CommandHandler} Reference to the command handler. */
commands; commands;
/** @type {Map<string, string>} */ /** @type {Map<string, string>} Command UID → file path. */
commandFiles = new Map(); commandFiles = new Map();
/** @type {Map<string, Function>} */ /** @type {Map<string, Function>} Command UID → run function. */
runnables = new Map(); runnables = new Map();
/** @type {object} Shared context (the bot instance). */
context; context;
/** /** @param {CommandHandler} commands @param {object} context - Bot context object. */
* @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
*/
constructor(commands, context) { constructor(commands, context) {
this.commands = commands; this.commands = commands;
this.context = context; this.context = context;
@@ -865,11 +874,7 @@ export class CommandLoader {
}); });
} }
/** /** Normalize a module export to { command, run, exportDef }. @param {object} cData @returns {object} */
* 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 }
*/
canonData(cData) { canonData(cData) {
if (cData.command !== undefined) { if (cData.command !== undefined) {
return { return {
@@ -886,6 +891,7 @@ export class CommandLoader {
}; };
} }
/** @async Load all command files from a directory. @param {string} dir @returns {Promise<undefined[]>} */
loadFromDir(dir) { loadFromDir(dir) {
const files = fs.readdirSync(dir) const files = fs.readdirSync(dir)
.filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs"))); .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 @@
/** /** @module src/FluxerListManager @description FluxerList API integration for fetching server/bot voter lists with caching. */
* @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
*/
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
import { import {
@@ -23,18 +8,9 @@ import {
buildFluxerListUrl, buildFluxerListUrl,
} from "./constants/API.mjs"; } from "./constants/API.mjs";
/** /** @class FluxerListManager @description Fetches and caches voter lists from the FluxerList API for servers and bots. */
* FluxerListManager class.
*/
export class FluxerListManager { export class FluxerListManager {
/** /** @param {object} [config={}] @param {string} [config.apiKey] @param {string} [config.serverId] @param {string} [config.botId] @param {string} [config.serverSlug] @param {string} [config.botSlug] */
* @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")
*/
constructor(config = {}) { constructor(config = {}) {
this.apiKey = config?.apiKey ?? ""; this.apiKey = config?.apiKey ?? "";
this.serverId = config?.serverId ?? ""; this.serverId = config?.serverId ?? "";
@@ -52,23 +28,12 @@ export class FluxerListManager {
} }
} }
/** /** @private @param {string} type @param {string} id @param {number} page @param {number} limit @returns {string} */
* Generate a cache key from the request parameters.
* @param {"server"|"bot"} type
* @param {string} id
* @param {number} page
* @param {number} limit
* @returns {string}
*/
_cacheKey(type, id, page, limit) { _cacheKey(type, id, page, limit) {
return `${type}:${id}:p${page}:l${limit}`; return `${type}:${id}:p${page}:l${limit}`;
} }
/** /** @private @param {string} key @returns {object|null} */
* Get a cached response if still fresh.
* @param {string} key
* @returns {object|null}
*/
_getCached(key) { _getCached(key) {
const entry = this._cache.get(key); const entry = this._cache.get(key);
if (!entry) return null; if (!entry) return null;
@@ -79,12 +44,7 @@ export class FluxerListManager {
return entry.data; return entry.data;
} }
/** /** @private @param {string} key @param {object} data @param {number} [ttlMs] */
* Store a response in the cache with the configured TTL.
* @param {string} key
* @param {object} data
* @param {number} [ttlMs] - Override TTL in milliseconds
*/
_setCached(key, data, ttlMs) { _setCached(key, data, ttlMs) {
this._cache.set(key, { this._cache.set(key, {
data, data,
@@ -99,18 +59,7 @@ export class FluxerListManager {
} }
} }
/** /** @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. */
* 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 getVoters(type, id, options = {}) { async getVoters(type, id, options = {}) {
this._assertEnabled(); this._assertEnabled();
@@ -173,36 +122,17 @@ export class FluxerListManager {
return data; return data;
} }
/** /** @async @param {string} [id] @param {object} [options] @returns {Promise<object>} */
* 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 getServerVoters(id, options = {}) { async getServerVoters(id, options = {}) {
return this.getVoters("server", id, options); return this.getVoters("server", id, options);
} }
/** /** @async @param {string} [id] @param {object} [options] @returns {Promise<object>} */
* 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 getBotVoters(id, options = {}) { async getBotVoters(id, options = {}) {
return this.getVoters("bot", id, options); return this.getVoters("bot", id, options);
} }
/** /** @async Fetch all pages of voters for a resource. @param {"server"|"bot"} type @param {string} [id] @param {object} [options] @returns {Promise<Array>} */
* 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 getAllVoters(type, id, options = {}) { async getAllVoters(type, id, options = {}) {
this._assertEnabled(); this._assertEnabled();
@@ -223,6 +153,7 @@ export class FluxerListManager {
return allVoters; return allVoters;
} }
/** @private @throws {Error} If not configured. */
_assertEnabled() { _assertEnabled() {
if (!this.enabled) { if (!this.enabled) {
throw new Error("FluxerList integration is not configured (missing apiKey in config.json)."); throw new Error("FluxerList integration is not configured (missing apiKey in config.json).");
+150 -323
View File
@@ -1,8 +1,4 @@
/** /** @module src/GatewayHandler @description Handles all Discord gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. */
* @file GatewayHandler.mjs — GatewayHandler — processes raw WebSocket events for voice state tracking, 24/7 recovery, and guild lifecycle
* @module src.GatewayHandler
*/
import { Events, GatewayOpcodes } from "@fluxerjs/core"; import { Events, GatewayOpcodes } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice"; import { getVoiceManager } from "@fluxerjs/voice";
import { logger, _wsErrorCooldown } from "./constants/Logger.mjs"; import { logger, _wsErrorCooldown } from "./constants/Logger.mjs";
@@ -13,16 +9,11 @@ import { REQUIRED_BOT_PERMISSIONS } from "./MessageHandler.mjs";
import { cleanId } from "./Utils.mjs"; import { cleanId } from "./Utils.mjs";
import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "./constants/VoiceStateResolver.mjs"; import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "./constants/VoiceStateResolver.mjs";
/** /** @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. */
* 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.
*/
export class GatewayHandler { 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) { constructor(remix) {
this.remix = remix; this.remix = remix;
@@ -40,31 +31,21 @@ export class GatewayHandler {
this.presenceTimer = null; this.presenceTimer = null;
this.presenceIndex = 0; this.presenceIndex = 0;
/** @type {Map<string, {channelId, guildId}>} guildId:userId → state */
this._prevVoiceState = new Map(); this._prevVoiceState = new Map();
/** @type {Map<string, {guild, timer}>} guildId → deferred cleanup data */
this._deferredGuildDeletes = new Map(); this._deferredGuildDeletes = new Map();
/** @type {number} How long to defer GuildDelete processing during startup (ms) */
this._startupDeleteGraceMs = 15_000; this._startupDeleteGraceMs = 15_000;
/** @type {boolean} Whether we're still in the startup grace period */
this._inStartupGrace = true; this._inStartupGrace = true;
/** @type {number} Counter for deferred deletions (used for batch summary log) */
this._deferredDeleteCount = 0; this._deferredDeleteCount = 0;
/** @type {number} Timestamp of the last Events.Ready fire (initial + reconnects). 0 = never. */
this._lastReadyAt = 0; this._lastReadyAt = 0;
/** @type {number} Window after a Ready event during which voice disconnects are treated as WS-induced (ms). */
this._wsReconnectGraceMs = 30_000; 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; this._moveEvidenceWindowMs = 10_000;
} }
/** /**
* Check whether a voice disconnect was likely caused by a recent WS reconnect * Check whether a WebSocket reconnect happened recently (within 30s).
* rather than a user-initiated leave. Uses the time since the last Events.Ready * Used to treat transient disconnects as non-24/7-requiring.
* fire as the signal — if the bot just re-identified, any voice session
* invalidation is almost certainly WS-induced.
* @returns {boolean} * @returns {boolean}
*/ */
isWsReconnectRecent() { isWsReconnectRecent() {
@@ -72,22 +53,21 @@ export class GatewayHandler {
return Date.now() - this._lastReadyAt < this._wsReconnectGraceMs; return Date.now() - this._lastReadyAt < this._wsReconnectGraceMs;
} }
/** /** @private Build a composite bot key for voice state tracking. @param {string} userId @param {string} guildId @returns {string|null} */
* Generate a composite key for bots in the observedVoiceBots map.
* Bots can be in multiple guilds so we namespace by guildId.
*/
getObservedVoiceBotKey(userId, guildId) { getObservedVoiceBotKey(userId, guildId) {
const cleanUserId = cleanId(userId ?? ""); const cleanUserId = cleanId(userId ?? "");
const cleanGuildId = cleanId(guildId ?? ""); const cleanGuildId = cleanId(guildId ?? "");
return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : cleanUserId || null; 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) { getPrevVoiceStateKey(userId, guildId) {
const cleanUserId = cleanId(userId ?? ""); const cleanUserId = cleanId(userId ?? "");
const cleanGuildId = cleanId(guildId ?? ""); const cleanGuildId = cleanId(guildId ?? "");
return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : null; 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) { findPrevVoiceStateEntry(userId, guildId = null) {
const directKey = this.getPrevVoiceStateKey(userId, guildId); const directKey = this.getPrevVoiceStateKey(userId, guildId);
if (directKey && this._prevVoiceState.has(directKey)) { 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. * Check and warn about missing bot permissions in a guild.
* If critical permissions are missing, log a warning and attempt to send * Sends an embed to the system channel if critical or optional perms are missing.
* a notification to the guild's system channel (or first text channel). * @param {object} guild - The guild object.
* * @param {string} guildId - The guild ID.
* @param {import('@fluxerjs/core').Guild} guild * @returns {Promise<void>}
* @param {string} guildId * @private
*/ */
async _checkGuildPermissions(guild, guildId) { async _checkGuildPermissions(guild, guildId) {
const { remix } = this; const { remix } = this;
@@ -175,8 +155,8 @@ export class GatewayHandler {
} }
/** /**
* Seed observedVoiceUsers / observedVoiceBots from all cached guild voice * Seed the voice state cache from VoiceManager or guild cache on startup.
* states. Called once on Ready after the guild cache is populated. * @private
*/ */
seedVoiceStatesFromGuilds() { seedVoiceStatesFromGuilds() {
const { remix } = this; const { remix } = this;
@@ -229,19 +209,11 @@ export class GatewayHandler {
} }
/** /**
* Re-read the guild's voice_states cache and update observedVoiceUsers * Re-seed voice states for a specific channel from multiple sources.
* for any human users found in the specified channel. * Checks VoiceManager, guild cache, VoiceStateCache, and LiveKit participants.
* * @param {string} guildId - The guild ID.
* This is crucial after bot recovery: when the bot restarts and rejoins a * @param {string} channelId - The channel ID.
* voice channel, the initial `seedVoiceStatesFromGuilds()` may have run * @returns {number} Number of humans found in the channel.
* 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.
*/ */
reseedVoiceStatesForChannel(guildId, channelId) { reseedVoiceStatesForChannel(guildId, channelId) {
const { remix } = this; const { remix } = this;
@@ -370,13 +342,7 @@ export class GatewayHandler {
return humansFound; return humansFound;
} }
/** /** Attach a raw WebSocket listener to cache VOICE_SERVER_UPDATE events. @private */
* 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.
*/
attachRawListener() { attachRawListener() {
const { remix } = this; const { remix } = this;
const client = remix.client; const client = remix.client;
@@ -500,6 +466,7 @@ export class GatewayHandler {
} catch(e) { logger.warn("[Gateway] attachRawListener failed:", e?.message); } } catch(e) { logger.warn("[Gateway] attachRawListener failed:", e?.message); }
} }
/** Rotate the bot's presence/status text at a configured interval. @private */
setupPresenceRotation() { setupPresenceRotation() {
if (this.presenceContents.length === 0) return; if (this.presenceContents.length === 0) return;
@@ -549,8 +516,8 @@ export class GatewayHandler {
} }
/** /**
* Register all high-level Fluxer event listeners on the Fluxer client. * Register all gateway event handlers (GuildCreate, GuildDelete, VoiceStateUpdate, VoiceStatesSync).
* Call once during bot startup. * Called once during bot initialisation.
*/ */
setupEventHandlers() { setupEventHandlers() {
const { remix } = this; const { remix } = this;
@@ -656,9 +623,10 @@ export class GatewayHandler {
} }
/** /**
* Main voice state update dispatcher — calls focused sub-handlers. * Main handler for VOICE_STATE_UPDATE events. Routes to human or bot sub-handlers.
* Parses the raw VOICE_STATE_UPDATE payload, computes the old channel, * @param {object} data - The voice state update payload from the gateway.
* then delegates to specialised methods. * @returns {Promise<void>}
* @private
*/ */
async _handleVoiceStateUpdate(data) { async _handleVoiceStateUpdate(data) {
const { remix } = this; const { remix } = this;
@@ -697,15 +665,7 @@ export class GatewayHandler {
this._handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, data); this._handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, data);
} }
/** /** Handle VoiceStatesSync bulk event from the gateway. @param {object} data - Sync payload with voiceStates array. @private */
* 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
*/
_handleVoiceStatesSync(data) { _handleVoiceStatesSync(data) {
const { remix } = this; const { remix } = this;
const client = remix.client; const client = remix.client;
@@ -739,10 +699,7 @@ export class GatewayHandler {
} }
} }
/** /** @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 */
* Update the voice state cache when users move between channels.
* Adds users to the cache on join, removes them on leave.
*/
_updateVoiceStateCache(userId, guildId, oldChannelId, newChannelId, isBot, prev) { _updateVoiceStateCache(userId, guildId, oldChannelId, newChannelId, isBot, prev) {
const { remix } = this; const { remix } = this;
@@ -757,10 +714,7 @@ export class GatewayHandler {
} }
} }
/** /** @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 */
* Update the previous state map (LRU eviction).
* Maintains a bounded map of previous voice states for computing oldChannelId.
*/
_updatePreviousStates(userId, guildId, oldChannelId, newChannelId, isBot, prevEntry, prev) { _updatePreviousStates(userId, guildId, oldChannelId, newChannelId, isBot, prevEntry, prev) {
const { remix } = this; const { remix } = this;
const prevKey = prevEntry.key; const prevKey = prevEntry.key;
@@ -795,12 +749,7 @@ export class GatewayHandler {
} }
} }
/** /** @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}} */
* 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 }}
*/
_findAffectedPlayer(guildId, oldChannelId, newChannelId) { _findAffectedPlayer(guildId, oldChannelId, newChannelId) {
const { remix } = this; const { remix } = this;
@@ -825,10 +774,7 @@ export class GatewayHandler {
return { player: null, playerGuildId: null, homeChannelId: null }; return { player: null, playerGuildId: null, homeChannelId: null };
} }
/** /** @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 */
* Manage inactivity timers when humans join/leave voice channels.
* Also handles dashboard updates for human voice state changes.
*/
async _handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, vsu) { async _handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, vsu) {
const { remix } = this; const { remix } = this;
const client = remix.client; const client = remix.client;
@@ -910,8 +856,16 @@ export class GatewayHandler {
} }
/** /**
* Handle the bot being moved to a different channel or disconnected. * Handle a voice state update for the bot itself.
* Covers 24/7 re-key on move and auto-rejoin / autoleave on disconnect. * 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) { _handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, vsu) {
const { remix } = this; const { remix } = this;
@@ -919,175 +873,86 @@ export class GatewayHandler {
const guildId = vsuGuildId; const guildId = vsuGuildId;
if (newChannelId && guildId && oldChannelId && oldChannelId !== newChannelId) { if (newChannelId && guildId && oldChannelId && oldChannelId !== newChannelId) {
// During boot recovery, ignore move events — the recovery loop handles rejoining.
if (this._bootRecoveryActive) {
logger.voice247(
`[247] Ignoring bot move ${cleanId(oldChannelId)} → ${cleanId(newChannelId)} during boot recovery.`
);
return;
}
try { try {
const cleanNew = cleanId(newChannelId); const cleanNew = cleanId(newChannelId);
const cleanOld = cleanId(oldChannelId); 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) { // Check if old channel is a saved 24/7 channel
logger.voice247( const oldIs247 = (() => {
`[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanNew} ` +
`because guild ${guildId} already has multiple saved 24/7 channels ` +
`[${saved247Channels.join(", ")}]`
);
return;
}
const existingPlayer = remix.players.playerMap.get(cleanOld);
const newChannelAlreadySaved = (() => {
try { try {
const set = remix.settingsMgr.getServer(guildId); const set = remix.settingsMgr.getServer(guildId);
const raw = set?.get("stay_247"); return get247ChannelMode(set, cleanOld) === "on";
if (!raw || raw === "none") return false; } catch (_) { 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;
}
})(); })();
const newChannelPendingSpawn =
remix.players?._pendingJoins?.has?.(cleanNew) ||
false;
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; // Check if new channel is a saved 24/7 channel or has a pending spawn
if (existingPlayer && cleanNew !== cleanOld) { const newChannelSaved = (() => {
if (newChannelAlreadySaved || newChannelPendingSpawn) { try {
logger.voice247( const set = remix.settingsMgr.getServer(guildId);
`[247] Keeping both channels ${cleanOld} and ${cleanNew} ` + return get247ChannelMode(set, cleanNew) === "on";
`(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})` } catch (_) { return false; }
); })();
rekeyed = false; const newChannelPendingSpawn = remix.players?._pendingJoins?.has?.(cleanNew) || false;
} else
if (guildIsAmbiguous) { const existingPlayer = remix.players.playerMap.get(cleanOld);
const playerAtNewKey = remix.players.playerMap.get(cleanNew);
if (playerAtNewKey && playerAtNewKey !== existingPlayer) { if (oldIs247 && existingPlayer) {
existingPlayer._channelId = cleanNew; // Old channel is 24/7 — bot physically moved away, so the voice
existingPlayer._home247Channel = cleanNew; // connection to old channel is dead. Destroy the old player and
if (targetGuildId) existingPlayer._guildId = targetGuildId; // schedule a fresh rejoin so it gets a new live connection.
rekeyed = false; logger.voice247(
logger.voice247( `[247] Bot moved away from 24/7 channel ${cleanOld} → ${cleanNew}. ` +
`[247] Updated player channel ${cleanOld} → ${cleanNew} ` + `Destroying stale player, scheduling rejoin for ${cleanOld}.`
`(guild ${guildId} has ${guildPlayers.length} active players, ` + );
`new key occupied by another player — skipped re-key)` remix.players.playerMap.delete(cleanOld);
); const homeCh = cleanId(existingPlayer._home247Channel ?? "");
} else { if (homeCh && homeCh !== cleanOld) remix.players.playerMap.delete(homeCh);
remix.players.playerMap.delete(cleanOld); try { existingPlayer.destroy(); } catch (_) {}
remix.players.playerMap.set(cleanNew, existingPlayer); const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
existingPlayer._channelId = cleanNew; setTimeout(() => {
existingPlayer._home247Channel = cleanNew; this._rejoinChannel(cleanId(guildId), cleanOld).catch(err => {
if (targetGuildId) existingPlayer._guildId = targetGuildId; logger.warn(`[247] Failed to rejoin ${cleanOld} after move-away:`, err.message);
rekeyed = true; });
logger.voice247( }, rejoinDelay);
`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew} ` + } else if (newChannelSaved || newChannelPendingSpawn) {
`(guild ${guildId} has ${guildPlayers.length} active players)` // New channel is already 24/7 or being spawned — keep both, don't rekey.
); logger.voice247(
} `[247] Keeping both channels ${cleanOld} and ${cleanNew} ` +
} else if (playerGuildIdLocal && targetGuildId && playerGuildIdLocal !== targetGuildId) { `(saved=${newChannelSaved} pending=${newChannelPendingSpawn})`
if (!existingPlayer) { );
logger.voice247( } else if (existingPlayer && cleanNew !== cleanOld) {
`[247] Stale cross-guild move ${cleanOld} → ${cleanNew} ` + // Neither channel is 24/7 — safe to rekey the player.
`(no player in playerMap for old channel — updating bot state only)` const targetChannel = client.channels.get(cleanNew)
); ?? client.channels.get?.(cleanNew)
} else { ?? null;
const vsuGuildIdClean = cleanId(guildId ?? ""); const targetGuildId = cleanId(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? "");
if (vsuGuildIdClean && targetGuildId === vsuGuildIdClean) {
existingPlayer._guildId = targetGuildId; const playerAtNewKey = remix.players.playerMap.get(cleanNew);
existingPlayer._channelId = cleanNew; if (!playerAtNewKey || playerAtNewKey === existingPlayer) {
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.delete(cleanOld);
remix.players.playerMap.set(cleanNew, existingPlayer); remix.players.playerMap.set(cleanNew, existingPlayer);
existingPlayer._channelId = cleanNew; existingPlayer._channelId = cleanNew;
existingPlayer._home247Channel = cleanNew; existingPlayer._home247Channel = cleanNew;
if (targetGuildId) existingPlayer._guildId = targetGuildId; if (targetGuildId) existingPlayer._guildId = targetGuildId;
rekeyed = true;
logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew}`); logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew}`);
} } else {
} logger.voice247(
`[247] Skipped re-key ${cleanOld} → ${cleanNew} (new key occupied by another player)`
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) {
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`
);
}
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) { } 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)) { if (remix.intentionalLeaves.has(cleanOld)) {
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`); 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)) { } else if (this._isGuildMoveInProgress(cleanGuild, cleanOld)) {
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — guild move in progress, skipping.`); logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — guild move in progress, skipping.`);
} else if (this._bootRecoveryActive) { } else if (this._bootRecoveryActive) {
@@ -1126,10 +989,10 @@ export class GatewayHandler {
const mode = set ? get247ChannelMode(set, cleanOld) : "off"; const mode = set ? get247ChannelMode(set, cleanOld) : "off";
const wsInduced = this.isWsReconnectRecent(); const wsInduced = this.isWsReconnectRecent();
if (mode === "auto" || wsInduced) { if (mode === "on" || wsInduced) {
const reason = wsInduced && mode !== "auto" const reason = wsInduced && mode !== "on"
? `WS reconnect detected (${Math.round((Date.now() - this._lastReadyAt) / 1000)}s ago) — treating as transient, scheduling rejoin` ? `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( logger.voice247(
`[VoiceState] Bot unexpectedly disconnected from ${cleanOld} — ${reason}.` `[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(); _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(); _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; _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; static MAX_REJOIN_RETRIES = 3;
/** /**
* Shared rejoin attempt logic with exponential backoff retry. * Attempt to spawn a player for a channel with exponential-backoff retries.
* Used by both _rejoinChannel (disconnect recovery) and * @param {string} channelId - The target channel ID.
* rejoin247Channels (boot recovery). * @param {string} guildId - The guild ID.
* * @param {number} [maxRetries=3] - Maximum retry attempts.
* @param {string} channelId - Clean channel ID * @param {number} [baseDelay=5000] - Base delay in ms (doubled each retry).
* @param {string} guildId - Clean guild ID * @param {string} [context='Rejoin'] - Label for log messages.
* @param {number} [maxRetries=3] Maximum retry attempts * @returns {Promise<Player|null>} The spawned player, or null if all retries failed.
* @param {number} [baseDelay=5000] Base delay for exponential backoff (ms) * @private
* @param {string} [context="Rejoin"] Log context prefix
* @returns {Promise<object|null>} The spawned player, or null on failure
*/ */
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++) { for (let attempt = 1; attempt <= maxRetries; attempt++) {
try { try {
const player = await this.remix._spawnPlayer(guildId, channelId); const player = await this.remix._spawnPlayer(guildId, channelId);
@@ -1206,8 +1067,8 @@ export class GatewayHandler {
} catch (err) { } catch (err) {
const errMsg = err?.message ?? String(err); const errMsg = err?.message ?? String(err);
const isTrackTimeout = errMsg.includes("track publication timed out") const isTrackTimeout = errMsg.includes("track publication timed out")
|| errMsg.includes("publishToRoom failed") || errMsg.includes("lavalink player create failed")
|| errMsg.includes("Failed to create MediaPlayer") || errMsg.includes("Failed to create audio player")
|| errMsg.includes("internal error"); || errMsg.includes("internal error");
if (isTrackTimeout && attempt < maxRetries) { if (isTrackTimeout && attempt < maxRetries) {
@@ -1231,14 +1092,12 @@ export class GatewayHandler {
} }
/** /**
* Rejoin a voice channel after an unexpected disconnect. * Safely rejoin a 24/7 channel. Guards against duplicate joins,
* Used by the %247 auto mode to automatically reconnect. * intentional leaves, missing channels, and pending joins.
* * @param {string} guildId - The guild ID.
* Includes deduplication (prevents concurrent rejoin for the same channel) * @param {string} channelId - The target channel ID.
* and delegates retry logic to _attemptRejoin. * @returns {Promise<Player|null>} The spawned player, or null if skipped.
* * @private
* @param {string} guildId
* @param {string} channelId
*/ */
async _rejoinChannel(guildId, channelId) { async _rejoinChannel(guildId, channelId) {
const { remix } = this; const { remix } = this;
@@ -1268,12 +1127,6 @@ export class GatewayHandler {
return; 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); const channel = remix.client?.channels?.get?.(cleanChannelId);
if (!channel) { if (!channel) {
logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`); logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`);
@@ -1301,16 +1154,7 @@ export class GatewayHandler {
} }
} }
/** /** @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. */
* 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
*/
_isGuildMoveInProgress(guildId, oldChannelId) { _isGuildMoveInProgress(guildId, oldChannelId) {
const { remix } = this; const { remix } = this;
const cleanGuild = cleanId(guildId); const cleanGuild = cleanId(guildId);
@@ -1346,21 +1190,7 @@ export class GatewayHandler {
return false; return false;
} }
/** /** @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. */
* 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 seedGuildsFromRest() { async seedGuildsFromRest() {
const { remix } = this; const { remix } = this;
const client = remix.client; const client = remix.client;
@@ -1428,11 +1258,7 @@ export class GatewayHandler {
} }
} }
/** /** @private @returns {Function|null} The Guild constructor class. */
* 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.
*/
_getGuildClass() { _getGuildClass() {
if (this._GuildClass) return this._GuildClass; if (this._GuildClass) return this._GuildClass;
try { try {
@@ -1448,6 +1274,11 @@ export class GatewayHandler {
return null; 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() { onReady() {
this._lastReadyAt = Date.now(); this._lastReadyAt = Date.now();
this.seedVoiceStatesFromGuilds(); this.seedVoiceStatesFromGuilds();
@@ -1478,14 +1309,10 @@ export class GatewayHandler {
} }
/** /**
* Rejoin all 24/7 channels after boot with staggered delays. * Boot recovery: sequentially rejoin all saved 24/7 channels.
* * Sets _bootRecoveryActive=true to suppress fake move events during the process.
* Both %247 auto and %247 on channels are rejoined because: * Cleans up missing channels from settings to prevent repeated failures.
* %247 auto: always stays in voice (disconnect + reboot) * @returns {Promise<void>}
* %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.
*/ */
async rejoin247Channels() { async rejoin247Channels() {
this._bootRecoveryActive = true; this._bootRecoveryActive = true;
@@ -1503,7 +1330,7 @@ export class GatewayHandler {
for (const channelId of channels) { for (const channelId of channels) {
const mode = get247ChannelMode(serverSettings, channelId); const mode = get247ChannelMode(serverSettings, channelId);
if (mode === "auto" || mode === "on") { if (mode === "on") {
channelsToRejoin.push({ guildId, channelId, mode }); channelsToRejoin.push({ guildId, channelId, mode });
} }
} }
@@ -1603,14 +1430,14 @@ export class GatewayHandler {
`[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.` `[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. * Process a confirmed guild deletion. Cleans up voice cache and previous state.
* Extracted from the GuildDelete handler so it can be called after the * Does NOT delete 24/7 settings (preserved for re-invite).
* startup grace period expires. * @param {string} guildId - The deleted guild ID.
* @param {string} guildId * @private
*/ */
_processGuildDelete(guildId) { _processGuildDelete(guildId) {
const { remix } = this; 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 @@
/** /** @module src/MessageHandler @description Message creation, reaction observation, permission checking, pagination, and command help display. */
* @file MessageHandler.mjs — MessageHandler — wraps Fluxer messages with reply helpers, embed builders, permission checks, and voice state utilities
* @module src.MessageHandler
*/
import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core"; import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
import { Utils } from "./Utils.mjs"; import { Utils } from "./Utils.mjs";
/** /** @type {Map<string, {name: string, desc: string}>} @description Required bot permissions with human-readable names and descriptions. */
* 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 }>}
*/
export const REQUIRED_BOT_PERMISSIONS = Object.freeze(new Map([ export const REQUIRED_BOT_PERMISSIONS = Object.freeze(new Map([
["ViewChannel", { name: "View Channels", desc: "See channels and read their content" }], ["ViewChannel", { name: "View Channels", desc: "See channels and read their content" }],
["SendMessages", { name: "Send Messages", desc: "Respond to commands and send messages" }], ["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" }], ["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"]; 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"]; 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) { export function parseColor(value, fallback = 0xe9196c) {
if (!value) return fallback; if (!value) return fallback;
if (typeof value === "number") return value; if (typeof value === "number") return value;
@@ -41,31 +32,17 @@ export function parseColor(value, fallback = 0xe9196c) {
return isNaN(n) ? fallback : n; return isNaN(n) ? fallback : n;
} }
/** Global embed color — set once at startup from config */ /** @private */
let _globalColor = 0xe9196c; let _globalColor = 0xe9196c;
/** /** Set the global embed color. @param {string|number} value */
* setGlobalColor function.
* @param {{*}} value
* @returns {*}
*/
export function setGlobalColor(value) { _globalColor = parseColor(value); } export function setGlobalColor(value) { _globalColor = parseColor(value); }
/** /** @returns {number} The current global embed color. */
* getGlobalColor function.
* @returns {*}
*/
export function getGlobalColor() { return _globalColor; } export function getGlobalColor() { return _globalColor; }
/** /** Re-export of {@link cleanId} from Utils for convenience. @type {function} */
* Strip non-digit characters from a value, returning a clean ID string.
* Re-exported from Utils.mjs for backward compatibility.
*/
export { cleanId } from "./Utils.mjs"; export { cleanId } from "./Utils.mjs";
/** /** Extract the guild ID from various message wrapper shapes. @param {object} message @returns {string|null} */
* Resolve a guild ID from various message-like shapes.
* @param {object} message
* @returns {string|null}
*/
export function getMessageGuildId(message) { export function getMessageGuildId(message) {
return message?.channel?.guildId ?? return message?.channel?.guildId ??
message?.channel?.guild?.id ?? message?.channel?.guild?.id ??
@@ -78,25 +55,18 @@ export function getMessageGuildId(message) {
null; null;
} }
/** /** @class MessageHandler @description Handles message creation, reaction observation, permission checking, and pagination. */
* MessageHandler class.
*/
export class MessageHandler { export class MessageHandler {
/** /** @type {Client} */
* Fluxer.js client instance
* @type {Client}
* @public
*/
client; client;
/** @type {Map<string, object>} Message ID → reaction observer data. */
observedReactions; observedReactions;
/** @type {Map<string, string[]>} */ /** @type {Map<string, Array>} Channel ID → user message observer callbacks. */
observedChannels; observedChannels;
/** @type {import('./constants/Locale.mjs').Locale} */ /** @type {object|null} Locale manager instance. */
locale; locale;
/** /** @param {Client} client - The Discord client. */
* @param {Client} client
*/
constructor(client) { constructor(client) {
this.client = 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; } setLocale(locale) { this.locale = locale; }
/** /** Translate a locale key. @param {string} guildId @param {string} key @param {object} [replacements={}] @returns {string} */
* Translate a locale key for a given guild.
* @param {string} guildId
* @param {string} key
* @param {Object} [replacements={}]
* @returns {string}
*/
t(guildId, key, replacements = {}) { t(guildId, key, replacements = {}) {
if (!this.locale) return key; if (!this.locale) return key;
return this.locale.translate(guildId, key, replacements); return this.locale.translate(guildId, key, replacements);
} }
/** @private Register reaction add/remove event listeners. */
setupEvents() { setupEvents() {
const reactionUpdate = (payload) => { const reactionUpdate = (payload) => {
const { userId, messageId, emoji } = payload; const { userId, messageId, emoji } = payload;
@@ -148,13 +113,7 @@ export class MessageHandler {
this.client.on(Events.MessageReactionRemove, (payload) => reactionUpdate(payload)); this.client.on(Events.MessageReactionRemove, (payload) => reactionUpdate(payload));
} }
/** /** Return the permission keys the bot is missing in a channel. @param {string[]} permissions @param {object} channel @returns {string[]} Missing permission keys. */
* 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.
*/
checkPermissions(permissions, channel) { checkPermissions(permissions, channel) {
if (!channel?.guild) return []; if (!channel?.guild) return [];
const me = channel.guild.members?.me ?? null; const me = channel.guild.members?.me ?? null;
@@ -170,14 +129,7 @@ export class MessageHandler {
return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p)); return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p));
} }
/** /** Check all REQUIRED_BOT_PERMISSIONS and split into critical vs optional. @param {object} channel @returns {{missing: string[], criticalMissing: string[], optionalMissing: string[]}} */
* 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[] }}
*/
checkAllBotPermissions(channel) { checkAllBotPermissions(channel) {
const allKeys = [...REQUIRED_BOT_PERMISSIONS.keys()]; const allKeys = [...REQUIRED_BOT_PERMISSIONS.keys()];
const missing = this.checkPermissions(allKeys, channel); const missing = this.checkPermissions(allKeys, channel);
@@ -188,14 +140,7 @@ export class MessageHandler {
}; };
} }
/** /** Build an EmbedBuilder showing missing permissions. @param {string[]} missingKeys @param {string} guildId @returns {EmbedBuilder} */
* 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}
*/
buildPermissionEmbed(missingKeys, guildId) { buildPermissionEmbed(missingKeys, guildId) {
const criticalItems = []; const criticalItems = [];
const optionalItems = []; const optionalItems = [];
@@ -237,11 +182,7 @@ export class MessageHandler {
return embed; return embed;
} }
/** /** Check permissions; send a DM or embed if missing. @async @param {string[]} permissions @param {object} message @returns {Promise<boolean>} */
* @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.
*/
async assertPermissions(permissions, message) { async assertPermissions(permissions, message) {
const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId); const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId);
if (guild && !guild.members?.me) { if (guild && !guild.members?.me) {
@@ -275,25 +216,14 @@ export class MessageHandler {
return false; return false;
} }
/** /** Register a listener for all incoming messages. @param {Function} listener */
* @callback MessageListener
* @param {Message} message
*/
/**
* Listen for new messages
* @param {MessageListener} listener
*/
onMessage(listener) { onMessage(listener) {
this.client.on(Events.MessageCreate, (msg) => { this.client.on(Events.MessageCreate, (msg) => {
listener(new Message(msg, this)); listener(new Message(msg, this));
}); });
} }
/** /** Get a wrapped Message from cache by ID. @param {string} id @returns {Message|null} */
* Get a cached message by id.
* @param {string} id
* @returns {Message|null}
*/
get(id) { get(id) {
for (const channel of this.client.channels.values()) { for (const channel of this.client.channels.values()) {
const msg = channel.messages?.get?.(id) ?? null; const msg = channel.messages?.get?.(id) ?? null;
@@ -302,12 +232,7 @@ export class MessageHandler {
return null; return null;
} }
/** /** @async Get a message from cache or fetch it from the API. @param {string} id @param {string} channelId @returns {Promise<Message|null>} */
* Either gets a message from cache or fetches it.
* @param {string} id message id
* @param {string} channelId channel id
* @returns {Promise<Message>}
*/
async getOrFetch(id, channelId) { async getOrFetch(id, channelId) {
const cached = this.get(id); const cached = this.get(id);
if (cached) return cached; if (cached) return cached;
@@ -317,20 +242,13 @@ export class MessageHandler {
return raw ? new Message(raw, this) : null; return raw ? new Message(raw, this) : null;
} }
/** /** Get a wrapped Channel by ID. @param {string} id @returns {Channel} */
* Get a cached channel by id.
* @param {string} id channel id
* @returns {Channel}
*/
getChannel(id) { getChannel(id) {
const c = this.client.channels.get(id); const c = this.client.channels.get(id);
return new Channel(c, this); return new Channel(c, this);
} }
/** /** @async Get a channel from cache or fetch from the API. @param {string} id @returns {Promise<Channel>} */
* @param {string} id
* @returns {Promise<Channel>}
*/
async getOrFetchChannel(id) { async getOrFetchChannel(id) {
const c = this.getChannel(id); const c = this.getChannel(id);
if (c?.channel) return c; if (c?.channel) return c;
@@ -338,6 +256,7 @@ export class MessageHandler {
return new Channel(raw, this); 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) { observeReactions(msg, reactions, cb, user) {
this.observedReactions.set(msg.id, { this.observedReactions.set(msg.id, {
reactions: reactions, reactions: reactions,
@@ -347,16 +266,12 @@ export class MessageHandler {
}); });
return msg.id; return msg.id;
} }
/** Stop observing reactions. @param {string} i - Observation ID. @returns {boolean} */
unobserveReactions(i) { unobserveReactions(i) {
return this.observedReactions.delete(i); return this.observedReactions.delete(i);
} }
/** /** Observe messages from a specific user in a channel. @param {string} userId @param {object} channel @param {Function} callback @returns {string} Observation ID. */
* @param {string} userId
* @param {BaseChannel} channel
* @param {MessageListener} callback
* @returns {string}
*/
observeUserMessagesChannel(userId, channel, callback) { observeUserMessagesChannel(userId, channel, callback) {
const current = (this.observedChannels.get(channel.id) || []); const current = (this.observedChannels.get(channel.id) || []);
const nonce = Utils.uid(); const nonce = Utils.uid();
@@ -368,6 +283,7 @@ export class MessageHandler {
this.observedChannels.set(channel.id, current); this.observedChannels.set(channel.id, current);
return userId + ";" + channel.id + ";" + nonce; return userId + ";" + channel.id + ";" + nonce;
} }
/** @private Stop observing a user's messages in a channel. @param {string} oid */
unobserveUserMessagesChannel(oid) { unobserveUserMessagesChannel(oid) {
const [userId, channelId, nonce] = oid.split(";"); const [userId, channelId, nonce] = oid.split(";");
const current = (this.observedChannels.get(channelId) || []); const current = (this.observedChannels.get(channelId) || []);
@@ -378,6 +294,7 @@ export class MessageHandler {
this.observedChannels.set(channelId, current); 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 = {}) { #embedify(text = "", options = {}) {
const color = options.color ?? getGlobalColor(); const color = options.color ?? getGlobalColor();
const builder = new EmbedBuilder() const builder = new EmbedBuilder()
@@ -401,6 +318,7 @@ export class MessageHandler {
return builder; return builder;
} }
/** @private Create a message payload object with an embed. @param {string} text @param {object} [options={}] @returns {{content: *, embeds: EmbedBuilder[]}} */
#createEmbed(text, options = {}) { #createEmbed(text, options = {}) {
return { return {
content: options.content ?? undefined, content: options.content ?? undefined,
@@ -408,12 +326,7 @@ export class MessageHandler {
}; };
} }
/** /** @async Reply to a message with permission checks. @param {object} replyingTo @param {string|object} message @param {boolean} [mention=false] @returns {Promise<Message|null>} */
* @param {FluxerMessage} replyingTo
* @param {string|Object} message
* @param {boolean} mention
* @returns {Promise<Message>}
*/
async reply(replyingTo, message, mention = false) { async reply(replyingTo, message, mention = false) {
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null; if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
let opts; let opts;
@@ -425,12 +338,7 @@ export class MessageHandler {
return new Message(await replyingTo.reply(opts, { ping: false }), this); return new Message(await replyingTo.reply(opts, { ping: false }), this);
} }
/** /** @async Reply with an embed. @param {object} replyingTo @param {string|object} message @param {object} [options={}] @returns {Promise<Message|null>} */
* @param {FluxerMessage} replyingTo
* @param {string|Object} message
* @param {Object} options
* @returns {Promise<Message>}
*/
async replyEmbed(replyingTo, message, options = {}) { async replyEmbed(replyingTo, message, options = {}) {
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null; 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); return new Message(await replyingTo.reply(payload, { ping: false }), this);
} }
/** /** @async Send a message to a channel. @param {object} channel @param {string|object} message @returns {Promise<Message|null>} */
* @param {BaseChannel} channel
* @param {string|Object} message
* @returns {Promise<Message>}
*/
async sendMessage(channel, message) { async sendMessage(channel, message) {
if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) { if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) {
logger.warn("[MessageHandler] Missing SendMessages/EmbedLinks permission in channel", channel.id); 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); return new Message(await channel.send(opts), this);
} }
/** /** @async Send an embed to a channel. @param {object} channel @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
* @param {BaseChannel} channel
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
async sendEmbed(channel, content, embedOptions = {}) { async sendEmbed(channel, content, embedOptions = {}) {
if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) { if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) {
return this.sendMessage(channel, typeof content === "string" ? content : content?.embedText ?? ""); 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); return new Message(await channel.send(payload), this);
} }
/** /** @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>} */
* @param {FluxerMessage} message
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
async editEmbed(message, content, embedOptions = {}) { async editEmbed(message, content, embedOptions = {}) {
const RETRYABLE = new Set([502, 503, 504]); const RETRYABLE = new Set([502, 503, 504]);
const MAX_ATTEMPTS = 3; const MAX_ATTEMPTS = 3;
@@ -537,11 +431,7 @@ export class MessageHandler {
} }
} }
/** /** @async Create a paginated message with arrow reactions. @param {PageBuilder} builder @param {Message} msg @returns {Promise<void>} */
* Initialize paginated messages.
* @param {PageBuilder} builder
* @param {Message} msg
*/
async initPagination(builder, msg) { async initPagination(builder, msg) {
const pages = builder.createPages(); const pages = builder.createPages();
if (pages.length === 0) return; if (pages.length === 0) return;
@@ -572,13 +462,7 @@ export class MessageHandler {
}, 5 * 60 * 1000); }, 5 * 60 * 1000);
} }
/** /** @async Join a voice channel using VoiceManager. @param {string} channelId @returns {Promise<object>} @throws {Error} If channel not found or not a guild channel. */
* 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 joinChannel(channelId) { async joinChannel(channelId) {
const { getVoiceManager } = await import("@fluxerjs/voice"); const { getVoiceManager } = await import("@fluxerjs/voice");
const channel = await this.client.channels.fetch(channelId).catch(() => null); const channel = await this.client.channels.fetch(channelId).catch(() => null);
@@ -590,57 +474,45 @@ export class MessageHandler {
} }
} }
/** /** @class Channel @description Wrapper around a Discord channel object providing helpers for sending messages and observing users. */
* Channel class.
*/
export class Channel { export class Channel {
/** /** @type {object} The raw channel object. */
* The actual underlying fluxer.js channel instance
* @type {import("@fluxerjs/core").BaseChannel}
*/
channel; channel;
/** @type {MessageHandler} */ /** @type {MessageHandler} */
handler; handler;
/** /** @param {object} channel @param {MessageHandler} handler */
* @param {import("@fluxerjs/core").BaseChannel} channel
* @param {MessageHandler} handler
*/
constructor(channel, handler) { constructor(channel, handler) {
this.channel = channel; this.channel = channel;
this.handler = handler; this.handler = handler;
} }
/** @type {Guild} */ /** @returns {object|null} The guild this channel belongs to. */
get server() { get server() {
return this.channel?.guild ?? null; return this.channel?.guild ?? null;
} }
/** @type {Guild} */ /** @returns {object|null} Alias for server (guild). */
get guild() { get guild() {
return this.channel?.guild ?? null; return this.channel?.guild ?? null;
} }
/** @type {boolean} */ /** @returns {boolean} Whether this channel is a voice channel. */
get isVoice() { get isVoice() {
return this.channel?.isVoiceBased?.() ?? false; return this.channel?.isVoiceBased?.() ?? false;
} }
/** @type {string} */ /** @returns {string} The channel ID. */
get id() { get id() {
return this.channel?.id; return this.channel?.id;
} }
/** @type {string} */ /** @returns {string|null} The guild ID. */
get guildId() { get guildId() {
return this.channel?.guildId ?? null; return this.channel?.guildId ?? null;
} }
/** @type {string} */ /** @returns {string|null} Alias for guildId. */
get serverId() { get serverId() {
return this.guildId; return this.guildId;
} }
/** /** Observe messages from a specific user in this channel. @param {Function} callback @param {object} user @returns {Function} Unobserve function. */
* @param {MessageListener} callback
* @param {User} user
* @returns {Function}
*/
onMessageUser(callback, user) { onMessageUser(callback, user) {
const resolvedUserId = user?.id const resolvedUserId = user?.id
?? user?._id ?? user?._id
@@ -656,92 +528,67 @@ export class Channel {
}; };
} }
/** /** Send a message to this channel. @param {string|object} content @returns {Promise<Message|null>} */
* @param {string|Object} content
* @returns {Promise<Message>}
*/
sendMessage(content) { sendMessage(content) {
return this.handler.sendMessage(this.channel, content); return this.handler.sendMessage(this.channel, content);
} }
/** /** Alias for sendMessage. @param {string|object} content @returns {Promise<Message|null>} */
* @param {string|Object} content
* @returns {Promise<Message>}
*/
send(content) { send(content) {
return this.handler.sendMessage(this.channel, content); return this.handler.sendMessage(this.channel, content);
} }
/** /** Send an embed to this channel. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
sendEmbed(content, embedOptions = {}) { sendEmbed(content, embedOptions = {}) {
return this.handler.sendEmbed(this.channel, content, embedOptions); return this.handler.sendEmbed(this.channel, content, embedOptions);
} }
/** /** Join this voice channel. @async @returns {Promise<object>} @throws {Error} If not a voice channel. */
* @returns {Promise<import("@fluxerjs/voice").VoiceConnection>}
*/
join() { join() {
if (!this.isVoice) throw new Error("Cannot join a text channel. Attempting to 'join' into channel `" + this.channel?.id + "`"); 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); return this.handler.joinChannel(this.channel.id);
} }
} }
/** /** @class Message @description Wrapper around a Discord message providing helpers for replying, editing, and reaction observation. */
* Message class.
*/
export class Message { export class Message {
/** /** @type {object} */
* The actual underlying message instance
* @type {import("@fluxerjs/core").Message}
*/
message; message;
/** @type {MessageHandler} */ /** @type {MessageHandler} */
handler; handler;
/** /** @param {object} message @param {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
*/
constructor(message, handler) { constructor(message, handler) {
this.message = message; this.message = message;
this.handler = handler; this.handler = handler;
} }
/** @type {string} */ /** @returns {string} The raw message content. */
get content() { get content() {
return this.message.content; return this.message.content;
} }
/** @type {string} */ /** @returns {string} The message ID. */
get id() { get id() {
return this.message.id; return this.message.id;
} }
/** @type {User} */ /** @returns {object} The author object. */
get author() { get author() {
return this.message.author; return this.message.author;
} }
/** @type {string} */ /** @returns {string} The author's user ID. */
get authorId() { get authorId() {
return this.message.author?.id; return this.message.author?.id;
} }
/** @type {GuildMember|null} */ /** @returns {object|null} The guild member, if available. */
get member() { get member() {
return this.message.member ?? null; return this.message.member ?? null;
} }
/** @type {Channel} */ /** @returns {Channel} The wrapped channel this message was sent in. */
get channel() { get channel() {
return this.handler.getChannel(this.message.channelId); return this.handler.getChannel(this.message.channelId);
} }
/** /** Observe reactions on this message. @param {string[]} reactions @param {Function} callback @param {object} [user=null] @returns {Function} Unobserve function. */
* @param {string[]} reactions
* @param {function} callback
* @param {User} [user]
* @returns {function} unobserve
*/
onReaction(reactions, callback, user = null) { onReaction(reactions, callback, user = null) {
const oid = this.handler.observeReactions(this.message, reactions, callback, user); const oid = this.handler.observeReactions(this.message, reactions, callback, user);
return () => { return () => {
@@ -749,21 +596,12 @@ export class Message {
}; };
} }
/** /** Reply to this message. @param {string|object} content @param {boolean} [mention=false] @returns {Promise<Message|null>} */
* @param {string|Object} content
* @param {boolean} mention
* @returns {Promise<Message>}
*/
reply(content, mention = false) { reply(content, mention = false) {
return this.handler.reply(this.message, content, mention); return this.handler.reply(this.message, content, mention);
} }
/** /** Reply to this message with an embed. @param {string|object} content @param {boolean} [mention=false] @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
* @param {string|Object} content
* @param {boolean} mention
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
replyEmbed(content, mention = false, embedOptions = {}) { replyEmbed(content, mention = false, embedOptions = {}) {
return this.handler.replyEmbed(this.message, content, { return this.handler.replyEmbed(this.message, content, {
mention, mention,
@@ -771,39 +609,31 @@ export class Message {
}); });
} }
/** /** Edit this message's embed. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
editEmbed(content, embedOptions = {}) { editEmbed(content, embedOptions = {}) {
return this.handler.editEmbed(this.message, content, embedOptions); return this.handler.editEmbed(this.message, content, embedOptions);
} }
/** /** Alias for editEmbed. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
* @param {string|Object} content
* @param {Object} embedOptions
* @returns {Promise<Message>}
*/
edit(content, embedOptions = {}) { edit(content, embedOptions = {}) {
return this.handler.editEmbed(this.message, content, embedOptions); return this.handler.editEmbed(this.message, content, embedOptions);
} }
} }
/** /** @class PageBuilder @description Splits content into pages with template-based formatting. */
* PageBuilder class.
*/
export class PageBuilder { export class PageBuilder {
/** @type {string} Template form string with $maxPage, $currentPage, $content placeholders. */
form = ""; form = "";
/** @type {number} Maximum lines per page. */
maxLinesPerPage = 2; maxLinesPerPage = 2;
/** @type {string[]} */ /** @type {Array|string[]} Content lines or array items. */
content = []; content = [];
/** @type {boolean} Whether pages have been created. */
initiated = false; initiated = false;
/** @type {Array<Array>} Created page arrays. */
pages = []; pages = [];
/** /** @param {string|Array} content - String to split by newlines or an array of items. */
* @param {string|string[]} content
*/
constructor(content) { constructor(content) {
if (!Array.isArray(content)) { if (!Array.isArray(content)) {
this.content = content.split("\n"); this.content = content.split("\n");
@@ -812,18 +642,21 @@ export class PageBuilder {
this.content = content; this.content = content;
} }
/** Set the template form string with $maxPage, $currentPage, $content placeholders. @param {string} form @returns {PageBuilder} */
setForm(form) { setForm(form) {
this.form = form; this.form = form;
this.initiated = false; this.initiated = false;
return this; return this;
} }
/** Set the maximum lines per page. @param {number} [maxLinesPerPage=2] @returns {PageBuilder} */
setMaxLines(maxLinesPerPage = 2) { setMaxLines(maxLinesPerPage = 2) {
this.maxLinesPerPage = maxLinesPerPage; this.maxLinesPerPage = maxLinesPerPage;
this.initiated = false; this.initiated = false;
return this; return this;
} }
/** Create page arrays from content. Lazily initialized; returns cached pages if already created. @returns {Array<Array>} */
createPages() { createPages() {
if (this.initiated) return this.pages; if (this.initiated) return this.pages;
@@ -840,10 +673,7 @@ export class PageBuilder {
return pages; return pages;
} }
/** /** Get a formatted page string by index (0-based). @param {number} n @returns {string|null} */
* @param {number} n
* @returns {string|null}
*/
getPage(n) { getPage(n) {
const pages = this.createPages(); const pages = this.createPages();
if (!pages[n]) return null; if (!pages[n]) return null;
@@ -854,38 +684,22 @@ export class PageBuilder {
.replace(/\$content/gi, pages[n].join("\n")); .replace(/\$content/gi, pages[n].join("\n"));
} }
/** /** Get raw page content by index (0-based) without template formatting. @param {number} n @returns {string|null} */
* @param {number} n
* @returns {string|null}
*/
getContent(n) { getContent(n) {
const pages = this.createPages(); const pages = this.createPages();
if (!pages[n]) return null; if (!pages[n]) return null;
return pages[n].join("\n"); return pages[n].join("\n");
} }
/** @returns {number} */ /** Get the total number of pages. @returns {number} */
size() { size() {
return this.pages.length; return this.pages.length;
} }
} }
/** /** @class RichPaginator @description Multi-tab paginated embed with tab and arrow navigation via reactions. */
* 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();
*/
export class RichPaginator { export class RichPaginator {
/** /** @param {Message} msg @param {MessageHandler} handler */
* @param {Message} msg
* @param {MessageHandler} handler
*/
constructor(msg, handler) { constructor(msg, handler) {
this._msg = msg; this._msg = msg;
this._handler = handler; this._handler = handler;
@@ -897,24 +711,19 @@ export class RichPaginator {
this._state = { tab: 0, page: 0 }; 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; } 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; } 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; } 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; } setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; }
/** /** 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} */
* 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)
*/
addTab(tab) { addTab(tab) {
this._tabs.push({ this._tabs.push({
emoji: tab.emoji, emoji: tab.emoji,
@@ -925,6 +734,7 @@ export class RichPaginator {
return this; return this;
} }
/** @private Build an embed for a given tab and sub-page. @param {number} tabIdx @param {number} pageIdx @returns {EmbedBuilder} */
_buildEmbed(tabIdx, pageIdx) { _buildEmbed(tabIdx, pageIdx) {
const tab = this._tabs[tabIdx]; const tab = this._tabs[tabIdx];
const totalTabs = this._tabs.length; const totalTabs = this._tabs.length;
@@ -943,6 +753,7 @@ export class RichPaginator {
.setFooter({ text: footerParts.join(" ") }); .setFooter({ text: footerParts.join(" ") });
} }
/** @async Send the paginated embed and start observing reactions. @returns {Promise<object|null>} The raw sent message. */
async send() { async send() {
if (this._tabs.length === 0) return null; if (this._tabs.length === 0) return null;
@@ -992,6 +803,7 @@ export class RichPaginator {
rawMsg.edit({ embeds: [buildEmbed(state.tab, state.page)] }).catch(() => {}); rawMsg.edit({ embeds: [buildEmbed(state.tab, state.page)] }).catch(() => {});
}); });
/** @private Clear all reactions on the paginator message. */
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await rawMsg.removeAllReactions(); await rawMsg.removeAllReactions();
@@ -1006,6 +818,7 @@ export class RichPaginator {
} }
}; };
/** @private Close the pagination session, update footer, and clear reactions. */
const closeSession = async () => { const closeSession = async () => {
unobserve(); unobserve();
const currentEmbed = buildEmbed(state.tab, state.page); const currentEmbed = buildEmbed(state.tab, state.page);
@@ -1017,6 +830,7 @@ export class RichPaginator {
let timer = setTimeout(closeSession, this._timeout); let timer = setTimeout(closeSession, this._timeout);
/** @private Reset the inactivity timer. */
const resetTimer = () => { const resetTimer = () => {
clearTimeout(timer); clearTimeout(timer);
timer = setTimeout(closeSession, this._timeout); timer = setTimeout(closeSession, this._timeout);
@@ -1032,23 +846,9 @@ export class RichPaginator {
} }
} }
/** /** @class QueuePaginator @description Simple two-arrow paginator for queue embeds with page count. */
* 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 }
*/
export class QueuePaginator { 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) { constructor(msg, handler, client) {
this._msg = msg; this._msg = msg;
this._handler = handler; this._handler = handler;
@@ -1058,17 +858,13 @@ export class QueuePaginator {
this._next = "➡️"; this._next = "➡️";
} }
/** @param {number} ms */ /** Set the session timeout duration. @param {number} ms @returns {QueuePaginator} */
setTimeout(ms) { this._timeout = ms; return this; } 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; } setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; }
/** /** @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. */
* @param {function(page: number): object} buildEmbed - returns a raw embed object
* @param {number} totalPages
* @param {number} [startPage=1]
*/
async send(buildEmbed, totalPages, startPage = 1) { async send(buildEmbed, totalPages, startPage = 1) {
const state = { page: Math.max(1, Math.min(startPage, totalPages)) }; const state = { page: Math.max(1, Math.min(startPage, totalPages)) };
const nativeMsg = this._msg.message ?? this._msg; 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 channelId = rawMsg.channelId ?? rawMsg.channel_id ?? rawMsg.channel?.id;
const msgId = rawMsg.id; const msgId = rawMsg.id;
/** @private Clear all reactions on the paginator message. */
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await rawMsg.removeAllReactions(); await rawMsg.removeAllReactions();
@@ -1106,6 +903,7 @@ export class QueuePaginator {
} }
}; };
/** @private Close the pagination session, update footer, and clear reactions. */
const closeSession = async () => { const closeSession = async () => {
unobserve(); unobserve();
const embed = buildEmbed(state.page); const embed = buildEmbed(state.page);
@@ -1120,6 +918,7 @@ export class QueuePaginator {
}; };
let timer = setTimeout(closeSession, this._timeout); let timer = setTimeout(closeSession, this._timeout);
/** @private Reset the inactivity timer. */
const resetTimer = () => { const resetTimer = () => {
clearTimeout(timer); clearTimeout(timer);
timer = setTimeout(closeSession, this._timeout); 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; const HELP_CMDS_PER_PAGE = 10;
/** @type {number} Help paginator session timeout in milliseconds. */
const HELP_SESSION_MS = 30 * 1000; const HELP_SESSION_MS = 30 * 1000;
const HELP_TABS = [ const HELP_TABS = [
@@ -1168,6 +969,7 @@ const HELP_TABS = [
}, },
]; ];
/** @private @param {string} prefix @returns {string} */
function _helpHomeContent(prefix) { function _helpHomeContent(prefix) {
return ( return (
"**Welcome to the Remix help page.**\n\n" + "**Welcome to the Remix help page.**\n\n" +
@@ -1182,6 +984,7 @@ function _helpHomeContent(prefix) {
); );
} }
/** @private @returns {string} */
function _helpSupportContent() { function _helpSupportContent() {
return ( return (
"If you need help with anything or encounter any issues, hop over to " + "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) { function _helpBuildCategoryPages(tab, allCmds, prefix) {
const cmds = allCmds const cmds = allCmds
.filter(cmd => { .filter(cmd => {
@@ -1219,29 +1023,16 @@ function _helpBuildCategoryPages(tab, allCmds, prefix) {
return pages; return pages;
} }
/** /** @class HelpCommand @description Rich paginated help command with tabbed navigation (Home, Music, Utilities, Support). */
* HelpCommand class.
*/
export class HelpCommand { export class HelpCommand {
/** /** @param {CommandHandler} commandHandler @param {MessageHandler} messageHandler @param {Function} getSettingsFn */
* @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)
*/
constructor(commandHandler, messageHandler, getSettingsFn) { constructor(commandHandler, messageHandler, getSettingsFn) {
this._commands = commandHandler; this._commands = commandHandler;
this._messages = messageHandler; this._messages = messageHandler;
this._getSettings = getSettingsFn; this._getSettings = getSettingsFn;
} }
/** /** Register the help command, intercept invalid command replies, and intercept help aliases. */
* 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() { register() {
if (this._registered) return; if (this._registered) return;
this._registered = true; 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) { _handle(msg, args, prefix) {
const allCmds = this._commands.commands; const allCmds = this._commands.commands;
const query = (args[0] ?? "").trim(); 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); }
}
}
+679 -1460
View File
File diff suppressed because it is too large. Load diff
+70 -179
View File
@@ -1,14 +1,4 @@
/** /** @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. */
* @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.
*/
import Player from "./Player.mjs"; import Player from "./Player.mjs";
import { Utils, cleanId } from "./Utils.mjs"; import { Utils, cleanId } from "./Utils.mjs";
@@ -21,6 +11,7 @@ import { Dashboard } from "./dashboard/Dashboard.mjs";
import { hasHumansInChannel, iterateVoiceStates } from "./constants/VoiceStateResolver.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) { function getPlayerGuildId(player, fallbackChannel = null) {
return cleanId( return cleanId(
player?._guildId ?? 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) { function getPlayerChannelId(player, fallbackChannelId = null) {
return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId); return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId);
} }
/** /** @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. */
* 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
*/
function botHasVoicePermissions(client, channelId) { function botHasVoicePermissions(client, channelId) {
try { try {
const channel = client?.channels?.get?.(channelId); const channel = client?.channels?.get?.(channelId);
@@ -63,19 +46,7 @@ function botHasVoicePermissions(client, channelId) {
} }
} }
/** /** @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. */
* 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").
*/
function sanitizeJoinError(err, client = null, channelId = null) { function sanitizeJoinError(err, client = null, channelId = null) {
const msg = String(err?.message ?? err ?? ""); const msg = String(err?.message ?? err ?? "");
if (msg.includes("401") || msg.includes("Unauthorized")) { if (msg.includes("401") || msg.includes("Unauthorized")) {
@@ -99,47 +70,49 @@ function sanitizeJoinError(err, client = null, channelId = null) {
return null; return null;
} }
/** /** @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. */
* PlayerManager class.
*/
export class PlayerManager { export class PlayerManager {
/** @type {SettingsManager} */ /** @type {RemoteSettingsManager} */
settings; settings;
/** @type {CommandHandler} */ /** @type {CommandHandler} */
commands; commands;
/** @type {Map<string, Player>} Keyed by cleaned channel ID */ /** @type {Map<string, Player>} Player instances keyed by channel ID. */
playerMap = new Map(); 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(); _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(); _pendingJoins = new Set();
/** @type {Map<string, {timer, songUrl, startedAtMs}>} Pending scrobble timers keyed by channel ID. /** @private @type {Map<string, {timer: setTimeout, songUrl: string, startedAtMs: number}>} */
* Prevents duplicate scrobbles when startplay fires multiple times. */
_pendingScrobbleTimers = new Map(); _pendingScrobbleTimers = new Map();
/** @type {Object} */ /** @type {object} Full bot config. */
config; config;
/** @type {Object} */ /** @type {object} Player-specific config (lavalink reference). */
playerConfig; playerConfig;
/** @type {import("./constants/Locale.mjs").Locale|null} */ /** @type {Locale|null} */
locale = null; locale = null;
/** @type {import("./dashboard/Dashboard.mjs").Dashboard|null} */ /** @type {Dashboard|null} */
dashboard = null; dashboard = null;
/** /**
* @param {SettingsManager} settings * Create a new PlayerManager.
* @param {CommandHandler} commands * @param {RemoteSettingsManager} settings - The settings manager.
* @param {Object} config * @param {CommandHandler} commands - The command handler.
* @param {Object} config.config - Parsed config.json * @param {object} config - Configuration object.
* @param {Object} config.player - Config data passed to new Player instances * @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) { constructor(settings, commands, config) {
this.commands = commands; this.commands = commands;
@@ -153,12 +126,7 @@ export class PlayerManager {
this.trackOptions = config.trackOptions ?? null; this.trackOptions = config.trackOptions ?? null;
} }
/** /** @private Index a player by guild and channel ID for fast lookups. @param {string} guildId @param {string} channelId */
* Add a channel to the guild→player reverse index.
* Called after a successful player join.
* @param {string} guildId
* @param {string} channelId
*/
_indexPlayer(guildId, channelId) { _indexPlayer(guildId, channelId) {
const gId = cleanId(guildId); const gId = cleanId(guildId);
const cId = cleanId(channelId); const cId = cleanId(channelId);
@@ -168,12 +136,7 @@ export class PlayerManager {
set.add(cId); set.add(cId);
} }
/** /** @private Remove a player from the guild-player index. @param {string} guildId @param {string} channelId */
* Remove a channel from the guild→player reverse index.
* Called on player leave/destroy.
* @param {string} guildId
* @param {string} channelId
*/
_unindexPlayer(guildId, channelId) { _unindexPlayer(guildId, channelId) {
const gId = cleanId(guildId); const gId = cleanId(guildId);
const cId = cleanId(channelId); const cId = cleanId(channelId);
@@ -185,12 +148,7 @@ export class PlayerManager {
} }
} }
/** /** Get all active (non-destroyed) players for a guild. @param {string} guildId @returns {Array<[string, Player]>} Array of [channelId, Player] pairs. */
* 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]>}
*/
getGuildPlayers(guildId) { getGuildPlayers(guildId) {
const gId = cleanId(guildId); const gId = cleanId(guildId);
const set = this._guildPlayerIndex.get(gId); const set = this._guildPlayerIndex.get(gId);
@@ -207,13 +165,8 @@ export class PlayerManager {
return result; return result;
} }
/** /** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */
* Find a player by guildId and channelId using the reverse index. getPlayerByGuildAndChannel(guildId, channelId) {
* @param {string} guildId
* @param {string} channelId
* @returns {Player|null}
*/
getPlayerByGuildAndChannel(guildId, channelId) {
const cId = cleanId(channelId); const cId = cleanId(channelId);
const players = this.getGuildPlayers(guildId); const players = this.getGuildPlayers(guildId);
for (const [mapChannelId, player] of players) { for (const [mapChannelId, player] of players) {
@@ -222,12 +175,8 @@ export class PlayerManager {
return null; return null;
} }
/** /** Find a player by its channel ID across all guilds. @param {string} channelId @returns {Player|null} */
* Find a player by channelId alone (scans guild index first, then fallback). getPlayerByChannelId(channelId) {
* @param {string} channelId
* @returns {Player|null}
*/
getPlayerByChannelId(channelId) {
const cId = cleanId(channelId); const cId = cleanId(channelId);
for (const [, channelSet] of this._guildPlayerIndex) { for (const [, channelSet] of this._guildPlayerIndex) {
for (const mapChannelId of channelSet) { for (const mapChannelId of channelSet) {
@@ -238,22 +187,7 @@ export class PlayerManager {
return null; return null;
} }
/** /** Bind dashboard update and message-sending events on a player. @param {Player} player @param {object} [context={}] @returns {Player} The same player, with events bound. */
* 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}
*/
setupEvents(player, context = {}) { setupEvents(player, context = {}) {
if (!player || player._dashboardEventsBound) return player; if (!player || player._dashboardEventsBound) return player;
@@ -409,25 +343,14 @@ export class PlayerManager {
return player; return player;
} }
/** /** @private Translate a locale key for a message context. @param {object} message @param {string} key @param {object} [replacements={}] @returns {string} */
* Translate a locale key using the message's guild locale.
* @param {Object} message
* @param {string} key
* @param {Object} [replacements={}]
* @returns {string}
*/
_t(message, key, replacements = {}) { _t(message, key, replacements = {}) {
if (!this.locale) return key; if (!this.locale) return key;
const guildId = getMessageGuildId(message); const guildId = getMessageGuildId(message);
return this.locale.translate(guildId, key, replacements); return this.locale.translate(guildId, key, replacements);
} }
/** /** 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}>} */
* 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}>}
*/
async checkVoiceChannels(message, settings) { async checkVoiceChannels(message, settings) {
const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message); const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message);
const userId = message?.author?.id ?? message?.member?.user?.id; const userId = message?.author?.id ?? message?.member?.user?.id;
@@ -494,15 +417,8 @@ export class PlayerManager {
return { channelId, alreadyInVoice, hasHumans: hasHumansResult }; return { channelId, alreadyInVoice, hasHumans: hasHumansResult };
} }
/** /** 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>} */
* Get or create a player for the user's voice channel. async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) {
* @param {Message} 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 guildId = getMessageGuildId(message);
const cleanGuildId = cleanId(guildId); const cleanGuildId = cleanId(guildId);
@@ -586,11 +502,7 @@ export class PlayerManager {
return null; return null;
} }
/** /** Prompt the user to select a voice channel via reactions or text input. @async @param {object} msg @returns {Promise<Player|false>} */
* Prompt the user to select a voice channel.
* @param {Message} msg
* @returns {Promise<string|false>}
*/
async promptVC(msg) { async promptVC(msg) {
const { channelId: autoDetected } = await this.checkVoiceChannels(msg); const { channelId: autoDetected } = await this.checkVoiceChannels(msg);
if (autoDetected) { if (autoDetected) {
@@ -675,11 +587,7 @@ export class PlayerManager {
}); });
} }
/** /** Leave a voice channel, destroy the player, and send a confirmation. @async @param {object} msg @param {string} [cid] @returns {Promise<void>} */
* Make the player leave its current voice channel.
* @param {Message} msg
* @param {string} [cid]
*/
async leave(msg, cid) { async leave(msg, cid) {
if (!cid) { if (!cid) {
const guildId = getMessageGuildId(msg); const guildId = getMessageGuildId(msg);
@@ -714,11 +622,7 @@ export class PlayerManager {
await msg.reply(this._t(msg, "responses._common.successfullyLeft")); await msg.reply(this._t(msg, "responses._common.successfullyLeft"));
} }
/** /** @private Restore saved volume for a player from guild settings. @param {Player} player @param {string} guildId */
* Restore saved volume for a player from server settings.
* @param {Player} player
* @param {string} guildId
*/
_restorePlayerVolume(player, guildId) { _restorePlayerVolume(player, guildId) {
const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume"); const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume");
if (savedVol !== undefined && savedVol !== null) { if (savedVol !== undefined && savedVol !== null) {
@@ -727,12 +631,7 @@ export class PlayerManager {
} }
} }
/** /** 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. */
* Create and register a new Player for the given voice channel.
* @param {Message} message
* @param {string} cid - Voice channel ID
* @returns {Promise<Player|null>}
*/
async initPlayer(message, cid) { async initPlayer(message, cid) {
const channel = this.commands.client?.channels?.get(cid); const channel = this.commands.client?.channels?.get(cid);
@@ -775,9 +674,7 @@ export class PlayerManager {
...this.playerConfig, ...this.playerConfig,
client: this.commands.client, client: this.commands.client,
config: this.config, config: this.config,
nodelink: this.config.nodelink, lavalink: this.playerConfig?.lavalink ?? null,
moonlink: this.playerConfig?.moonlink ?? null,
revoice: this.playerConfig?.revoice ?? null,
settingsMgr: this.settings, settingsMgr: this.settings,
getPrefix: (guildId) => this.commands.getPrefix(guildId), getPrefix: (guildId) => this.commands.getPrefix(guildId),
observedVoiceUsers: this.observedVoiceUsers ?? null, observedVoiceUsers: this.observedVoiceUsers ?? null,
@@ -818,8 +715,8 @@ export class PlayerManager {
? get247ChannelMode(this.settings.getServer(guildId), matchChannel) ? get247ChannelMode(this.settings.getServer(guildId), matchChannel)
: "off"; : "off";
if (mode247 === "auto" || mode247 === "on") { if (mode247 === "on") {
logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 ${mode247} channel ${activeChannelId} (guild ${guildId})`); logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 channel ${activeChannelId} (guild ${guildId})`);
return; return;
} }
if (player._hasHumansInChannel()) { if (player._hasHumansInChannel()) {
@@ -841,17 +738,8 @@ export class PlayerManager {
const prefix = this.commands.getPrefix(guildId); const prefix = this.commands.getPrefix(guildId);
let desc; const desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive", { channel: `<#${activeChannelId}>`, prefix })
if (mode247 === "on") { ?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247\``;
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\``;
}
if (typeof ch?.send === "function") { if (typeof ch?.send === "function") {
ch.send({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)], allowedMentions: { parse: [] } }).catch(err => { ch.send({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)], allowedMentions: { parse: [] } }).catch(err => {
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) { if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
@@ -862,6 +750,18 @@ export class PlayerManager {
}); });
player.on("message", (m) => { 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; let ch = player.textChannel;
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch })); 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()); ["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return; if (disabled) return;
if (!ch || typeof ch.send !== "function") { if (!isTextChannel(ch)) {
try { try {
const serverSettings = this.settings.getServer(guildId); const serverSettings = this.settings.getServer(guildId);
const savedAnnChId = serverSettings?.get?.("announcementChannelId"); const savedAnnChId = serverSettings?.get?.("announcementChannelId");
if (savedAnnChId) { 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) { } catch(e) {
logger.warn("[PlayerManager] Failed to resolve announcement channel:", e?.message); logger.warn("[PlayerManager] Failed to resolve announcement channel:", e?.message);
} }
} }
if (!ch || typeof ch.send !== "function") { if (!isTextChannel(ch)) {
try { try {
const guild = this.commands?.client?.guilds?.get?.(guildId); const guild = this.commands?.client?.guilds?.get?.(guildId);
if (guild?.systemChannelId) { 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) { } catch(e) {
logger.warn("[PlayerManager] Failed to resolve system channel:", e?.message); logger.warn("[PlayerManager] Failed to resolve system channel:", e?.message);
} }
} }
if (!ch || typeof ch.send !== "function") { if (!isTextChannel(ch)) {
try { try {
const guild = this.commands?.client?.guilds?.get?.(guildId); const guild = this.commands?.client?.guilds?.get?.(guildId);
if (guild?.channels) { if (guild?.channels) {
for (const c of (guild.channels.values?.() ?? [])) { for (const c of (guild.channels.values?.() ?? [])) {
if (c.isTextBased?.() || c.type === 0 || c.type === "GUILD_TEXT") { if (isTextChannel(c)) {
ch = c; ch = c;
break; break;
} }
@@ -906,12 +808,12 @@ export class PlayerManager {
logger.warn("[PlayerManager] Failed to find fallback text channel:", e?.message); logger.warn("[PlayerManager] Failed to find fallback text channel:", e?.message);
} }
} }
if (!ch || typeof ch.send !== "function") { if (!isTextChannel(ch)) {
logger.warn(`[PlayerManager] Could not resolve any channel to send now-playing announcement (guild ${guildId})`); logger.warn(`[PlayerManager] Could not resolve any text channel to send now-playing announcement (guild ${guildId})`);
return; 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) const payload = typeof m === "object" && Array.isArray(m.embeds)
? { ...m, allowedMentions: { parse: [] } } ? { ...m, allowedMentions: { parse: [] } }
@@ -948,10 +850,6 @@ export class PlayerManager {
logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`); logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`);
try { try {
await new Promise(r => setTimeout(r, 2_000)); 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); await player.join(cid);
this.playerMap.set(cleanChannelId, player); this.playerMap.set(cleanChannelId, player);
@@ -982,14 +880,7 @@ export class PlayerManager {
} }
} }
/** /** @private Handle Last.fm now-playing update and schedule scrobble timer. @param {Player} player @param {object} song */
* 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
*/
_handleLastFmStartPlay(player, song) { _handleLastFmStartPlay(player, song) {
const lastfm = this._lastfm; const lastfm = this._lastfm;
if (!lastfm?.enabled) return; if (!lastfm?.enabled) return;
+284 -122
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 fs from "node:fs";
import { logger } from "./constants/Logger.mjs";
import mysql from "mysql2"; import mysql from "mysql2";
import { EventEmitter } from "node:events"; import { EventEmitter } from "node:events";
import { logger } from "./constants/Logger.mjs";
/** /**
* Abstract base class for settings managers. * Base settings manager providing defaults, descriptions, and key utilities.
* Provides the interface that all concrete settings managers must implement. * Subclassed by RemoteSettingsManager for MySQL-backed persistence.
* @extends {EventEmitter}
*/ */
export class SettingsManager extends EventEmitter { export class SettingsManager extends EventEmitter {
/** @abstract @type {Object} */ /** @type {object} Default setting values keyed by setting name. */
defaults; defaults;
/** @abstract */
update(server, key) { } /** @type {object} Setting descriptions keyed by setting name. */
/** @abstract @returns {ServerSettings} */ descriptions;
getServer(id) { }
/** @abstract @returns {boolean} */ /** @type {Set<string>} Internal keys hidden from getPublicKeys(). */
hasServer(id) { } internalKeys;
/** @abstract @returns {boolean} */
isOption(key) { } /**
* 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);
}
/**
* 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));
}
} }
/** /**
* ServerSettings class. * Per-guild settings container. Delegates persistence to a RemoteSettingsManager.
* All mutations call manager.update() which triggers a debounced DB write.
*/ */
export class ServerSettings { export class ServerSettings {
/** @type {string} The guild ID. */
id; id;
/** @type {RemoteSettingsManager} The parent settings manager. */
manager; manager;
/** @type {object} Key-value store of current setting values. */
data = {}; data = {};
/** /**
* @param {string} id Guild ID these settings belong to * Create a new ServerSettings instance for a guild.
* @param {SettingsManager} mgr Owning settings manager, used for defaults and persistence * @param {string} id - The guild ID.
* @param {RemoteSettingsManager} mgr - The parent settings manager.
*/ */
constructor(id, mgr) { constructor(id, mgr) {
this.id = id; this.id = id;
this.manager = mgr; this.manager = mgr;
this.loadDefaults(); 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); } 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]; } 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]); } 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 }; } get serializationData() { return { ...this.data, id: this.id }; }
/** @returns {object} Alias for serializationData. */
serialize() { return this.serializationData; } serialize() { return this.serializationData; }
/** @returns {object} Alias for serializationData. */
serializeObject() { return this.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 { export class RemoteSettingsManager extends SettingsManager {
/** @type {Map<string, ServerSettings>} Cached guild settings keyed by guild ID. */
guilds = new Map(); guilds = new Map();
descriptions = {};
defaults = {}; /** @type {import('mysql2').Pool} MySQL connection pool. */
db = null; 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; 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; _hasBotIdColumn = false;
/** @private */
_loadAttempts = 0; _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; _loadPromise = null;
/** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */
_debounceTimers = new Map(); _debounceTimers = new Map();
/** @private @type {boolean} True after shutdown() is called. */
_shuttingDown = false;
/** /**
* @param {Object} config MySQL connection config passed to mysql2's createPool * Create a new RemoteSettingsManager backed by a MySQL pool.
* @param {string} defaultsPath Filesystem path to the JSON file with default guild settings * @param {object} config - mysql2 pool configuration (host, user, password, database).
* @param {string|null} [botId=null] Bot user ID for multi-bot row isolation, or null for single-bot mode * @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) { constructor(config, defaultsPath, botId = null) {
super(); super();
this.botId = botId; this.botId = botId;
this.db = mysql.createPool({ connectionLimit: 15, ...config }); this.db = mysql.createPool({ connectionLimit: 15, ...config });
this.db.on("error", (err) => { this.db.on('error', (err) => {
logger.error("[DB] MySQL pool error:", err.code ?? err.message); logger.error('[DB] MySQL pool error:', err.code ?? err.message);
}); });
if (defaultsPath) this.loadDefaultsSync(defaultsPath); 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 * Stop all pending debounced writes. Call before process exit.
* part of the primary key. If the column is missing, auto-migrate by * @returns {Promise<void>}
* 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), async shutdown() {
* fix the NULL values and retry the PK update. 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() { async _ensureBotIdColumn() {
if (this._hasBotIdColumn) return; if (this._hasBotIdColumn) return;
const res = await this.query( const res = await this.query(
`SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS ` `SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS `
+ `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'` + `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'`
); );
if (res.error) { 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; return;
} }
if (res.results.length === 0) { if (res.results.length === 0) {
logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); 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 ''`);
const alterRes = await this.query(
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`
);
if (alterRes.error) { 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; return;
} }
if (this.botId) { if (this.botId) {
await this.query( await this.query(`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`);
`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) { if (pkRes.error) {
logger.error("[Settings] Failed to update primary key:", pkRes.error); logger.error('[Settings] Failed to update primary key:', pkRes.error);
return; return;
} }
this._hasBotIdColumn = true; this._hasBotIdColumn = true;
logger.settings("[Settings] Auto-migration complete: bot_id column added."); logger.settings('[Settings] Auto-migration complete: bot_id column added.');
return; return;
} }
const colInfo = res.results[0]; const colInfo = res.results[0];
const isNullable = colInfo.IS_NULLABLE === 'YES'; if (colInfo.COLUMN_KEY === 'PRI') {
const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI';
if (isPrimaryKey) {
this._hasBotIdColumn = true; this._hasBotIdColumn = true;
return; return;
} }
logger.settings('[Settings] Fixing bot_id column: adding to primary key...');
logger.settings("[Settings] Fixing bot_id column: adding to primary key..."); if (colInfo.IS_NULLABLE === 'YES') {
if (isNullable) {
await this.query(`UPDATE settings SET bot_id = '' WHERE bot_id IS NULL`); 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 ''`); await this.query(`ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`);
} }
if (this.botId) { if (this.botId) {
await this.query( await this.query(`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`);
`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) { if (pkRes.error) {
logger.error("[Settings] Failed to update primary key:", pkRes.error); logger.error('[Settings] Failed to update primary key:', pkRes.error);
return; return;
} }
this._hasBotIdColumn = true; 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. * Set the bot ID and claim any orphaned settings rows (bot_id = '').
* Called after login when the bot user ID becomes available. * @param {string} id - The bot user ID.
* @param {string} id * @returns {Promise<void>}
*/ */
async setBotId(id) { async setBotId(id) {
const changed = this.botId !== id; const changed = this.botId !== id;
@@ -186,7 +282,6 @@ export class RemoteSettingsManager extends SettingsManager {
if (changed) { if (changed) {
if (this._loadPromise) await this._loadPromise; if (this._loadPromise) await this._loadPromise;
await this._ensureBotIdColumn(); await this._ensureBotIdColumn();
if (this._hasBotIdColumn && this.botId) { if (this._hasBotIdColumn && this.botId) {
const claimRes = await this.query( const claimRes = await this.query(
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` `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}`); logger.settings(`[Settings] Claimed ${claimRes.results.affectedRows} legacy row(s) for bot ${this.botId}`);
} }
} }
this.guilds.clear(); this.guilds.clear();
this._loadPromise = this.load(); this._loadPromise = this.load();
await this._loadPromise; 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() { _botIdWhere() {
if (!this.botId || !this._hasBotIdColumn) return ""; if (!this.botId || !this._hasBotIdColumn) return '';
return ` AND bot_id = ${mysql.escape(String(this.botId))}`; 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() { _botIdInsert() {
if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" }; if (!this.botId || !this._hasBotIdColumn) return { col: '', val: '' };
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` }; 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)); const escapedId = mysql.escape(String(guildId));
return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`); return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`);
} }
query(q) { /**
return new Promise(res => { * Load all guild settings from the database. Retries with exponential backoff on failure.
this.db.query(q, (error, results, fields) => { res({ error, results, fields }); }); * Emits 'ready' when complete.
}); * @returns {Promise<void>}
} */
async load() { async load() {
const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`); const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`);
if (res.error) { if (res.error) {
this._loadAttempts++; this._loadAttempts++;
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000); 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); }); return new Promise((resolve) => { setTimeout(() => { this.load().then(resolve).catch(resolve); }, delay); });
} }
this._loadAttempts = 0; this._loadAttempts = 0;
res.results.forEach((r) => { res.results.forEach((r) => {
try { try {
const server = new ServerSettings(r.id, this); 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.deserialize(parsed);
server.checkDefaults(this.defaults); server.checkDefaults(this.defaults);
this.guilds.set(server.id, server); this.guilds.set(server.id, server);
} catch (e) { } 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) { async remoteUpdate(server, key) {
if (this._shuttingDown) return;
const val = server.data[key]; 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); return this.remoteSave(server);
} }
const escapedPath = mysql.escape(`$.${key}`); const escapedPath = mysql.escape(`$.${key}`);
const escapedVal = (typeof val === "boolean" || typeof val === "number") const jsonVal = JSON.stringify(val);
? mysql.escape(val) const escapedVal = mysql.escape(jsonVal);
: mysql.escape(String(val)); const escapedId = mysql.escape(server.id);
const escapedId = mysql.escape(server.id); const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, CAST(${escapedVal} AS JSON)) WHERE id=${escapedId}${this._botIdWhere()}`);
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);
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) { async remoteSave(server) {
if (this._shuttingDown) return;
const escapedData = mysql.escape(JSON.stringify(server.data)); const escapedData = mysql.escape(JSON.stringify(server.data));
const escapedId = mysql.escape(server.id); const escapedId = mysql.escape(server.id);
const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}`); 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) { loadDefaultsSync(filePath) {
try { try {
const d = fs.readFileSync(filePath, "utf8"); const d = fs.readFileSync(filePath, 'utf8');
const parsed = JSON.parse(d); const parsed = JSON.parse(d);
this.descriptions = parsed.descriptions; this.descriptions = parsed.descriptions ?? {};
this.defaults = parsed.values; this.defaults = parsed.values ?? {};
if (parsed.internal) this.markInternal(...parsed.internal);
} catch (e) { } 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.descriptions = {};
this.defaults = {}; this.defaults = {};
} }
} }
/**
* Save all guild settings to the database in parallel.
* @returns {Promise<void>}
*/
async saveAsync() { async saveAsync() {
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v))); 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) { async create(id, server) {
const escapedId = mysql.escape(id); if (this._shuttingDown) return;
const escapedId = mysql.escape(id);
const escapedData = mysql.escape(JSON.stringify(server.data)); const escapedData = mysql.escape(JSON.stringify(server.data));
const bi = this._botIdInsert(); const bi = this._botIdInsert();
const r = await this.query( const r = await this.query(
`INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})` `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) { 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); const s = this.guilds.get(server.id);
s.data[key] = server.data[key]; s.data[key] = server.data[key];
const existing = this._debounceTimers.get(server.id); const existing = this._debounceTimers.get(server.id);
if (existing) clearTimeout(existing); if (existing) clearTimeout(existing);
this._debounceTimers.set(server.id, setTimeout(() => { this._debounceTimers.set(server.id, setTimeout(() => {
this._debounceTimers.delete(server.id); this._debounceTimers.delete(server.id);
this.remoteSave(s); const target = this.guilds.get(server.id);
if (target) this.remoteUpdate(target, key);
}, 80)); }, 80));
} }
/**
* Check whether a setting key exists in defaults.
* @param {string} key - The setting key.
* @returns {boolean}
*/
isOption(key) { return key in this.defaults; } 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); } 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) { getServer(id) {
if (!this.guilds.has(id)) { if (!this.guilds.has(id)) return new ServerSettings(id, this);
return new ServerSettings(id, this);
}
return this.guilds.get(id); 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) { removeServer(id) {
const timer = this._debounceTimers.get(id); const timer = this._debounceTimers.get(id);
if (timer) { if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); }
clearTimeout(timer);
this._debounceTimers.delete(id);
}
this.guilds.delete(id); this.guilds.delete(id);
} }
} }
+25 -11
View File
@@ -1,29 +1,28 @@
/** /** @module src/TrackOptionsManager @description Per-user track options (start/end timestamps) stored in MySQL. Provides caching, matching, and CRUD for track segments. */
* @file TrackOptionsManager.mjs — TrackOptionsManager — SQLite-backed per-track options storage for auto-seek and end-time timers
* @module src.TrackOptionsManager
*/
import mysql from "mysql2"; import mysql from "mysql2";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
const DEFAULT_ALIAS = "default"; const DEFAULT_ALIAS = "default";
const MAX_ALIAS_LEN = 32; const MAX_ALIAS_LEN = 32;
/** /** @class TrackOptionsManager @description Manages per-user track options (start/end timestamps, aliases) stored in MySQL. Provides caching, best-match lookup, and CRUD operations. */
* TrackOptionsManager class.
*/
export class TrackOptionsManager { export class TrackOptionsManager {
/** @type {import('mysql2').Pool} */
db = null; db = null;
/** @type {string|null} */
botId = null; botId = null;
/** @private */
_hasTable = false; _hasTable = false;
/** @private */
_ready = false; _ready = false;
/** @private */
_readyPromise = null; _readyPromise = null;
/** @private @type {Map<string, object>} */
_cache = new Map(); _cache = new Map();
/** @private @type {number} */
_cacheMaxSize = 2000; _cacheMaxSize = 2000;
/** /** @param {object} mysqlConfig - MySQL connection config. */
* @param {Object} mysqlConfig MySQL connection config passed to mysql2's createPool
*/
constructor(mysqlConfig) { constructor(mysqlConfig) {
this.db = mysql.createPool({ connectionLimit: 10, ...mysqlConfig }); this.db = mysql.createPool({ connectionLimit: 10, ...mysqlConfig });
this.db.on("error", (err) => { this.db.on("error", (err) => {
@@ -32,10 +31,12 @@ export class TrackOptionsManager {
this._readyPromise = this._ensureTable(); this._readyPromise = this._ensureTable();
} }
/** @async Wait for the table to be ready. @returns {Promise<void>} */
async ready() { async ready() {
await this._readyPromise; await this._readyPromise;
} }
/** @private @async Ensure the track_options table exists with proper schema. */
async _ensureTable() { async _ensureTable() {
try { try {
await this._query( 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() { async _migrateOldTable() {
try { try {
const cols = await this._query(`SHOW COLUMNS FROM track_options LIKE 'alias'`); 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) { async setBotId(id) {
this.botId = id; this.botId = id;
} }
/** @private Execute a raw SQL query. @param {string} q @returns {Promise<Array>} */
_query(q) { _query(q) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.db.query(q, (error, results) => { this.db.query(q, (error, results) => {
@@ -88,22 +92,26 @@ export class TrackOptionsManager {
}); });
} }
/** @private @returns {string} SQL WHERE clause fragment for bot_id. */
_botIdWhere() { _botIdWhere() {
if (!this.botId) return ""; if (!this.botId) return "";
return ` AND bot_id = ${mysql.escape(String(this.botId))}`; 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() { _botIdInsert() {
if (!this.botId) return { col: "", val: "" }; if (!this.botId) return { col: "", val: "" };
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` }; 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) { static sanitizeAlias(raw) {
if (!raw || typeof raw !== "string") return DEFAULT_ALIAS; if (!raw || typeof raw !== "string") return DEFAULT_ALIAS;
const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, "").toLowerCase().slice(0, MAX_ALIAS_LEN); const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, "").toLowerCase().slice(0, MAX_ALIAS_LEN);
return cleaned || DEFAULT_ALIAS; 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) { static makeTrackIdentifier(track) {
if (!track) return null; if (!track) return null;
if (track.url) { if (track.url) {
@@ -122,6 +130,7 @@ export class TrackOptionsManager {
return null; 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) { async set(userId, track, startMs, endMs, alias = DEFAULT_ALIAS) {
await this.ready(); await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track); 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) { async get(userId, track, alias = DEFAULT_ALIAS) {
await this.ready(); await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track); 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) { async getAllForTrack(userId, track) {
await this.ready(); await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track); 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) { async remove(userId, track, alias = null) {
await this.ready(); await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track); 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) { async list(userId, limit = 25) {
await this.ready(); await this.ready();
try { 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) { async getBestMatchForChannel(userIds, track, alias = DEFAULT_ALIAS) {
await this.ready(); await this.ready();
const identifier = TrackOptionsManager.makeTrackIdentifier(track); const identifier = TrackOptionsManager.makeTrackIdentifier(track);
+72 -92
View File
@@ -1,40 +1,24 @@
/** /** @module src/Utils @description General-purpose utility functions for formatting, validation, string manipulation, and ID cleaning. */
* @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.
*/
import { escapeMarkdown as _escapeMarkdown, truncate as _truncate } from "@fluxerjs/util"; import { escapeMarkdown as _escapeMarkdown, truncate as _truncate } from "@fluxerjs/util";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
/** /**
* Strip non-digit characters from a value, returning a clean ID string. * Strip all non-digit characters from a value to extract a Snowflake/numeric ID.
* Replaces the inline `String(x).replace(/\D/g, "")` pattern used 97+ times. * @param {*} value - The value to clean (string, number, or null/undefined).
* @param {string|number} value * @returns {string} The numeric portion of the value, or empty string if none.
* @returns {string}
*/ */
export function cleanId(value) { export function cleanId(value) {
return String(value ?? "").replace(/\D/g, ""); return String(value ?? "").replace(/\D/g, "");
} }
/** /** @class Utils @description Collection of static utility methods for formatting, parsing, and string manipulation. */
* @class Utils
* @description Static utility methods for time formatting, array manipulation,
* string processing, and validation used across the music bot.
*/
export class Utils { export class Utils {
/** /**
* Format milliseconds to human-readable time string (H:MM:SS or M:SS) * Format a duration in milliseconds to a human-readable string (e.g. "1:23:45").
* @param {number} milliseconds - Duration in milliseconds * @param {number} milliseconds - Duration in milliseconds.
* @returns {string} Formatted time string * @returns {string} Formatted duration string.
*/ */
static prettifyMS(milliseconds) { static prettifyMS(milliseconds) {
if (!milliseconds || milliseconds < 0 || !isFinite(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. * Parse a duration string (e.g. "1:30", "1:30:00", "90") into milliseconds.
* @param {string} str - Duration string * @param {string} str - Duration string in mm:ss, hh:mm:ss, or plain seconds.
* @returns {number} Milliseconds, 0 if invalid * @returns {number} Duration in milliseconds, or 0 if unparseable.
*/ */
static parseDuration(str) { static parseDuration(str) {
if (!str || typeof str !== "string") return 0; if (!str || typeof str !== "string") return 0;
@@ -78,9 +62,9 @@ export class Utils {
} }
/** /**
* Format seconds to MM:SS (for NodeLink duration compatibility) * Format seconds into a human-readable duration string.
* @param {number} seconds - Duration in seconds * @param {number} seconds - Duration in seconds.
* @returns {string} Formatted time * @returns {string} Formatted duration string.
*/ */
static formatSeconds(seconds) { static formatSeconds(seconds) {
if (!seconds || seconds < 0 || !isFinite(seconds)) return "0:00"; if (!seconds || seconds < 0 || !isFinite(seconds)) return "0:00";
@@ -88,10 +72,9 @@ export class Utils {
} }
/** /**
* Shuffles array in-place using Fisher-Yates algorithm * Fisher-Yates in-place shuffle of an array.
* @template T * @param {Array} array - The array to shuffle (mutated in place).
* @param {T[]} array - Array to shuffle * @returns {Array} The same array, shuffled.
* @returns {T[]} Same array reference (shuffled)
*/ */
static shuffleArr(array) { static shuffleArr(array) {
if (!Array.isArray(array) || array.length < 2) return array; if (!Array.isArray(array) || array.length < 2) return array;
@@ -104,11 +87,11 @@ export class Utils {
} }
/** /**
* Truncate text with ellipsis * Truncate a string to a maximum length, appending a suffix if truncated.
* @param {string} str - String to truncate * @param {string} str - The string to truncate.
* @param {number} [maxLen=100] - Maximum length * @param {number} [maxLen=100] - Maximum character length.
* @param {string} [suffix="..."] - Suffix to add * @param {string} [suffix="..."] - Suffix to append when truncated.
* @returns {string} Truncated string * @returns {string} Truncated string.
*/ */
static truncate(str, maxLen = 100, suffix = "...") { static truncate(str, maxLen = 100, suffix = "...") {
if (!str || typeof str !== "string") return ""; if (!str || typeof str !== "string") return "";
@@ -118,10 +101,9 @@ export class Utils {
} }
/** /**
* Clean song title by removing common suffixes/prefixes for better matching * Clean a track title by removing common noise patterns (feat, remix, lyrics, etc.).
* Used for lyrics search and display normalization * @param {string} title - The raw track title.
* @param {string} title - Raw title * @returns {string} Cleaned title.
* @returns {string} Cleaned title
*/ */
static cleanTitle(title) { static cleanTitle(title) {
if (!title || typeof title !== "string") return "Unknown"; if (!title || typeof title !== "string") return "Unknown";
@@ -156,10 +138,9 @@ export class Utils {
} }
/** /**
* Escape markdown formatting characters. * Escape Discord markdown special characters in text.
* Delegates to @fluxerjs/util escapeMarkdown. * @param {string} text - The text to escape.
* @param {string} text - Raw text * @returns {string} Escaped text, or empty string if falsy.
* @returns {string} Escaped text
*/ */
static escapeMarkdown(text) { static escapeMarkdown(text) {
if (!text || typeof text !== "string") return ""; if (!text || typeof text !== "string") return "";
@@ -167,9 +148,9 @@ export class Utils {
} }
/** /**
* Format number with commas (e.g., 1,000,000) * Format a number with locale-aware thousand separators.
* @param {number} num - Number to format * @param {number} num - The number to format.
* @returns {string} Formatted number * @returns {string} Formatted number string.
*/ */
static formatNumber(num) { static formatNumber(num) {
if (num === null || num === undefined || isNaN(num)) return "0"; if (num === null || num === undefined || isNaN(num)) return "0";
@@ -177,9 +158,9 @@ export class Utils {
} }
/** /**
* Generate random unique ID * Generate a unique ID string based on timestamp and random characters.
* @param {number} [length=16] - Desired length of ID (8-32 recommended) * @param {number} [length=16] - Target length of the ID (clamped 8–32).
* @returns {string} Random ID * @returns {string} A unique alphanumeric ID.
*/ */
static uid(length = 16) { static uid(length = 16) {
const targetLen = Math.max(8, Math.min(length, 32)); const targetLen = Math.max(8, Math.min(length, 32));
@@ -195,9 +176,9 @@ export class Utils {
} }
/** /**
* Check if a value represents a finite number * Check whether a value is a valid finite number or numeric string.
* @param {string|number} str * @param {*} str - Value to check.
* @returns {boolean} * @returns {boolean} True if the value is a valid number.
*/ */
static isNumber(str) { static isNumber(str) {
if (str === null || str === undefined || str === "") return false; if (str === null || str === undefined || str === "") return false;
@@ -207,10 +188,9 @@ export class Utils {
} }
/** /**
* Check if value is a valid URL * Check whether a string is a valid URL.
* Used by worker.mjs YTUtils.isValidUrl * @param {string} str - String to check.
* @param {string} str - String to check * @returns {boolean} True if the string is a valid URL.
* @returns {boolean} True if valid URL
*/ */
static isValidUrl(str) { static isValidUrl(str) {
if (!str || typeof str !== "string") return false; if (!str || typeof str !== "string") return false;
@@ -223,11 +203,11 @@ export class Utils {
} }
/** /**
* Clamp number between min and max * Clamp a number between a minimum and maximum value.
* @param {number} num - Number to clamp * @param {number} num - The number to clamp.
* @param {number} min - Minimum value * @param {number} min - Minimum value.
* @param {number} max - Maximum value * @param {number} max - Maximum value.
* @returns {number} Clamped value * @returns {number} Clamped value.
*/ */
static clamp(num, min, max) { static clamp(num, min, max) {
if (isNaN(num)) return min; if (isNaN(num)) return min;
@@ -235,8 +215,8 @@ export class Utils {
} }
/** /**
* Sleep/delay promise * Return a promise that resolves after a specified delay.
* @param {number} ms - Milliseconds to sleep * @param {number} ms - Delay in milliseconds.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
static sleep(ms) { 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 * @template T
* @param {Promise<T>} promise - Promise to wrap * @param {Promise<T>} promise - The promise to wrap.
* @param {number} ms - Timeout in milliseconds * @param {number} ms - Timeout in milliseconds.
* @param {string} [message="Operation timed out"] - Error message * @param {string} [message="Operation timed out"] - Rejection message.
* @returns {Promise<T>} * @returns {Promise<T>} The original promise result, or rejection on timeout.
*/ */
static timeout(promise, ms, message = "Operation timed out") { static timeout(promise, ms, message = "Operation timed out") {
let timerId; let timerId;
@@ -260,14 +240,14 @@ export class Utils {
} }
/** /**
* Create progress bar string * Generate a text-based progress bar.
* @param {number} current - Current position in ms or 0-1 ratio * @param {number} current - Current progress value or ratio.
* @param {number} [total] - Total duration in ms (if omitted, current is treated as 0-1 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 {number} [length=15] - Bar length in characters.
* @param {string} [filledChar="━"] - Filled character * @param {string} [filledChar="━"] - Character for the filled portion.
* @param {string} [emptyChar="─"] - Empty character * @param {string} [emptyChar="─"] - Character for the empty portion.
* @param {string} [indicator="⬤"] - Position indicator * @param {string} [indicator="⬤"] - Character for the current position indicator.
* @returns {string} Progress bar string * @returns {string} The progress bar string.
*/ */
static progressBar( static progressBar(
current, current,
@@ -301,10 +281,10 @@ export class Utils {
} }
/** /**
* Format track info for display * Format a track object into a display string with title, artist, and optional duration.
* @param {object} track - Track object * @param {object} track - Track object with title, author, and optional duration.
* @param {boolean} [includeDuration=true] - Include duration * @param {boolean} [includeDuration=true] - Whether to include the duration.
* @returns {string} Formatted string * @returns {string} Formatted track info string.
*/ */
static formatTrackInfo(track, includeDuration = true) { static formatTrackInfo(track, includeDuration = true) {
if (!track) return "Unknown Track"; if (!track) return "Unknown Track";
@@ -325,9 +305,9 @@ export class Utils {
} }
/** /**
* Parse YouTube-like ISO duration (PT4M13S) to milliseconds * Parse an ISO 8601 duration string (e.g. "PT1H30M45S") into milliseconds.
* @param {string} isoDuration - ISO 8601 duration * @param {string} isoDuration - The ISO duration string.
* @returns {number} Milliseconds * @returns {number} Duration in milliseconds, or 0 if unparseable.
*/ */
static parseISODuration(isoDuration) { static parseISODuration(isoDuration) {
if (!isoDuration || typeof isoDuration !== "string") return 0; 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. * Normalize text by stripping non-alphanumeric characters, lowercasing, and trimming.
* Replaces the duplicated normalizeMatchText / normalizeTrackText functions. * Optionally cleans the title first using cleanTitle.
* @param {string} value - Raw text to normalize * @param {string} value - The text to normalize.
* @param {boolean} [cleanFirst=false] - Run cleanTitle() first (for worker.mjs title matching) * @param {boolean} [cleanFirst=false] - Whether to run cleanTitle before normalizing.
* @returns {string} Normalized text * @returns {string} Normalized lowercase text.
*/ */
static normalizeText(value, cleanFirst = false) { static normalizeText(value, cleanFirst = false) {
let text = String(value ?? ""); let text = String(value ?? "");
+34 -42
View File
@@ -1,52 +1,45 @@
/** /** @module constants/API */
* @file API.mjs — API constants — FluxerList API endpoints, authentication headers, pagination defaults, and cache TTL values
* @module src.constants.API
*/
/** /**
* API.mjs — Single source of truth for all external API constants. * FluxerList API configuration.
* * @namespace FLUXERLIST
* 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.
*/ */
export const 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", 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", 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: { ENDPOINTS: {
/** GET /api/v1/servers/:id/voters — voters for a server */
SERVER_VOTERS: "/servers/:id/voters", SERVER_VOTERS: "/servers/:id/voters",
/** GET /api/v1/bots/:id/voters — voters for a bot */
BOT_VOTERS: "/bots/:id/voters", 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"], RESOURCE_TYPES: ["server", "bot"],
/** Thumbnail image for vote embeds (FluxerList branding) */ /** Thumbnail API base URL. @type {string} */
THUMBNAIL: "https://fluxerlist.com/api/v1", THUMBNAIL: "https://fluxerlist.com/api/v1",
}; };
/**
* FluxerList authentication helpers.
* @namespace FLUXERLIST_AUTH
*/
export const FLUXERLIST_AUTH = { export const FLUXERLIST_AUTH = {
/** Header name for API key authentication */ /** HTTP header name for auth. @type {string} */
HEADER: "Authorization", HEADER: "Authorization",
/** Prefix prepended to all FluxerList API keys */ /** Required API key prefix. @type {string} */
KEY_PREFIX: "fl_", KEY_PREFIX: "fl_",
/** /**
* Build the Authorization header value. * Format an API key as a Bearer token, prepending the prefix if needed.
* @param {string} apiKey - The raw API key (with or without the fl_ prefix) * @param {string} apiKey - Raw or prefixed API key.
* @returns {string} Header value in "Bearer fl_xxx" format * @returns {string} `Bearer fl_...` string.
*/ */
bearer(apiKey) { bearer(apiKey) {
const key = apiKey.startsWith(FLUXERLIST_AUTH.KEY_PREFIX) 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 = { export const FLUXERLIST_LIMITS = {
/** Default page number when none is specified */ /** Default page number. @type {number} */
DEFAULT_PAGE: 1, DEFAULT_PAGE: 1,
/** Default number of results per page */ /** Default items-per-page. @type {number} */
DEFAULT_LIMIT: 50, DEFAULT_LIMIT: 50,
/** Maximum number of results per page (API enforced) */ /** Maximum allowed items-per-page. @type {number} */
MAX_LIMIT: 100, 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, CACHE_TTL_MS: 5 * 60 * 1000,
}; };
/** /**
* Build a full FluxerList API URL by replacing :id in the endpoint path. * 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} endpoint - One of FLUXERLIST.ENDPOINTS values (e.g. "/servers/:id/voters") * @param {string} resourceId - Value to substitute for `:id`.
* @param {string} resourceId - The server or bot ID or slug to substitute for :id * @param {{ page?: number, limit?: number }} [queryParams={}]
* @param {object} [queryParams] - Optional query parameters * @returns {string} Fully qualified URL.
* @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()
*/ */
export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) { export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) {
const path = endpoint.replace(":id", encodeURIComponent(resourceId)); 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. * Build a FluxerList vote link for a server or bot.
* Both vote and profile links share the same URL pattern. * @param {"server"|"bot"} type - Resource type.
* * @param {string} resourceId - The server/bot ID.
* @param {"server"|"bot"} type - Resource type * @returns {string} Absolute URL to the vote page.
* @param {string} resourceId - The server or bot ID or slug
* @returns {string} URL to the resource page on FluxerList
*/ */
export function buildVoteLink(type, resourceId) { export function buildVoteLink(type, resourceId) {
const path = type === "server" ? "servers" : "bots"; 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);
}
}
+26 -59
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 * Simplified 24/7 helpers — single mode (on/off), no per-channel modes.
* @module src.constants.Helpers247 * 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. * Check if a channel has 24/7 enabled.
* * @param {object} set - ServerSettings instance
* The per-channel mode map (`stay_247_modes`) stores each channel's 24/7 mode * @param {string} channelId
* independently so a guild can have channel A on "on" and channel B on "auto". * @returns {"on"|"off"}
*
* 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"}
*/ */
export function get247ChannelMode(set, channelId) { export function get247ChannelMode(set, channelId) {
if (!set?.get) return "off"; if (!set?.get) return "off";
const modes = set.get("stay_247_modes"); const raw = set.get("stay_247");
if (modes && typeof modes === "object" && !Array.isArray(modes)) { if (!raw || raw === "none") return "off";
const perChannel = modes[channelId]; const channels = Array.isArray(raw)
if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel; ? raw.map(id => String(id).trim()).filter(Boolean)
} : [String(raw).trim()];
const guildMode = set.get("stay_247_mode") ?? "off"; return channels.includes(channelId) ? "on" : "off";
return guildMode;
} }
/** /**
* Set the 24/7 mode for a specific channel. * No-op: per-channel modes removed. Kept for backward compatibility.
* * Original GatewayHandler.mjs and index.mjs still import this.
* @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
*/ */
export function remove247ChannelMode(set, channelId, currentChannels) { export function remove247ChannelMode(set, channelId, currentChannels) {
let modes = set.get("stay_247_modes"); // No-op: modes no longer exist, stay_247 array is managed directly.
if (!modes || typeof modes !== "object" || Array.isArray(modes)) return; }
delete modes[channelId];
set.set("stay_247_modes", modes); /**
if (!currentChannels || currentChannels.size === 0) { * No-op: per-channel modes removed. Kept for backward compatibility.
set.set("stay_247_mode", "off"); */
} else { export function set247ChannelMode(set, channelId, mode) {
const firstChannel = [...currentChannels][0]; // No-op: modes no longer exist.
set.set("stay_247_mode", modes[firstChannel] ?? "auto");
}
} }
+42 -51
View File
@@ -1,53 +1,46 @@
/** /** @module constants/Locale */
* @file Locale.mjs — Locale — i18n system loading JSON locale files with per-guild language settings and template variable interpolation
* @module src.constants.Locale
*/
import { readFileSync, readdirSync, existsSync } from "fs"; import { readFileSync, readdirSync, existsSync } from "fs";
import path from "path"; import path from "path";
import { fileURLToPath } from "url"; import { fileURLToPath } from "url";
import { logger } from "./Logger.mjs"; import { logger } from "./Logger.mjs";
/** @private */
const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __dirname = path.dirname(fileURLToPath(import.meta.url));
/** @private */
const LOCALES_DIR = path.resolve(__dirname, "../../storage/locales/bot"); const LOCALES_DIR = path.resolve(__dirname, "../../storage/locales/bot");
/** /**
* Lightweight i18n locale loader. * Locale/i18n manager that loads JSON locale files from disk and provides
* * dot-notation key lookups with `{{placeholder}}` and `$prefix` substitution.
* Loads all JSON files from storage/locales/bot/ at startup and provides * @class
* 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 })
*/ */
export class Locale { export class Locale {
constructor() { /**
/** @type {Map<string, Object>} locale code → parsed JSON */ * @param {string} [defaultPrefix="%"] - Fallback prefix used when no prefix
this.locales = new Map(); * resolver is registered and the settings manager yields no prefix.
/** @type {Map<string, Object>} guildId → locale JSON (resolved & cached) */ */
this._resolved = new Map(); constructor(defaultPrefix = "%") {
/** Default fallback locale */ /** @private */ this.locales = new Map();
this.defaultLocale = "en"; /** @private */ this._resolved = new Map();
/** settingsMgr reference — set after construction via bind() */ /** @type {string} */ this.defaultLocale = "en";
this.settingsMgr = null; /** @private */ this.settingsMgr = null;
/** getPrefix callback — set by CommandHandler so prefix logic lives in one place */ /** @private */ this._getPrefixFn = null;
this._getPrefixFn = null; /** @private */ this._defaultPrefix = defaultPrefix;
/** Maximum guild locale cache size */ /** @private */ this._maxResolvedCache = 5000;
this._maxResolvedCache = 5000;
} }
/** /**
* Bind a settings manager so translate() can look up per-guild locale settings. * Bind a settings manager so the locale resolver can look up per-guild locale preferences.
* @param {object} settingsMgr - RemoteSettingsManager instance * @param {object} settingsMgr - Settings manager exposing `guilds.get(guildId)`.
*/ */
bind(settingsMgr) { bind(settingsMgr) {
this.settingsMgr = settingsMgr; this.settingsMgr = settingsMgr;
} }
/** /**
* Load all locale JSON files from the locales directory. * Load all `.json` locale files from the locales directory.
* Call once at startup after config is available. * Clears any previously loaded data and the resolved-cache.
*/ */
load() { load() {
this.locales.clear(); this.locales.clear();
@@ -81,8 +74,7 @@ export class Locale {
} }
/** /**
* Return the set of available locale codes. * Return the set of loaded locale codes.
* Useful for validation (e.g. the settings command).
* @returns {Set<string>} * @returns {Set<string>}
*/ */
availableLocales() { availableLocales() {
@@ -90,12 +82,11 @@ export class Locale {
} }
/** /**
* Resolve the locale data for a guild. * Resolve the locale data object for a guild, using per-guild settings or falling
* Checks the per-guild "locale" setting from the DB, falls back to English. * back to the default locale. Results are cached with an LRU-style cap.
* Results are cached per guildId. * @private
*
* @param {string} guildId * @param {string} guildId
* @returns {Object} * @returns {object} The locale data object.
*/ */
_getLocaleData(guildId) { _getLocaleData(guildId) {
if (!guildId) return this.locales.get(this.defaultLocale) ?? {}; 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). * Invalidate the resolved-cache for a specific guild or all guilds.
* @param {string} [guildId] - Specific guild to invalidate, or omit for all. * @param {string} [guildId] - Omit to clear the entire cache.
*/ */
invalidateCache(guildId) { invalidateCache(guildId) {
if (guildId) { if (guildId) {
@@ -138,17 +129,16 @@ export class Locale {
} }
/** /**
* Set the prefix resolver callback. Called once by CommandHandler at startup * Register a custom prefix resolver function.
* so that all prefix resolution goes through CommandHandler.getPrefix(). * @param {function(string): string} fn - Receives `guildId`, returns the prefix string.
* @param {(guildId: string) => string} fn
*/ */
setPrefixResolver(fn) { setPrefixResolver(fn) {
this._getPrefixFn = fn; this._getPrefixFn = fn;
} }
/** /**
* Get the per-guild prefix. Delegates to CommandHandler.getPrefix() when * Resolve the command prefix for a guild.
* available, otherwise falls back to a direct settings lookup. * @private
* @param {string} guildId * @param {string} guildId
* @returns {string} * @returns {string}
*/ */
@@ -165,9 +155,10 @@ export class Locale {
} }
/** /**
* Look up a dotted key in a nested object. * Resolve a dot-notation key against a nested object.
* @param {Object} obj * @private
* @param {string} key e.g. "responses.play.noResults" * @param {object} obj
* @param {string} key - e.g. "commands.play.description"
* @returns {*} * @returns {*}
*/ */
_resolve(obj, key) { _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} guildId
* @param {string} key Dotted key, e.g. "responses.play.noResults" * @param {string} key - Dot-notation locale key.
* @param {Object} [replacements={}] e.g. { count: 5, channel: "#general" } * @param {Object<string, *>} [replacements={}] - Placeholder values to substitute.
* @returns {string} Translated string, or the key itself if not found * @returns {string} The translated (or fallback) string.
*/ */
translate(guildId, key, replacements = {}) { translate(guildId, key, replacements = {}) {
const localeData = this._getLocaleData(guildId); const localeData = this._getLocaleData(guildId);
+94 -36
View File
@@ -1,87 +1,145 @@
/** /** @module constants/Logger */
* @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)
*/
/** @private */
let _config = null; let _config = null;
/** /**
* Call once at startup with the loaded config object. * Initialize the logger with a configuration object.
* @param {object} config * @param {object} [config] - Application configuration object.
* @param {object} [config.logging] - Logging-specific configuration.
*/ */
export function initLogger(config) { export function initLogger(config) {
_config = config?.logging ?? {}; _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) { function isEnabled(category) {
if (!_config) return true; if (!_config) return true;
if (_config.enabled === false) return false; if (_config.enabled === false) return false;
return _config[category] !== 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() { function ts() {
return new Date().toISOString().replace("T", " ").slice(0, 19); return new Date().toISOString().replace("T", " ").slice(0, 19);
} }
/** /**
* Shared cooldown state for WebSocket transport error logging. * Cooldown state for WebSocket error logging to avoid spam.
* Prevents the same WS close event from being logged by multiple * @type {{ lastLogged: number, COOLDOWN_MS: number }}
* listeners (shard handler, GatewayHandler, MoonlinkManager).
* All three share this timestamp so only the first logs.
*/ */
export const _wsErrorCooldown = { lastLogged: 0, COOLDOWN_MS: 15_000 }; export const _wsErrorCooldown = { lastLogged: 0, COOLDOWN_MS: 15_000 };
/**
* Structured logger exposing category-gated log methods.
* @namespace logger
*/
export const 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) { error(tag, ...args) {
console.error(`[${ts()}] ${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) { warn(tag, ...args) {
if (!_config) { console.warn(`[${ts()}] ${tag}`, ...args); return; } if (!_config) { console.warn(`[${ts()}] ${tag}`, ...args); return; }
if (_config.enabled === false && _config.warn !== true) return; if (_config.enabled === false && _config.warn !== true) return;
console.warn(`[${ts()}] ${tag}`, ...args); 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) { info(tag, ...args) {
if (_config?.enabled === false) return; if (_config?.enabled === false) return;
console.log(`[${ts()}] ${tag}`, ...args); console.log(`[${ts()}] ${tag}`, ...args);
}, },
/**
* Category-gated player log.
* @param {...*} args
*/
player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...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); }, 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); }, 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); }, 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); }, mediaplayer(...args) { if (isEnabled("mediaplayer")) console.log(`[${ts()}]`, ...args); },
/**
* Category-gated commands log.
* @param {...*} args
*/
commands(...args) { if (isEnabled("commands")) console.log(`[${ts()}]`, ...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); }, guild(...args) { if (isEnabled("guild")) console.log(`[${ts()}]`, ...args); },
/**
* Category-gated recovery log.
* @param {...*} args
*/
recovery(...args) { if (isEnabled("recovery")) console.log(`[${ts()}]`, ...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); }, 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); }, aloneCheck(...args) { if (isEnabled("aloneCheck")) console.log(`[${ts()}]`, ...args); },
/**
* Category-gated voice log.
* @param {...*} args
*/
voice(...args) { if (isEnabled("voice")) console.log(`[${ts()}]`, ...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); }, dashboard(...args) { if (isEnabled("dashboard")) console.log(`[${ts()}]`, ...args); },
/**
* Category-gated redis log.
* @param {...*} args
*/
redis(...args) { if (isEnabled("redis")) console.log(`[${ts()}]`, ...args); }, redis(...args) { if (isEnabled("redis")) console.log(`[${ts()}]`, ...args); },
}; };
+13 -21
View File
@@ -1,45 +1,37 @@
/** /** @module constants/UI */
* @file UI.mjs — UI constants — shared color values, emoji arrays, timeout durations, and volume limits used across commands and embeds
* @module src.constants.UI
*/
/** /** Hex color string for error embeds. @type {string} */
* 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". */
export const ERROR_COLOR = "#ff0000"; 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; export const WARN_COLOR = 0xFFAA00;
/** Success colour for diagnostic embeds. */ /** Numeric hex color for success embeds. @type {number} */
export const SUCCESS_COLOR = 0x00CC66; 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; 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; 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; 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 = [ export const NUMBER_EMOJIS = [
"1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣",
"6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟",
]; ];
/** Cancel emoji for selection menus. */ /** Emoji used to cancel a selection. @type {string} */
export const CANCEL_EMOJI = "❌"; export const CANCEL_EMOJI = "❌";
/** Navigation emojis for paginated embeds. */ /** Emoji for previous-page navigation. @type {string} */
export const PREV_EMOJI = "⬅️"; export const PREV_EMOJI = "⬅️";
/** Emoji for next-page navigation. @type {string} */
export const NEXT_EMOJI = "➡️"; export const NEXT_EMOJI = "➡️";
/** Maximum allowed volume percentage. */ /** Maximum allowed volume value. @type {number} */
export const MAX_VOLUME = 200; export const MAX_VOLUME = 200;
+82 -133
View File
@@ -1,78 +1,58 @@
/** /** @module constants/VoiceStateCache */
* @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)
*/
import { logger } from "./Logger.mjs"; import { logger } from "./Logger.mjs";
import { cleanId } from "../Utils.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 { export class VoiceStateCache {
/** /**
* @param {object} [opts] * @param {object} [opts]
* @param {number} [opts.maxUsers=50000] Max human entries before LRU eviction * @param {number} [opts.maxUsers=50000] - Max cached human user entries.
* @param {number} [opts.maxBots=10000] Max bot entries before LRU eviction * @param {number} [opts.maxBots=10000] - Max cached bot user entries.
*/ */
constructor(opts = {}) { constructor(opts = {}) {
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
this.userLocations = new Map(); this.userLocations = new Map();
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
this.channelMembers = new Map(); this.channelMembers = new Map();
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
this.botLocations = new Map(); this.botLocations = new Map();
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
this.botChannelMembers = new Map(); this.botChannelMembers = new Map();
this._maxUsers = opts.maxUsers ?? 50_000; this._maxUsers = opts.maxUsers ?? 50_000;
this._maxBots = opts.maxBots ?? 10_000; this._maxBots = opts.maxBots ?? 10_000;
/** @type {string[]} MRU-first list of user location keys */
this._lruUserKeys = []; this._lruUserKeys = [];
/** @type {string[]} MRU-first list of bot location keys */
this._lruBotKeys = []; 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) { static userKey(guildId, userId) {
return `${cleanId(guildId)}:${cleanId(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) { static channelKey(guildId, channelId) {
return `${cleanId(guildId)}:${cleanId(channelId)}`; return `${cleanId(guildId)}:${cleanId(channelId)}`;
} }
/** /**
* Update voice state for a user. * 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.
* @param {object} params * Automatically evicts LRU entries when capacity is exceeded.
* @param {string} params.guildId * @param {{ guildId: string, userId: string, channelId: string|null, isBot?: boolean }} opts
* @param {string} params.userId
* @param {string|null} params.channelId null = user left voice
* @param {boolean} [params.isBot=false]
*/ */
updateUser({ guildId, userId, channelId, isBot = false }) { updateUser({ guildId, userId, channelId, isBot = false }) {
const cleanGuild = cleanId(guildId); const cleanGuild = cleanId(guildId);
@@ -139,9 +119,7 @@ export class VoiceStateCache {
} }
/** /**
* Check if there are any human users in a specific channel. * Check whether any human users are cached in the given channel.
* O(1) via channelMembers index.
*
* @param {string} guildId * @param {string} guildId
* @param {string} channelId * @param {string} channelId
* @returns {boolean} * @returns {boolean}
@@ -153,9 +131,7 @@ export class VoiceStateCache {
} }
/** /**
* Get the number of human users in a specific channel. * Get the count of human users cached in the given channel.
* O(1) via channelMembers index.
*
* @param {string} guildId * @param {string} guildId
* @param {string} channelId * @param {string} channelId
* @returns {number} * @returns {number}
@@ -167,9 +143,7 @@ export class VoiceStateCache {
} }
/** /**
* Get all human userIds in a specific channel. * Get the array of human user IDs cached in the given channel.
* O(1) lookup + Set iteration.
*
* @param {string} guildId * @param {string} guildId
* @param {string} channelId * @param {string} channelId
* @returns {string[]} * @returns {string[]}
@@ -181,9 +155,7 @@ export class VoiceStateCache {
} }
/** /**
* Get the channelId a human user is currently in (within a specific guild). * Get the channel ID a human user is currently in, or `null`.
* O(1) via userLocations index.
*
* @param {string} guildId * @param {string} guildId
* @param {string} userId * @param {string} userId
* @returns {string|null} * @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} guildId
* @param {string} userId * @param {string} userId
* @returns {boolean} * @returns {boolean}
@@ -206,19 +177,17 @@ 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} guildId
* @param {string} userId * @param {string} userId
* @returns {{channelId: string, guildId: string, userId: string}|undefined} * @returns {{ channelId: string, guildId: string, userId: string }|undefined}
*/ */
getUserLocation(guildId, userId) { getUserLocation(guildId, userId) {
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId)); return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
} }
/** /**
* 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} guildId
* @param {string} userId * @param {string} userId
* @param {string} channelId * @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 * @param {string} guildId
*/ */
removeGuild(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} guildId
* @param {string} channelId * @param {string} channelId
*/ */
@@ -317,12 +284,10 @@ export class VoiceStateCache {
} }
/** /**
* Selectively remove entries for users whose IDs appear in a given set * Remove specific users from a guild's cache.
* (used during GuildCreate to purge stale entries being replaced).
*
* @param {string} guildId * @param {string} guildId
* @param {Set<string>} userIds User IDs whose entries should be purged * @param {string[]} userIds
* @param {boolean} [botsOnly=false] Only purge bot entries * @param {boolean} [botsOnly=false] - If `true`, only purge bot entries.
*/ */
purgeUsersInGuild(guildId, userIds, botsOnly = false) { purgeUsersInGuild(guildId, userIds, botsOnly = false) {
const cleanGuild = cleanId(guildId); const cleanGuild = cleanId(guildId);
@@ -353,21 +318,20 @@ export class VoiceStateCache {
} }
/** /**
* Get the "observedVoiceUsers" size (human count). * Number of cached human users.
* Backward-compat with `this.observedVoiceUsers.size` * @type {number}
*/ */
get observedVoiceUsersSize() { return this.userLocations.size; } get observedVoiceUsersSize() { return this.userLocations.size; }
/** /**
* Get the "observedVoiceBots" size. * Number of cached bot users.
* Backward-compat with `this.observedVoiceBots.size` * @type {number}
*/ */
get observedVoiceBotsSize() { return this.botLocations.size; } get observedVoiceBotsSize() { return this.botLocations.size; }
/** /**
* Iterate over all human user locations. * Iterate over all cached human user entries as `[userId, { channelId, guildId }]` pairs.
* Yields [compositeKey, {channelId, guildId, userId}] — same shape as Map entries. * @yields {[string, { channelId: string, guildId: string }]}
* Backward-compat with `for (const [uid, info] of this.observedVoiceUsers)`.
*/ */
*iterateHumanUsers() { *iterateHumanUsers() {
for (const [uKey, loc] of this.userLocations) { for (const [uKey, loc] of this.userLocations) {
@@ -376,9 +340,8 @@ export class VoiceStateCache {
} }
/** /**
* Iterate over all bot user locations. * Iterate over all cached bot user entries as `[compositeKey, { channelId, guildId }]` pairs.
* Yields [compositeKey, {channelId, guildId, userId}]. * @yields {[string, { channelId: string, guildId: string }]}
* Backward-compat with `for (const [uid, info] of this.observedVoiceBots)`.
*/ */
*iterateBotUsers() { *iterateBotUsers() {
for (const [uKey, loc] of this.botLocations) { for (const [uKey, loc] of this.botLocations) {
@@ -387,13 +350,10 @@ export class VoiceStateCache {
} }
/** /**
* Get a human user's location by userId and guildId. * Get the location record for a human user. If `guildId` is omitted, performs a linear scan.
* If guildId is provided, uses O(1) composite key.
* If guildId is null, falls back to O(n) scan (legacy compat).
*
* @param {string} userId * @param {string} userId
* @param {string|null} [guildId=null] * @param {string|null} [guildId]
* @returns {{channelId: string, guildId: string}|undefined} * @returns {{ channelId: string, guildId: string }|undefined}
*/ */
getHumanUser(userId, guildId = null) { getHumanUser(userId, guildId = null) {
if (guildId) { if (guildId) {
@@ -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 {string} userId
* @param {{channelId: string, guildId: string}} info * @param {{ guildId: string, channelId: string }} info
*/ */
setHumanUser(userId, info) { setHumanUser(userId, info) {
const guildId = info.guildId; const guildId = info.guildId;
@@ -421,10 +380,9 @@ export class VoiceStateCache {
} }
/** /**
* Set a bot user's location (backward-compat with observedVoiceBots.set). * Set a bot user's voice location via `updateUser`.
* * @param {string} compositeKey - `guildId:userId` composite key.
* @param {string} compositeKey "guildId:userId" composite key * @param {{ guildId: string, channelId: string }} info
* @param {{channelId: string, guildId: string}} info
*/ */
setBotUser(compositeKey, info) { setBotUser(compositeKey, info) {
const guildId = info.guildId; const guildId = info.guildId;
@@ -436,11 +394,9 @@ export class VoiceStateCache {
} }
/** /**
* Delete a human user by userId (scans all guilds if no guildId given). * Remove a human user from the cache. If `guildId` is omitted, scans all entries.
* Backward-compat with observedVoiceUsers.delete(userId).
*
* @param {string} userId * @param {string} userId
* @param {string|null} [guildId=null] * @param {string|null} [guildId]
*/ */
deleteHumanUser(userId, guildId = null) { deleteHumanUser(userId, guildId = null) {
if (guildId) { if (guildId) {
@@ -456,10 +412,8 @@ export class VoiceStateCache {
} }
/** /**
* Delete a bot user by composite key. * Remove a bot user from the cache by its composite key.
* Backward-compat with observedVoiceBots.delete(compositeKey). * @param {string} compositeKey - `guildId:userId` composite key.
*
* @param {string} compositeKey "guildId:userId"
*/ */
deleteBotUser(compositeKey) { deleteBotUser(compositeKey) {
const parts = compositeKey.split(":"); const parts = compositeKey.split(":");
@@ -471,11 +425,9 @@ export class VoiceStateCache {
} }
/** /**
* Check if a human user exists in the cache. * Check whether a human user exists in the cache. If `guildId` is omitted, scans all entries.
* Backward-compat with observedVoiceUsers.has(userId).
*
* @param {string} userId * @param {string} userId
* @param {string|null} [guildId=null] * @param {string|null} [guildId]
* @returns {boolean} * @returns {boolean}
*/ */
hasHumanUser(userId, guildId = null) { hasHumanUser(userId, guildId = null) {
@@ -490,10 +442,8 @@ export class VoiceStateCache {
} }
/** /**
* Check if a bot user exists in the cache. * Check whether a bot user exists in the cache by composite key.
* Backward-compat with observedVoiceBots.has(compositeKey). * @param {string} compositeKey - `guildId:userId` composite key.
*
* @param {string} compositeKey
* @returns {boolean} * @returns {boolean}
*/ */
hasBotUser(compositeKey) { hasBotUser(compositeKey) {
@@ -501,8 +451,8 @@ export class VoiceStateCache {
} }
/** /**
* Default iterator — iterates human users. * Implement the iterable protocol over human user entries.
* Yields [userId, {channelId, guildId}] — same shape as old observedVoiceUsers Map. * @yields {[string, { channelId: string, guildId: string }]}
*/ */
*[Symbol.iterator]() { *[Symbol.iterator]() {
for (const [uKey, loc] of this.userLocations) { 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; } get size() { return this.userLocations.size; }
/** /**
* Backward-compat with `observedVoiceUsers.has(userId)`. * Map-like `has` — checks if a human user is cached.
* If called with a single argument (userId), scans all guilds.
* If called with two arguments (userId, guildId), does O(1) lookup.
*
* @param {string} userId * @param {string} userId
* @param {string} [guildId] * @param {string} [guildId]
* @returns {boolean} * @returns {boolean}
@@ -536,13 +484,10 @@ export class VoiceStateCache {
} }
/** /**
* Backward-compat with `observedVoiceUsers.get(userId)`. * Map-like `get` — retrieve a human user's location.
* If called with a single argument (userId), returns first match across all guilds.
* If called with two arguments (userId, guildId), does O(1) lookup.
*
* @param {string} userId * @param {string} userId
* @param {string} [guildId] * @param {string} [guildId]
* @returns {{channelId: string, guildId: string}|undefined} * @returns {{ channelId: string, guildId: string }|undefined}
*/ */
get(userId, guildId) { get(userId, guildId) {
if (guildId !== undefined) { if (guildId !== 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 {string} userId
* @param {{channelId: string, guildId: string}} info * @param {{ guildId: string, channelId: string }} info
*/ */
set(userId, info) { set(userId, info) {
const guildId = info?.guildId; 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} userId
* @param {string} [guildId] * @param {string} [guildId]
*/ */
@@ -592,9 +535,8 @@ export class VoiceStateCache {
} }
/** /**
* Backward-compat with `observedVoiceUsers.forEach(fn)`. * Map-like `forEach` — iterate over human user entries.
* * @param {function(string, { channelId: string, guildId: string }, VoiceStateCache): void} fn
* @param {Function} fn callback(userId, info, cache)
*/ */
forEach(fn) { forEach(fn) {
for (const [userId, info] of this) { 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() { *entries() {
yield* this; yield* this;
} }
/** /**
* Backward-compat with `observedVoiceUsers.keys()`. * Map-like `keys` iterator.
* @yields {string}
*/ */
*keys() { *keys() {
for (const [userId] of this) { 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() { *values() {
for (const [, info] of this) { 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() { get stats() {
return { return {
humanUsers: this.userLocations.size, humanUsers: this.userLocations.size,
+18 -37
View File
@@ -1,26 +1,11 @@
/** /** @module constants/VoiceStateResolver */
* @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.
*/
import { logger } from "./Logger.mjs"; import { logger } from "./Logger.mjs";
/** /**
* Iterate over all voice states for a guild, yielding objects with * Iterate over a guild's voice states, normalising different data shapes.
* { userId, channelId, isBot } regardless of the underlying data structure. * Yields objects with `{ userId, channelId, isBot }` for each member in a voice channel.
* * @param {object} guild - Discord guild object with a `voice_states` property.
* @param {import("@fluxerjs/core").Guild} guild
* @yields {{ userId: string, channelId: string, isBot: boolean }} * @yields {{ userId: string, channelId: string, isBot: boolean }}
*/ */
export function* iterateVoiceStates(guild) { export function* iterateVoiceStates(guild) {
@@ -59,18 +44,16 @@ export function* iterateVoiceStates(guild) {
} }
/** /**
* Check whether a guild's voice channel contains any non-bot users. * Check whether any non-bot humans are currently in a voice channel.
* Uses three fallback strategies: VoiceStateCache, guild.voice_states, * Checks, in order: VoiceStateCache → ObservedVoiceUsers → guild voice_states → LiveKit participants.
* and LiveKit remote participants.
*
* @param {object} opts * @param {object} opts
* @param {string} opts.guildId - Clean guild ID * @param {string} opts.guildId
* @param {string} opts.channelId - Clean channel ID * @param {string} opts.channelId
* @param {object} [opts.client] - Fluxer client (for guild cache) * @param {object} [opts.client] - Discord client with `guilds`.
* @param {object} [opts.voiceCache] - VoiceStateCache instance * @param {VoiceStateCache} [opts.voiceCache]
* @param {Map} [opts.observedVoiceUsers] - Observed voice users map * @param {Map} [opts.observedVoiceUsers]
* @param {object} [opts.room] - LiveKit Room (for remote participants) * @param {object} [opts.room] - LiveKit room with `remoteParticipants`.
* @param {string} [opts.botId] - Bot user ID (to exclude from LiveKit check) * @param {string} [opts.botId]
* @returns {boolean} * @returns {boolean}
*/ */
export function hasHumansInChannel({ guildId, channelId, client, voiceCache, observedVoiceUsers, room, botId }) { 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. * Get the set of channel IDs that contain at least one human user.
* * @param {object} guild - Discord guild object.
* @param {import("@fluxerjs/core").Guild} guild * @returns {Set<string>}
* @returns {Set<string>} Set of channel IDs with human users
*/ */
export function getChannelsWithHumans(guild) { export function getChannelsWithHumans(guild) {
const channels = new Set(); const channels = new Set();
@@ -142,9 +124,8 @@ export function getChannelsWithHumans(guild) {
} }
/** /**
* Get all user IDs in a specific voice channel (including bots). * Get the list of user IDs present in a specific voice channel.
* * @param {object} guild - Discord guild object.
* @param {import("@fluxerjs/core").Guild} guild
* @param {string} channelId * @param {string} channelId
* @returns {string[]} * @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;
+35 -11
View File
@@ -1,24 +1,30 @@
/** /** @module constants/audio/Tuna */
* @file Tuna.mjs — Tuna — Voicemod Tuna API client for sound effect search and download
* @module src.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"; import pkg from "follow-redirects";
const { https } = pkg; const { https } = pkg;
/**
* Client for the Tuna (Voicemod) sound-effect API.
* @class
*/
class Tuna { class Tuna {
apiKey = null; /** @private */ apiKey = null;
/** /**
* @param {Object} auth Auth config * @param {{ key: string }} auth - Object containing the API key.
* @param {string} auth.key Voicemod Tuna API key
*/ */
constructor(auth) { constructor(auth) {
this.apiKey = auth.key; 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 = {}) { get(path, params = {}) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const qs = new URLSearchParams(params).toString(); const qs = new URLSearchParams(params).toString();
@@ -49,6 +55,16 @@ class Tuna {
req.end(); 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) { search(query, page = 1, size = 10) {
return this.get("/v1/sounds/search", { size, page, search: query }).then(results => { return this.get("/v1/sounds/search", { size, page, search: query }).then(results => {
results.items = results.items.map(s => { results.items = results.items.map(s => {
@@ -65,6 +81,14 @@ class Tuna {
return results; 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) { getSound(id) {
return this.get("/v1/sounds/" + id).then(sound => { return this.get("/v1/sounds/" + id).then(sound => {
const oggPath = sound.oggPath; 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 @@
/** /** @module constants/providers */
* @file providers.mjs — Music provider definitions — source names, emoji icons, choice lists, and inline provider parsing for search commands
* @module src.constants.providers
*/
/** /**
* providers.mjs — Single source of truth for all provider data. * 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
* PROVIDERS — full map: { prefix, label } — used by worker.mjs for search * prefix/label pair.
* PROVIDER_NAMES — derived label-only map — used by Player.mjs for display * @type {Object<string, { prefix: string, label: string }>}
* PROVIDER_CHOICES — ordered list of valid keys — used by command option builders
*
* Edit only here; worker.mjs and Player.mjs import from this file.
*/ */
export const PROVIDERS = { export const PROVIDERS = {
yt: { prefix: "ytsearch", label: "YouTube" }, yt: { prefix: "ytsearch", label: "YouTube" },
ytm: { prefix: "ytmsearch", label: "YouTube Music" }, ytm: { prefix: "ytmsearch", label: "YouTube Music" },
@@ -71,11 +64,18 @@ export const PROVIDERS = {
ftts: { prefix: "ftts", label: "Flowery TTS" }, 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( export const PROVIDER_NAMES = Object.fromEntries(
Object.entries(PROVIDERS).map(([k, v]) => [k, v.label]) Object.entries(PROVIDERS).map(([k, v]) => [k, v.label])
); );
/**
* Complete list of accepted provider keys for command choices.
* @type {string[]}
*/
export const PROVIDER_CHOICES = [ export const PROVIDER_CHOICES = [
"ytm", "yt", "scld", "sc", "ytm", "yt", "scld", "sc",
"sp", "spotify", "sp", "spotify",
@@ -105,8 +105,10 @@ export const PROVIDER_CHOICES = [
]; ];
/** /**
* Parse an inline provider prefix from a query string (e.g. "sp: song name"). * Parse an inline provider prefix from raw query text (e.g. `"yt: never gonna give you up"`).
* @param {string} raw * 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 }} * @returns {{ provider: string|null, query: string }}
*/ */
export function parseInlineProvider(raw) { 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 dashboard/Dashboard
* @module src.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"; import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
@@ -13,18 +15,23 @@ import { logger } from "../constants/Logger.mjs";
import { iterateVoiceStates } from "../constants/VoiceStateResolver.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 { export class Dashboard {
/** @type {boolean} Whether the dashboard is enabled. */
enabled = false; enabled = false;
/** @type {number} Login code expiry time in milliseconds (default 6 hours). */
expiryTime = 1000 * 60 * 60 * 6; expiryTime = 1000 * 60 * 60 * 6;
/** /**
* @param {Remix} remix * Create a new Dashboard instance.
* @param {Object} opts * @param {object} remix - The main bot (Remix) instance.
* @param {boolean} opts.enabled Whether the Dashboard is enabled and connections should be attempted * @param {object} opts - Dashboard options.
* @param {Object} opts.redis Connection options passed directly to redis createClient * @param {boolean} [opts.enabled] - Whether the dashboard is enabled.
* @param {Object} [opts.mysql] MySQL connection config for login code verification * @param {object} [opts.redis] - Redis connection options.
* @param {object} [opts.mysql] - MySQL connection options for the dashboard database.
*/ */
constructor(remix, opts) { constructor(remix, opts) {
this.enabled = opts?.enabled; this.enabled = opts?.enabled;
@@ -129,8 +136,8 @@ export class Dashboard {
/** /**
* Set the bot ID for multi-bot Redis namespace isolation. * Set the bot ID for the Redis platform prefix.
* Updates the Redis platform string so each bot uses its own channel namespace. * @param {string} botId - The bot's Discord user ID.
*/ */
setBotId(botId) { setBotId(botId) {
if (!this.enabled || !this.redis) return; if (!this.enabled || !this.redis) return;
@@ -139,10 +146,13 @@ export class Dashboard {
/** /**
* @param {Object} params * Execute a remote dashboard function (e.g. join, pause, volume).
* @param {string} params.func * @async
* @param {any} params.data * @param {object} params - Function call parameters.
* @returns {Promise<any>} * @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) { async runFunction(params) {
let user; 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. * Verify that the given user is allowed to control the given player.
* @param {import("@fluxerjs/core").User|null} user * Bot owners bypass the check; otherwise the user must be in the same voice channel.
* @param {Player} player * @private
* @returns {string|null} Error message, or null if authorized * @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) { _authorizePlayerControl(user, player) {
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null; 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. * Verify that the given user is a member of the specified guild.
* @param {import("@fluxerjs/core").User} user * Bot owners bypass the check.
* @param {string} guildId * @private
* @returns {Promise<string|null>} Error message, or null if authorized * @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) { async _authorizeUserInGuild(user, guildId) {
if (this.remix.handler?.owners?.includes?.(user.id)) return null; 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) * Look up a player by channel ID, guild ID, or player ID.
* @param {string} id * @private
* @returns {Player|null} * @param {string} id - Channel ID, guild ID, or player ID.
* @returns {object|null} The matching Player instance, or null.
*/ */
_getPlayerById(id) { _getPlayerById(id) {
return this.remix.players.playerMap.get(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) { static convertUser(user) {
let avatarUrl = ""; 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) { static convertVideo(vid) {
if (!vid) return null; 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) { static convertChannel(channel) {
const type = channel.type ?? 0; 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) { static convertServer(guild) {
const channelStore = guild.channels; const channelStore = guild.channels;
@@ -558,8 +587,10 @@ export class Dashboard {
} }
/** /**
* Lightweight server summary for player payloads. * Convert a Discord guild to a lightweight summary object (no channels).
* @param {import("@fluxerjs/core").Guild} guild * @static
* @param {object} guild - The Discord guild.
* @returns {{ name: string, id: string, icon: string|null, description: string|null, ownerId: string|null }}
*/ */
static convertServerSummary(guild) { static convertServerSummary(guild) {
let iconUrl = null; 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) { static convertPlayer(player) {
const channelId = player._channelId; 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) { static convertOption(opt) {
return { return {
@@ -664,8 +702,11 @@ export class Dashboard {
} }
/** /**
* @param {CommandBuilder} com * Convert a command (and its subcommands/options) to a dashboard-safe plain object.
* @param {CommandHandler} commands * @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) { static convertCommand(com, commands) {
return { return {
@@ -684,23 +725,14 @@ export class Dashboard {
} }
/** @private */
_playerUpdateTimers = new Map(); _playerUpdateTimers = new Map();
/** /**
* Global player update (broadcast to all dashboard listeners on {platform}:players). * Broadcast a player state update to the dashboard via Redis.
* * Debounces non-init/close updates by 500ms.
* Used for two purposes: * @param {object} details - The update payload (e.g. `{ type: 'song' }`).
* 1. Lifecycle events: { type: "init" } / { type: "close" } — the backend * @param {object} player - The Player instance that changed.
* 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
*/ */
playerUpdate(details, player) { playerUpdate(details, player) {
if (!this.enabled) return; if (!this.enabled) return;
@@ -738,20 +770,9 @@ export class Dashboard {
} }
/** /**
* Per-player channel update (sent to {platform}:player_{channelId}). * Send a lightweight update to the player-specific Redis channel.
* * @param {object} details - The update payload.
* The backend PlayerManager.setupEvents() expects messages in the format: * @param {object} player - The Player instance.
* { 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
*/ */
updatePlayer(details, player) { updatePlayer(details, player) {
if (!this.enabled) return; if (!this.enabled) return;
@@ -760,9 +781,9 @@ export class Dashboard {
} }
/** /**
* Global user update (sent to {platform}:users). * Broadcast a user update to the global users Redis channel.
* @param {Object} details * @param {object} details - The update payload.
* @param {import("@fluxerjs/core").User} user * @param {object} user - The Discord user.
*/ */
userUpdate(details, user) { userUpdate(details, user) {
if (!this.enabled) return; if (!this.enabled) return;
@@ -774,9 +795,9 @@ export class Dashboard {
} }
/** /**
* Per-user channel update (sent to {platform}:user_{userId}). * Send a lightweight update to the user-specific Redis channel.
* @param {Object} details * @param {object} details - The update payload.
* @param {import("@fluxerjs/core").User} user * @param {object} user - The Discord user.
*/ */
updateUser(details, user) { updateUser(details, user) {
if (!this.enabled) return; if (!this.enabled) return;
@@ -786,13 +807,11 @@ export class Dashboard {
/** /**
* Verify a login code submitted by a user via DM. * Verify a dashboard login code for a user.
* The backend stores the code in MySQL; this method compares the supplied * @async
* code against the stored (bcrypt-hashed) value. * @param {string} user - The Discord user ID.
* * @param {string} code - The login code to verify.
* @param {string} user User ID * @returns {Promise<string|null>} An error message if verification fails, or null on success.
* @param {string} code Plain-text code supplied by the user
* @returns {Promise<string|null>} null on success, error message on failure
*/ */
async confirmLogin(user, code) { async confirmLogin(user, code) {
if (!this.enabled) return "Dashboard not enabled."; 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 dashboard/DatabaseManager
* @module src.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"; import { compare, genSalt, hash } from "bcryptjs";
@@ -8,12 +9,14 @@ import { createPool } from "mysql2/promise";
import { logger } from "../constants/Logger.mjs"; import { logger } from "../constants/Logger.mjs";
/** /**
* DatabaseManager — MySQL pool for dashboard login codes and API tokens. * @class
* Adapted for use with the Fluxer bot. * @description Wraps a mysql2 connection pool with convenience methods for
* parameterised queries and bcrypt hash operations.
*/ */
export class DatabaseManager { 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) { constructor(config) {
this.db = createPool({ this.db = createPool({
@@ -26,19 +29,21 @@ export class DatabaseManager {
} }
/** /**
* Execute a raw SQL query. * Execute a raw SQL query (no parameter binding).
* @param {string} query * @async
* @returns {Promise<[import("mysql2/promise").QueryResult, import("mysql2/promise").FieldPacket[]]>} * @param {string} query - The SQL query string.
* @returns {Promise<Array>} The query result rows and fields.
*/ */
async query(query) { async query(query) {
return this.db.query(query); return this.db.query(query);
} }
/** /**
* Execute a parameterized SQL query. * Execute a parameterised SQL query.
* @param {string} query * @async
* @param {any[]} [data] * @param {string} query - The SQL query with `?` placeholders.
* @returns {Promise<import("mysql2/promise").QueryResult>} * @param {Array} data - The values to bind.
* @returns {Promise<Array>} The result rows.
*/ */
async execute(query, data) { async execute(query, data) {
const [res, _fields] = await this.db.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. * Generate a bcrypt hash of the given plaintext.
* @param {string} plain * @async
* @returns {Promise<string>} * @param {string} plain - The plaintext string.
* @returns {Promise<string>} The hashed string.
*/ */
async hash(plain) { async hash(plain) {
const salt = await genSalt(10); const salt = await genSalt(10);
@@ -57,16 +63,17 @@ export class DatabaseManager {
/** /**
* Compare a plaintext string against a bcrypt hash. * Compare a plaintext string against a bcrypt hash.
* @param {string} plain * @async
* @param {string} hashed * @param {string} plain - The plaintext string.
* @returns {Promise<boolean>} * @param {string} hashed - The bcrypt hash.
* @returns {Promise<boolean>} True if the plaintext matches the hash.
*/ */
async compareHash(plain, hashed) { async compareHash(plain, hashed) {
return await compare(plain, hashed); return await compare(plain, hashed);
} }
/** /**
* Gracefully close the connection pool. * Close the underlying MySQL connection pool.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
close() { close() {
+34 -32
View File
@@ -1,15 +1,19 @@
/** /**
* @file RedisHandler.mjs — RedisHandler — Redis pub/sub handler for cross-process dashboard state synchronization * @module dashboard/RedisHandler
* @module src.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 { createClient } from "redis";
import { logger } from "../constants/Logger.mjs"; import { logger } from "../constants/Logger.mjs";
/** /**
* Default retry strategy: exponential backoff starting at 500ms, max 5s, max 20 retries. * Default reconnection strategy for Redis sockets.
* @param {Object} options * @param {object} options - Reconnection options from the Redis client.
* @returns {number} Delay in ms before next retry, or an Error to stop retrying * @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) => { const DEFAULT_RETRY_STRATEGY = (options) => {
if (options.totalRetryTime > 60_000) { 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 { export class RedisHandler {
/** @type {string} Platform prefix used for Redis channel names. */
platform = "fluxer"; platform = "fluxer";
/** @type {import("redis").RedisClientType|null} */ /** @type {import('redis').RedisClientType|null} The main (publisher) Redis client. */
client = null; client = null;
/** @type {import("redis").RedisClientType|null} */ /** @type {import('redis').RedisClientType|null} The subscriber Redis client. */
subscriber = null; subscriber = null;
/** Whether the handler has been explicitly destroyed */ /** @private @type {boolean} Whether the handler has been destroyed. */
_destroyed = false; _destroyed = false;
/** /**
* @param {Object} opts * Create a new RedisHandler and immediately begin connecting.
* @param {import("redis").RedisClientOptions} opts Redis client options * @param {object} [opts={}] - Redis connection options (passed to `createClient`).
* @param {string} [opts.platform] Platform identifier for channel namespacing * @param {string} [opts.platform] - Platform prefix for channels.
*/ */
constructor(opts = {}) { constructor(opts = {}) {
this.platform = opts.platform ?? "fluxer"; this.platform = opts.platform ?? "fluxer";
@@ -61,8 +68,10 @@ export class RedisHandler {
} }
/** /**
* Connect both publisher and subscriber with reconnection support. * Connect both the publisher and subscriber clients, then subscribe
* Wrapped in a method so it can be called once from the constructor. * to the "request" and "info" channels and start the ping interval.
* @private
* @async
*/ */
async _connect() { async _connect() {
try { try {
@@ -113,12 +122,8 @@ export class RedisHandler {
} }
/** /**
* Send the "connected" announcement to the backend. * Send a "connected" info message to the dashboard after a 5-second debounce.
* Delayed by 5 seconds so the bot has time to initialise players, * @returns {void}
* 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.
*/ */
readyMessage() { readyMessage() {
if (this._destroyed) return; if (this._destroyed) return;
@@ -135,9 +140,10 @@ export class RedisHandler {
/** /**
* Publish a message to a Redis channel. * Publish a message to a Redis channel.
* @param {string} channel * No-op if the handler is destroyed or the client is not ready.
* @param {string} message * @param {string} channel - The Redis channel to publish to.
* @returns {Promise<number>} Number of subscribers that received the message * @param {string} message - The message string to send.
* @returns {Promise<number>} Number of subscribers that received the message.
*/ */
send(channel, message) { send(channel, message) {
if (this._destroyed || !this.client?.isReady) return Promise.resolve(0); if (this._destroyed || !this.client?.isReady) return Promise.resolve(0);
@@ -147,24 +153,20 @@ export class RedisHandler {
}); });
} }
/** /** @type {Function|null} The current request handler function. */
* @callback RequestCallback
* @param {Object} data
* @param {string} data.type
* @returns {Promise<Object>}
*/
handleRequest; handleRequest;
/** /**
* @param {RequestCallback} handler * Set the handler function invoked for incoming "request" payloads.
* @param {Function} handler - Async function `(data) => result`.
*/ */
setRequestHandler(handler) { setRequestHandler(handler) {
this.handleRequest = handler; this.handleRequest = handler;
} }
/** /**
* Gracefully close both Redis connections. * Gracefully close both Redis connections and stop all internal timers.
* Should be called on process shutdown to avoid abrupt connection drops. * @async
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async destroy() { async destroy() {
+9 -4
View File
@@ -1,14 +1,19 @@
/** /** @module src/probe @description Audio probing utilities using ffprobe to extract metadata from media files/streams. */
* @file probe.mjs — Health probe — monitors NodeLink and LiveKit endpoint availability
* @module src.probe
*/
import ffprobe from "ffprobe-static"; import ffprobe from "ffprobe-static";
import { spawn } from "node:child_process"; import { spawn } from "node:child_process";
import { logger } from "./constants/Logger.mjs"; 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; 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) { export default function probe(file) {
return new Promise((res, rej) => { return new Promise((res, rej) => {
const args = [ 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", "pfp": "default",
"locale": "en", "locale": "en",
"stay_247": "none", "stay_247": "none",
"stay_247_mode": "off", "volume": 100
"stay_247_modes": {},
"volume": 100,
"announcementChannelId": null
}, },
"descriptions": { "descriptions": {
"songAnnouncements": "Whether the bot should announce every song in a new message when it starts playing. Set to `true` or `1` to enable.", "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.", "prefix": "The prefix used to trigger commands.",
"pfp": "What profile picture the bot should use. Presets: `default | dark | light | mono | <custom url>`.", "pfp": "What profile picture the bot should use. Presets: `default | dark | light | mono | <custom url>`.",
"locale": "The preferred language of your server.", "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": "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.",
"stay_247_mode": "Legacy guild-wide 24/7 mode. Superseded by stay_247_modes (per-channel). Kept for backward compatibility.", "volume": "The default playback volume for this server (1-200). Saved automatically when you use $prefixvolume."
"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."
} }
} }
+1
View File
@@ -295,6 +295,7 @@
"specifyChannel": "⚠️ أنت لست في قناة صوتية. أنا أعزف في:\n{{channels}}\n\nاستخدم `{{prefix}}leave <#channel>` لمغادرة قناة محددة.", "specifyChannel": "⚠️ أنت لست في قناة صوتية. أنا أعزف في:\n{{channels}}\n\nاستخدم `{{prefix}}leave <#channel>` لمغادرة قناة محددة.",
"noPlayerInChannel": "⚠️ أنا لا أعزف في <#{{channel}}>. أنا في:\n{{channels}}", "noPlayerInChannel": "⚠️ أنا لا أعزف في <#{{channel}}>. أنا في:\n{{channels}}",
"playerNotInit": "المشغّل غير مهيأ.", "playerNotInit": "المشغّل غير مهيأ.",
"left": "✅ تم المغادرة بنجاح",
"leftRejoin247": "✅ تم المغادرة بنجاح — سأعيد الانضمام إلى <#{{channel}}> خلال بضع ثوانٍ.\nلتعطيل وضع 24/7 بشكل دائم، استخدم `{{prefix}}247 off`.", "leftRejoin247": "✅ تم المغادرة بنجاح — سأعيد الانضمام إلى <#{{channel}}> خلال بضع ثوانٍ.\nلتعطيل وضع 24/7 بشكل دائم، استخدم `{{prefix}}247 off`.",
"left247On": "✅ تم المغادرة بنجاح.\nوضع 24/7 **مفعّل** — لن يعود البوت تلقائياً. استخدم `{{prefix}}play` لإعادته، أو `{{prefix}}247 off` لتعطيله بالكامل.\nاستخدم `{{prefix}}247` لعرض جميع القنوات المحفوظة.", "left247On": "✅ تم المغادرة بنجاح.\nوضع 24/7 **مفعّل** — لن يعود البوت تلقائياً. استخدم `{{prefix}}play` لإعادته، أو `{{prefix}}247 off` لتعطيله بالكامل.\nاستخدم `{{prefix}}247` لعرض جميع القنوات المحفوظة.",
"autoRejoinHint": "⚠️ وضع 24/7 مفعّل (تلقائي) — سأعيد الانضمام إلى <#{{channel}}> خلال بضع ثوانٍ.\nلتتمكن من إزالتي بشكل دائم، عطّل وضع 24/7 أولاً: `{{prefix}}247 off`" "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>` بەکاربهێنە بۆ جێهێشتنی کەناڵێکی دیاریکراو.", "specifyChannel": "⚠️ تۆ لە کەناڵێکی دەنگیدا نیت. من پەخش دەکەم لە:\n{{channels}}\n\n`{{prefix}}leave <#channel>` بەکاربهێنە بۆ جێهێشتنی کەناڵێکی دیاریکراو.",
"noPlayerInChannel": "⚠️ من پەخش ناکەم لە <#{{channel}}>. من لە:\n{{channels}}", "noPlayerInChannel": "⚠️ من پەخش ناکەم لە <#{{channel}}>. من لە:\n{{channels}}",
"playerNotInit": "پەخشکەرەکە ئامادە نەکراوە.", "playerNotInit": "پەخشکەرەکە ئامادە نەکراوە.",
"left": "✅ بە سەرکەوتوویی دەرچوو",
"leftRejoin247": "✅ بە سەرکەوتوویی دەرچوو — دووبارە بەشداری <#{{channel}}> دەکەم لە چەند چرکەیەکدا.\nبۆ ناچالاککردنی دۆخی 24/7 بەهەمیشەیی، `{{prefix}}247 off` بەکاربهێنە.", "leftRejoin247": "✅ بە سەرکەوتوویی دەرچوو — دووبارە بەشداری <#{{channel}}> دەکەم لە چەند چرکەیەکدا.\nبۆ ناچالاککردنی دۆخی 24/7 بەهەمیشەیی، `{{prefix}}247 off` بەکاربهێنە.",
"left247On": "✅ بە سەرکەوتوویی دەرچوو.\nدۆخی 24/7 **چالاکە** — بۆتەکە دووبارە خۆی ناچێتەوە. `{{prefix}}play` بەکاربهێنە بۆ گەڕاندنی، یان `{{prefix}}247 off` بۆ ناچالاککردنی تەواو.\n`{{prefix}}247` بەکاربهێنە بۆ بینینی هەموو کەناڵە پاشەکەوتکراوەکان.", "left247On": "✅ بە سەرکەوتوویی دەرچوو.\nدۆخی 24/7 **چالاکە** — بۆتەکە دووبارە خۆی ناچێتەوە. `{{prefix}}play` بەکاربهێنە بۆ گەڕاندنی، یان `{{prefix}}247 off` بۆ ناچالاککردنی تەواو.\n`{{prefix}}247` بەکاربهێنە بۆ بینینی هەموو کەناڵە پاشەکەوتکراوەکان.",
"autoRejoinHint": "⚠️ دۆخی 24/7 چالاکە (خۆکار) — دووبارە بەشداری <#{{channel}}> دەکەم لە چەند چرکەیەکدا.\nبۆ لابردنی من بەهەمیشەیی، سەرەتا دۆخی 24/7 ناچالاک بکە: `{{prefix}}247 off`" "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.", "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}}", "noPlayerInChannel": "⚠️ Ich spiele nicht in <#{{channel}}>. Ich bin in:\n{{channels}}",
"playerNotInit": "Player nicht initialisiert.", "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`.", "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.", "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`" "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.", "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}}", "noPlayerInChannel": "⚠️ I'm not playing in <#{{channel}}>. I'm in:\n{{channels}}",
"playerNotInit": "Player not initialized.", "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`.", "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.", "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`" "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.", "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}}", "noPlayerInChannel": "⚠️ Não estou tocando em <#{{channel}}>. Estou em:\n{{channels}}",
"playerNotInit": "Player não inicializado.", "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`.", "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.", "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`" "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.", "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}}", "noPlayerInChannel": "⚠️ <#{{channel}}> kanalında çalmıyorum. Şu kanallardayım:\n{{channels}}",
"playerNotInit": "Oynatıcı başlatılmadı.", "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.", "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.", "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`" "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
}
]