mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
idk what am doing
This commit is contained in:
1 parent
f9d54a61ef
commit
d00c9fb8a5
8 files changed
+856
-900
No files matched your search
@@ -11,25 +11,68 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://web.fluxer.app/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208">Invite to Server</a> ·
|
||||
<a href="https://fluxer.gg/Remix">Report a Bug</a> ·
|
||||
<a href="https://web.fluxer.app/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208">Invite to Server</a> ·
|
||||
<a href="https://fluxer.gg/Remix">Report a Bug</a> ·
|
||||
<a href="https://fluxer.gg/Remix">Request a Feature</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License">
|
||||
<img src="https://img.shields.io/badge/Fluxer-Bot-7289DA.svg" alt="Fluxer Bot">
|
||||
<img src="https://img.shields.io/badge/Audio-revoice.js-orange.svg" alt="revoice.js">
|
||||
<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/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/Database-MySQL-4479A1.svg" alt="MySQL">
|
||||
<img src="https://img.shields.io/badge/Maintained%3F-Yes-green.svg" alt="Maintained">
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## 🎵 About The Project
|
||||
## Table of Contents
|
||||
|
||||
Remix is a free and open-source music bot for Fluxer, built using [fluxerjs](https://github.com/fluxerjs/core) and powered by [revoice.js](https://github.com/ShadowLp174/revoice.js) for seamless, high-quality audio playback. We believe music features shouldn't be locked behind paywalls—**all commands on Remix are 100% free and always will be.**
|
||||
- [About The Project](#-about-the-project)
|
||||
- [Features](#-features)
|
||||
- [Getting Started (Users)](#-getting-started-users)
|
||||
- [Commands](#-commands)
|
||||
- [Self-Hosting](#-self-hosting-the-bot)
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Installation](#installation)
|
||||
- [Database Setup](#-database-setup)
|
||||
- [Dashboard Setup (Optional)](#-dashboard-setup-optional)
|
||||
- [Configuration Reference](#-configuration-reference)
|
||||
- [Project Architecture](#-project-architecture)
|
||||
- [Localization](#-localization)
|
||||
- [Scripts](#-npm-scripts)
|
||||
- [Credits](#-credits--license)
|
||||
|
||||
## 🚀 Getting Started
|
||||
---
|
||||
|
||||
## 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 `@fluxerjs/voice` for native voice integration alongside the Moonlink Lavalink proxy.
|
||||
|
||||
We believe music features shouldn't be locked behind paywalls — **all commands on Remix are 100% free and always will be.**
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **High-quality audio playback** via moonlink.js (Lavalink proxy) and `@fluxerjs/voice`
|
||||
- **Multi-source search** — YouTube, Spotify, SoundCloud, and direct URL support
|
||||
- **24/7 mode** — keep the bot in a voice channel permanently, with auto-recovery on restart
|
||||
- **Session recovery** — active players and queues survive bot restarts and crash recovery
|
||||
- **Interactive emoji player** — reaction-based control panel with play, pause, skip, volume, shuffle, and more
|
||||
- **Lyrics** — fetch song lyrics via the Genius API
|
||||
- **Radio stations** — built-in support for custom radio streams with keyword-based search
|
||||
- **Server settings** — per-guild configuration for prefix, volume, locale, 24/7 channels, and more
|
||||
- **Web dashboard** — optional browser-based control panel with Redis-backed sessions and Fluxer OAuth2 login
|
||||
- **Multi-language support** — available in English, Arabic, German, Kurdish (Sorani), and Brazilian Portuguese
|
||||
- **Configurable logging** — granular control over which log categories appear in the console
|
||||
- **Graceful shutdown** — saves active session state on SIGINT/SIGTERM for seamless reboot recovery
|
||||
- **Module system** — pluggable module architecture for extending bot functionality
|
||||
|
||||
---
|
||||
|
||||
## Getting Started (Users)
|
||||
|
||||
Want to use Remix in your server right away?
|
||||
|
||||
@@ -39,43 +82,79 @@ Want to use Remix in your server right away?
|
||||
|
||||
---
|
||||
|
||||
## 📜 Commands
|
||||
## Commands
|
||||
|
||||
Below is a complete list of Remix's commands. The default prefix is `%`.
|
||||
Below is the complete list of Remix's commands. The default prefix is `%`.
|
||||
|
||||
| Command | Description | Usage Example | Aliases |
|
||||
### Music
|
||||
|
||||
| Command | Description | Usage | Aliases |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `play` | Play a song from a URL/query, or a playlist. | `%play Never Gonna Give You Up` | `p` |
|
||||
| `playnext` | Play a song/playlist, adding it to the *top* of the queue. | `%playnext 'query: text'` | `pn` |
|
||||
| `pause` | Pause the current playback. | `%pause` | |
|
||||
| `resume` | Resume the paused playback. | `%resume` | |
|
||||
| `skip` | Skip the currently playing song. | `%skip` | |
|
||||
| `list` | View the upcoming queue for your voice channel. | `%list` | `queue` |
|
||||
| `np` | See the name and URL of the currently playing song. | `%np` | `current`, `nowplaying` |
|
||||
| `loop` | Toggle looping for the current song or the whole queue. | `%loop queue` | |
|
||||
| `shuffle` | Re-orders the queue randomly. | `%shuffle` | |
|
||||
| `remove` | Remove a specific song from the queue by its index number. | `%remove 3` | |
|
||||
| `clear` | Remove all songs from the queue. | `%clear` | `c` |
|
||||
| `volume` | Change the volume of the bot. | `%volume 50` | `v` |
|
||||
| `join` | Make the bot join a specific voice channel. | `%join 123456789` | |
|
||||
| `leave` | Make the bot leave your current voice channel. | `%leave` | `l` |
|
||||
| `player` | Create an interactive emoji player control panel. | `%player` | |
|
||||
| `search` | Display search results for a given query to choose from. | `%search 'query'` | |
|
||||
| `settings`| Change or view bot settings for the current server. | `%settings set` | `s` |
|
||||
| `stats` | Display bot statistics, like uptime and ping. | `%stats` | `info` |
|
||||
| `thumbnail`| Get the thumbnail image of the currently playing song. | `%thumbnail` | `thumb` |
|
||||
| `test` | A developer testing command. | `%test 1` | |
|
||||
| `play` | Play a song from a URL, search query, or playlist | `%play Never Gonna Give You Up` | `p` |
|
||||
| `playnext` | Add a song/playlist to the *top* of the queue | `%playnext query: text` | `pn` |
|
||||
| `pause` | Pause the current playback | `%pause` | |
|
||||
| `resume` | Resume the paused playback | `%resume` | |
|
||||
| `skip` | Skip the currently playing song | `%skip` | |
|
||||
| `np` | Show the currently playing song | `%np` | `current`, `nowplaying` |
|
||||
| `list` | View the upcoming queue | `%list` | `queue` |
|
||||
| `loop` | Toggle loop mode (song or queue) | `%loop queue` | |
|
||||
| `shuffle` | Randomize the queue order | `%shuffle` | |
|
||||
| `remove` | Remove a specific song by its queue index | `%remove 3` | |
|
||||
| `clear` | Clear the entire queue | `%clear` | `c` |
|
||||
| `volume` | Change the playback volume (1–200) | `%volume 50` | `v` |
|
||||
| `volumedefault` | Set the default volume for the server | `%volumedefault 80` | |
|
||||
| `search` | Search for a track and pick from results | `%search query` | |
|
||||
| `lyrics` | Fetch lyrics for the current or specified song | `%lyrics` | |
|
||||
| `thumbnail` | Get the thumbnail of the current track | `%thumbnail` | `thumb` |
|
||||
| `radio` | Play a built-in or custom radio station | `%radio` | |
|
||||
|
||||
### Voice Channel
|
||||
|
||||
| Command | Description | Usage | Aliases |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `join` | Make the bot join a specific voice channel | `%join 123456789` | |
|
||||
| `leave` | Make the bot leave the current voice channel | `%leave` | `l` |
|
||||
| `forceleave` | Force the bot to leave any channel (owner only) | `%forceleave` | |
|
||||
|
||||
### Player & UI
|
||||
|
||||
| Command | Description | Usage | Aliases |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `player` | Create an interactive emoji control panel | `%player` | |
|
||||
|
||||
### Settings & Server
|
||||
|
||||
| Command | Description | Usage | Aliases |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `settings` | View or change server settings | `%settings set` | `s` |
|
||||
| `filter` | Manage audio filters (bass, speed, nightcore, etc.) | `%filter bass 50` | |
|
||||
|
||||
### Utility
|
||||
|
||||
| Command | Description | Usage | Aliases |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `stats` | Display bot stats (uptime, ping, node info) | `%stats` | `info` |
|
||||
| `invite` | Get the bot invite link | `%invite` | |
|
||||
| `support` | Get an invite to the support server | `%support` | |
|
||||
| `reload` | Reload commands or settings at runtime (owner) | `%reload` | |
|
||||
| `servers` | List servers the bot is in (owner) | `%servers` | |
|
||||
| `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | |
|
||||
| `debug` | Debugging utilities (owner only) | `%debug` | |
|
||||
| `test` | Developer testing command | `%test 1` | |
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ 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.** Please 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)"*).
|
||||
|
||||
### Prerequisites
|
||||
- Node.js installed
|
||||
- A MySQL Database
|
||||
- A [NodeLink](https://github.com/PerformanC/NodeLink) instance
|
||||
|
||||
- **Node.js** >= 22.0.0 (required by moonlink.js v5)
|
||||
- **MySQL** 8.0+ with JSON column support
|
||||
- **[NodeLink](https://github.com/PerformanC/NodeLink)** instance (Lavalink proxy for audio)
|
||||
- **FFmpeg** (installed automatically via `ffmpeg-static`)
|
||||
- **Redis** (optional, required for the web dashboard)
|
||||
|
||||
### Installation
|
||||
|
||||
@@ -91,52 +170,237 @@ If you prefer to host Remix yourself, please note: **You must make it clear that
|
||||
```
|
||||
|
||||
3. **Configure the bot:**
|
||||
- Rename `config.example.json` to `config.json`.
|
||||
- Fill out the missing values (Bot Token, DB credentials, etc.).
|
||||
- *Note: You can generate Spotify credentials [here](https://developer.spotify.com/).*
|
||||
- Configure your NodeLink instance inside the `config.json` file:
|
||||
```json
|
||||
"nodelink": {
|
||||
"host": "localhost",
|
||||
"port": 3000,
|
||||
"password": "youshallnotpass"
|
||||
}
|
||||
```
|
||||
```bash
|
||||
cp config_example.json config.json
|
||||
```
|
||||
Open `config.json` and fill in the required values:
|
||||
- `token` — your Fluxer bot token
|
||||
- `mysql` — your MySQL connection details (host, port, user, password, database)
|
||||
- `prefix` — the command prefix (default: `%`)
|
||||
- `nodelink` — your NodeLink instance connection details
|
||||
- `spotify` — (optional) Spotify API credentials for Spotify track support
|
||||
- `geniusToken` — (optional) Genius API token for lyrics support
|
||||
- `owners` — array of Fluxer user IDs with owner-only command access
|
||||
|
||||
4. **Setup the Database:** *(See instructions below)*
|
||||
4. **Set up the database:** *(See [Database Setup](#-database-setup) below)*
|
||||
|
||||
5. **Start the bot:**
|
||||
```bash
|
||||
node index.mjs
|
||||
npm start
|
||||
```
|
||||
|
||||
### 🗄️ Database Setup
|
||||
For development with inspector:
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Remix requires a MySQL database to function properly.
|
||||
### Database Setup
|
||||
|
||||
1. Create a dedicated database for Remix to prevent data collisions with other apps.
|
||||
2. Enter your MySQL connection details into `config.json`.
|
||||
3. Run the following SQL query to create the necessary tables:
|
||||
Remix requires a MySQL database to store per-guild settings.
|
||||
|
||||
1. Create a dedicated database for Remix:
|
||||
```sql
|
||||
CREATE DATABASE remix;
|
||||
```
|
||||
|
||||
2. Enter your MySQL connection details into `config.json`:
|
||||
```json
|
||||
"mysql": {
|
||||
"host": "localhost",
|
||||
"port": 3306,
|
||||
"user": "remix",
|
||||
"password": "your-password",
|
||||
"database": "remix"
|
||||
}
|
||||
```
|
||||
|
||||
3. Create the required table:
|
||||
```sql
|
||||
CREATE TABLE `settings` (
|
||||
`id` varchar(70) NOT NULL,
|
||||
`data` json NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
|
||||
```
|
||||
*(Note: If you used the legacy settings system and want to migrate your data, please check the README inside the `settings` folder).*
|
||||
|
||||
4. *(Optional)* If migrating from the legacy settings system, run:
|
||||
```bash
|
||||
npm run migrate
|
||||
```
|
||||
|
||||
### Dashboard Setup (Optional)
|
||||
|
||||
Remix includes a web dashboard for controlling the bot through a browser interface.
|
||||
|
||||
1. Enable the dashboard in `config.json`:
|
||||
```json
|
||||
"dashboard": {
|
||||
"enabled": true,
|
||||
"redis": { "url": "redis://localhost:6379" },
|
||||
"fluxer": {
|
||||
"id": "your-fluxer-oauth2-app-id",
|
||||
"secret": "your-fluxer-oauth2-client-secret",
|
||||
"redirectUri": "https://your-backend.com/auth/fluxer"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. Create a Fluxer OAuth2 application at [https://fluxer.app/developers/applications](https://fluxer.app/developers/applications).
|
||||
|
||||
3. Create the additional database tables required by the dashboard:
|
||||
```sql
|
||||
CREATE TABLE `ksiTokens` (
|
||||
`user` varchar(26) NOT NULL,
|
||||
`id` varchar(50) NOT NULL,
|
||||
`token` varchar(70) 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;
|
||||
```
|
||||
|
||||
4. For HTTPS support, configure SSL in `config.json`:
|
||||
```json
|
||||
"ssl": {
|
||||
"private": "/etc/letsencrypt/live/your.domain/privkey.pem",
|
||||
"cert": "/etc/letsencrypt/live/your.domain/fullchain.pem",
|
||||
"useSSL": true,
|
||||
"httpPort": 80
|
||||
}
|
||||
```
|
||||
|
||||
### Configuration Reference
|
||||
|
||||
Key configuration options in `config.json`:
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| `token` | string | — | **Required.** Fluxer bot token |
|
||||
| `prefix` | string | `%` | Default command prefix |
|
||||
| `embedColor` | string | `0xe9196c` | Hex color for embed messages |
|
||||
| `owners` | string[] | `[]` | User IDs with owner privileges |
|
||||
| `playerAFKTimeout` | number | `60000` | Inactivity timeout in ms before bot leaves |
|
||||
| `webPort` | number | `80` | Port for the web dashboard |
|
||||
| `helpCatalog` | bool | `true` | Enable categorized help command |
|
||||
| `helpPagination` | bool | `true` | Enable paginated help output |
|
||||
| `mysql` | object | — | **Required.** MySQL connection settings |
|
||||
| `nodelink` | object | — | NodeLink connection (host, port, password) |
|
||||
| `spotify` | object | — | Spotify API credentials |
|
||||
| `geniusToken` | string | — | Genius API token for lyrics |
|
||||
| `dashboard` | object | — | Dashboard, Redis, and OAuth2 settings |
|
||||
| `logging` | object | — | Per-category log toggle (see config example) |
|
||||
| `timers` | object | — | Timing values for inactivity, recovery, etc. |
|
||||
| `cache` | object | — | Guild and member cache limits |
|
||||
| `radio` | array | `[]` | Custom radio station definitions |
|
||||
| `ssl` | object | — | SSL certificate paths and HTTPS toggle |
|
||||
|
||||
---
|
||||
|
||||
## 💬 Contact & Support
|
||||
## Project Architecture
|
||||
|
||||
If you have any questions, need help setting up, or just want to hang out with other Remix users, join our official Fluxer server:
|
||||
|
||||
👉 **[Join the Remix Support Server](https://fluxer.gg/Remix)**
|
||||
```
|
||||
fluxer/
|
||||
├── index.mjs # Entry point — Remix class, boot sequence, error handling
|
||||
├── config_example.json # Configuration template
|
||||
├── package.json
|
||||
├── commands/ # Command modules (one file per command)
|
||||
│ ├── play.mjs # Play a track or playlist
|
||||
│ ├── player.mjs # Interactive emoji control panel
|
||||
│ ├── settings.mjs # Per-guild settings management
|
||||
│ ├── lyrics.mjs # Genius lyrics fetcher
|
||||
│ ├── filter.mjs # Audio filter controls
|
||||
│ ├── radio.mjs # Radio station management
|
||||
│ └── ... # All other commands
|
||||
├── src/
|
||||
│ ├── CommandHandler.mjs # Command loader, prefix manager, registry
|
||||
│ ├── MessageHandler.mjs # Message parsing, embed builder, pagination, help
|
||||
│ ├── PlayerManager.mjs # Spawns and manages per-channel Player instances
|
||||
│ ├── Player.mjs # Core player — queue, playback, filters, events
|
||||
│ ├── MoonlinkManager.mjs # Moonlink.js (Lavalink) node session manager
|
||||
│ ├── Settings.mjs # RemoteSettingsManager + ServerSettings export
|
||||
│ ├── GatewayHandler.mjs # Raw WS events, voice-state tracking, presence rotation
|
||||
│ ├── RecoveryManager.mjs # Session persistence, crash recovery, 24/7 auto-join
|
||||
│ ├── Utils.mjs # Shared utilities
|
||||
│ ├── worker.mjs # Background task worker
|
||||
│ ├── probe.mjs # FFprobe wrapper for audio stream info
|
||||
│ ├── constants/
|
||||
│ │ ├── Logger.mjs # Structured logger with per-category control
|
||||
│ │ ├── Locale.mjs # i18n translation engine
|
||||
│ │ ├── providers.mjs # Audio source provider definitions
|
||||
│ │ └── audio/
|
||||
│ │ ├── StreamMerger.mjs # Audio stream merging utilities
|
||||
│ │ └── Tuna.mjs # Audio filter/effect processing
|
||||
│ └── dashboard/
|
||||
│ ├── Dashboard.mjs # Web dashboard server (Express + WebSocket)
|
||||
│ └── RedisHandler.mjs # Redis session and pub/sub handler
|
||||
├── settings/
|
||||
│ ├── Settings.mjs # Abstract SettingsManager base class
|
||||
│ ├── migrate.mjs # Legacy-to-remote settings migration script
|
||||
│ └── runnables.mjs # Runnable task definitions
|
||||
└── storage/
|
||||
├── defaults.json # Default per-guild settings template
|
||||
├── modules.json # Plugin module registry
|
||||
├── stats.json # Runtime statistics
|
||||
└── locales/bot/ # Translation files
|
||||
├── en.json
|
||||
├── ar-SA.json
|
||||
├── de-DE.json
|
||||
├── ckb.json
|
||||
└── pt-BR.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Localization
|
||||
|
||||
Remix supports multiple languages out of the box. The locale system loads JSON translation files from `storage/locales/bot/` and serves the appropriate language based on each guild's `locale` setting.
|
||||
|
||||
Currently supported languages:
|
||||
|
||||
| Code | Language |
|
||||
| :--- | :--- |
|
||||
| `en` | English (default) |
|
||||
| `ar-SA` | Arabic |
|
||||
| `de-DE` | German |
|
||||
| `ckb` | Kurdish (Sorani) |
|
||||
| `pt-BR` | Brazilian Portuguese |
|
||||
|
||||
To add a new language, place a JSON file in `storage/locales/bot/` following the same key structure as `en.json`, then set the locale per guild with `%settings set locale <code>`.
|
||||
|
||||
---
|
||||
|
||||
## npm Scripts
|
||||
|
||||
| Script | Command | Description |
|
||||
| :--- | :--- | :--- |
|
||||
| `npm start` | `node index.mjs` | Start the bot |
|
||||
| `npm run dev` | `node --inspect index.mjs --trace-warnings` | Start with Node.js inspector |
|
||||
| `npm run commands` | `node index.mjs usage` | Generate command usage documentation |
|
||||
| `npm run defaultsSync` | `node index.mjs sreload` | Sync default settings to all guilds |
|
||||
| `npm run migrate` | `node settings/migrate.mjs` | Run the legacy settings migration |
|
||||
|
||||
---
|
||||
|
||||
## Credits & License
|
||||
|
||||
**Design & Development:**
|
||||
- [ShadowLp174](https://github.com/ShadowLp174) — Lead developer, audio engine, moonlink.js
|
||||
- NoLogicAlan — Dashboard design
|
||||
- ophx — Dashboard design
|
||||
- Fantic — Contributions
|
||||
|
||||
**Powered by:**
|
||||
- [`@fluxerjs/core`](https://github.com/fluxerjs/core) — Fluxer API client
|
||||
- [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) — Native voice integration
|
||||
- [`moonlink.js`](https://github.com/ShadowLp174/moonlink.js) — Lavalink proxy
|
||||
- [NodeLink](https://github.com/PerformanC/NodeLink) — Audio node manager
|
||||
|
||||
<p align="center">
|
||||
© 2026 Remix. Code licensed under the <a href="LICENSE">MIT License</a>.<br>
|
||||
<em>The Remix name, logo, and branding are proprietary and may not be reused.</em>
|
||||
</p>
|
||||
</p>
|
||||
+5
-2
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"Comment": "Fluxer music bot configuration. IMPORTANT: Node.js >= 22.0.0 is required (moonlink.js v5 dependency). Run 'node --version' to verify.",
|
||||
"token": "your bot token",
|
||||
"fluxer.js": {
|
||||
"Comment": "Configuration data for @fluxerjs/core Client options. See: https://github.com/fluxerjs/core",
|
||||
@@ -114,6 +115,8 @@
|
||||
"playerSessionTimeout": 300000,
|
||||
"intentionalLeaveTTL": 10000,
|
||||
"recoveryStaggerMs": 2000,
|
||||
"recoveryConcurrency": 2
|
||||
"recoveryConcurrency": 2,
|
||||
"maxTransientRetries": 5,
|
||||
"retryBaseDelay": 15000
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -220,6 +220,8 @@ export class Remix {
|
||||
player: this.playerContext,
|
||||
dashboard: this.dashboard,
|
||||
locale: this.locale,
|
||||
spawnPlayer: this._spawnPlayer,
|
||||
timers: this.T,
|
||||
});
|
||||
this.players.observedVoiceUsers = this.observedVoiceUsers;
|
||||
|
||||
@@ -613,3 +615,10 @@ const saveAndExit = async () => {
|
||||
process.once("SIGINT", saveAndExit);
|
||||
process.once("SIGTERM", saveAndExit);
|
||||
process.once("SIGUSR2", saveAndExit);
|
||||
|
||||
// ── SIGPIPE handler ──────────────────────────────────────────────────────────
|
||||
// On some systems, writing to a broken pipe (e.g. Redis connection) raises
|
||||
// SIGPIPE which defaults to terminating the process. Ignoring it lets the
|
||||
// error surface through the normal exception/rejection handlers above so
|
||||
// recovery state is saved before exit.
|
||||
process.on("SIGPIPE", () => {});
|
||||
Generated
+197
-735
File diff suppressed because it is too large.
Load diff
+16
-19
@@ -548,14 +548,9 @@ export class GatewayHandler {
|
||||
// Bot moved channels — auto-save 247 setting
|
||||
if (channelId && guildId && oldChannelId && oldChannelId !== channelId) {
|
||||
try {
|
||||
if (multiVoiceGuild) {
|
||||
logger.voice247(
|
||||
`[247] Skipping bot move gateway auto-save ${oldChannelId} → ${channelId} ` +
|
||||
`(guild ${guildId} has ${activeGuildPlayers.length} active players)`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// For multi-voice guilds, only re-key if we can unambiguously match
|
||||
// the player by oldChannelId. Previously this skipped entirely for
|
||||
// multi-voice guilds, which broke recovery for all channels.
|
||||
const cleanId = String(channelId).replace(/\D/g, "");
|
||||
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
||||
|
||||
@@ -573,9 +568,16 @@ export class GatewayHandler {
|
||||
let rekeyed = false;
|
||||
if (existingPlayer && cleanId !== cleanOld) {
|
||||
if (guildIsAmbiguous) {
|
||||
// Multi-voice guild: can't safely re-key the playerMap (another player
|
||||
// might already use cleanId), but still update the moved player's
|
||||
// home channel so 24/7 recovery targets the right channel.
|
||||
existingPlayer._channelId = cleanId;
|
||||
existingPlayer._home247Channel = cleanId;
|
||||
if (targetGuildId) existingPlayer._guildId = targetGuildId;
|
||||
rekeyed = false; // keep false — don't touch playerMap keys
|
||||
logger.voice247(
|
||||
`[247] Skipping bot move auto-rekey ${cleanOld} → ${cleanId} ` +
|
||||
`(guild ${guildId} has ${guildPlayers.length} active players)`
|
||||
`[247] Updated player channel ${cleanOld} → ${cleanId} ` +
|
||||
`(guild ${guildId} has ${guildPlayers.length} active players, skipped re-key)`
|
||||
);
|
||||
} else if (playerGuildId && targetGuildId && playerGuildId !== targetGuildId) {
|
||||
logger.warn(
|
||||
@@ -595,7 +597,7 @@ export class GatewayHandler {
|
||||
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
const raw = set.get("stay_247");
|
||||
if (rekeyed && raw && raw !== "none") {
|
||||
if ((rekeyed || existingPlayer) && raw && raw !== "none") {
|
||||
const channels = Array.isArray(raw)
|
||||
? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean))
|
||||
: new Set([String(raw).replace(/\D/g, "")]);
|
||||
@@ -603,6 +605,7 @@ export class GatewayHandler {
|
||||
channels.delete(cleanOld);
|
||||
channels.add(cleanId);
|
||||
set.set("stay_247", [...channels]);
|
||||
logger.voice247(`[247] Updated stay_247: ${cleanOld} → ${cleanId}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -613,14 +616,6 @@ export class GatewayHandler {
|
||||
// Bot disconnected unexpectedly — rejoin if 247 active
|
||||
if (!channelId && oldChannelId && guildId) {
|
||||
try {
|
||||
if (multiVoiceGuild) {
|
||||
logger.voice247(
|
||||
`[247] Skipping bot disconnect gateway recovery for ${oldChannelId} ` +
|
||||
`(guild ${guildId} has ${activeGuildPlayers.length} active players)`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
||||
if (remix.intentionalLeaves.has(cleanOld)) {
|
||||
logger.voice247(`[247] Skipping rejoin for ${cleanOld} — intentional leave.`);
|
||||
@@ -634,6 +629,8 @@ export class GatewayHandler {
|
||||
if (channels.has(cleanOld)) {
|
||||
const mode = set.get("stay_247_mode") ?? "auto";
|
||||
if (mode === "on" || mode === "auto") {
|
||||
// For multi-voice guilds, match the specific player by channel ID
|
||||
// instead of skipping recovery entirely (was: if multiVoiceGuild return)
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player && !player.leaving) {
|
||||
logger.voice247("[247] Fluxer gateway disconnected us. Forcing player recovery...");
|
||||
|
||||
+109
-43
@@ -504,7 +504,8 @@ export default class Player extends EventEmitter {
|
||||
this.emit("autoleave");
|
||||
return;
|
||||
}
|
||||
const backoffMs = Math.min(2000 * this._recoveryAttempts, 30_000);
|
||||
// Exponential backoff: 2s, 4s, 8s, 16s, 32s (was linear: 2s, 4s, 6s, 8s, 10s)
|
||||
const backoffMs = Math.min(2000 * Math.pow(2, this._recoveryAttempts - 1), 30_000);
|
||||
logger.mediaplayer(`[Player] Recovery attempt ${this._recoveryAttempts}/${MAX_RECOVERY} for ${this._guildId} (backoff ${backoffMs}ms)`);
|
||||
await Utils.sleep(backoffMs);
|
||||
|
||||
@@ -514,6 +515,28 @@ export default class Player extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
// Wait for _isJoining to clear — if another operation (e.g. spawnPlayer or
|
||||
// a concurrent _recoverConnection from a different event path) is currently
|
||||
// calling join(), we must not race against it. Poll every 500ms for up to
|
||||
// 15s, then give up on this attempt and schedule a retry.
|
||||
let waited = 0;
|
||||
while (this._isJoining && waited < 15_000) {
|
||||
logger.mediaplayer(`[Player] Waiting for _isJoining to clear before recovery attempt...`);
|
||||
await Utils.sleep(500);
|
||||
waited += 500;
|
||||
}
|
||||
if (this._isJoining) {
|
||||
logger.warn("[Player] _isJoining still busy after 15s — deferring recovery attempt.");
|
||||
this._isRecovering = false;
|
||||
this._recoveryPending = false;
|
||||
// Schedule a retry via setTimeout so we don't stack synchronous calls
|
||||
this._recoveryTimer = setTimeout(() => {
|
||||
this._recoveryTimer = null;
|
||||
this._recoverConnection().catch(() => {});
|
||||
}, 2000);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.mediaplayer(`[Player] Attempting to recover voice connection for ${this._guildId}`);
|
||||
|
||||
try {
|
||||
@@ -1114,57 +1137,100 @@ export default class Player extends EventEmitter {
|
||||
|
||||
const room = connection.room;
|
||||
if (room) {
|
||||
logger.mediaplayer("[Player] Waiting for LiveKit room to connect...");
|
||||
logger.mediaplayer(`[Player] Room obtained (state: ${room.state}), settling...`);
|
||||
|
||||
// ── connectionStateChanged is unreliable on this LiveKit build ───────
|
||||
// The native lk-rtc layer connects and logs "connected to room", but
|
||||
// the JS wrapper often NEVER fires "connectionStateChanged" with
|
||||
// "connected" and room.state does not reflect the live state.
|
||||
// Waiting for that event causes a guaranteed 15 s timeout.
|
||||
//
|
||||
// Strategy: listen for the event as a best-effort fast path (resolves
|
||||
// instantly if it works), but also poll room.state every 500 ms.
|
||||
// If NEITHER detects "connected" within a short window, check whether
|
||||
// the room is in an obviously-dead state. If not, assume connected
|
||||
// and let _ensureMediaPlayer (publishToRoom) be the real gate — it
|
||||
// will throw if the room is genuinely unusable.
|
||||
let connected = false;
|
||||
let settled = false;
|
||||
|
||||
if (room.state === "connected" || room.state === 1) {
|
||||
logger.mediaplayer("[Player] Room already connected");
|
||||
connected = true;
|
||||
} else {
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
room.off("connectionStateChanged", onStateChange);
|
||||
reject(new Error("LiveKit connection timeout"));
|
||||
}, 15_000);
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
clearInterval(poll);
|
||||
try { room.off("connectionStateChanged", onStateChange); } catch (_) {}
|
||||
};
|
||||
|
||||
const onStateChange = (state) => {
|
||||
logger.mediaplayer(`[Player] LiveKit state changed: ${state}`);
|
||||
// only resolve on "connected" — never on "connecting".
|
||||
// "connecting" is a transient state and the engine may collapse
|
||||
// before publishToRoom can run, causing the "engine is closed" error.
|
||||
if (state === "connected" || state === 1) {
|
||||
clearTimeout(timeout);
|
||||
room.off("connectionStateChanged", onStateChange);
|
||||
connected = true;
|
||||
resolve();
|
||||
} else if (state === "disconnected" || state === 0 || state === "failed") {
|
||||
clearTimeout(timeout);
|
||||
room.off("connectionStateChanged", onStateChange);
|
||||
reject(new Error(`LiveKit failed: ${state}`));
|
||||
}
|
||||
};
|
||||
const timeout = setTimeout(() => {
|
||||
// Timeout — not necessarily a failure. The room may be connected
|
||||
// at the native level with no JS event/state propagation.
|
||||
logger.mediaplayer("[Player] connectionStateChanged not detected, checking state...");
|
||||
cleanup();
|
||||
const s = room.state;
|
||||
if (s === "disconnected" || s === 0 || s === "failed") {
|
||||
reject(new Error(`LiveKit failed: ${s}`));
|
||||
} else {
|
||||
// Indeterminate state (undefined, "connecting", etc.)
|
||||
// — optimistically proceed; MediaPlayer will validate.
|
||||
connected = true;
|
||||
settled = true;
|
||||
resolve();
|
||||
}
|
||||
}, 3_000); // 3 s instead of 15 s — avoid blocking recovery
|
||||
|
||||
room.on("connectionStateChanged", onStateChange);
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error("[Player] LiveKit connection failed:", err.message);
|
||||
throw err;
|
||||
}
|
||||
const onStateChange = (state) => {
|
||||
if (settled) return;
|
||||
logger.mediaplayer(`[Player] LiveKit state changed: ${state}`);
|
||||
if (state === "connected" || state === 1) {
|
||||
connected = true;
|
||||
cleanup();
|
||||
resolve();
|
||||
} else if (state === "disconnected" || state === 0 || state === "failed") {
|
||||
cleanup();
|
||||
reject(new Error(`LiveKit failed: ${state}`));
|
||||
}
|
||||
};
|
||||
|
||||
room.on("connectionStateChanged", onStateChange);
|
||||
|
||||
// Poll room.state every 500 ms as a fallback for builds where
|
||||
// the event never fires but the getter eventually updates.
|
||||
const poll = setInterval(() => {
|
||||
if (settled) return;
|
||||
const s = room.state;
|
||||
if (s === "connected" || s === 1) {
|
||||
connected = true;
|
||||
cleanup();
|
||||
resolve();
|
||||
} else if (s === "disconnected" || s === 0 || s === "failed") {
|
||||
cleanup();
|
||||
reject(new Error(`LiveKit failed: ${s}`));
|
||||
}
|
||||
}, 500);
|
||||
|
||||
// Immediate check after listener is registered.
|
||||
const currentState = room.state;
|
||||
if (currentState === "connected" || currentState === 1) {
|
||||
connected = true;
|
||||
cleanup();
|
||||
logger.mediaplayer("[Player] Room already connected (immediate check)");
|
||||
resolve();
|
||||
} else if (currentState === "disconnected" || currentState === 0 || currentState === "failed") {
|
||||
cleanup();
|
||||
reject(new Error(`LiveKit failed: ${currentState}`));
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error("[Player] LiveKit connection failed:", err.message);
|
||||
throw err;
|
||||
}
|
||||
|
||||
await Utils.sleep(300);
|
||||
|
||||
// re-check liveness using the `connected` flag set by the event
|
||||
// handler rather than re-reading room.state — on some LiveKit builds the
|
||||
// state getter returns undefined outside of the event callback even when
|
||||
// the room is healthy (the property is not persistently stored).
|
||||
if (!connected) {
|
||||
if (connected) {
|
||||
logger.mediaplayer("[Player] Room ready, proceeding to MediaPlayer");
|
||||
} else {
|
||||
throw new Error("LiveKit room did not reach connected state");
|
||||
}
|
||||
|
||||
logger.mediaplayer("[Player] Proceeding to create MediaPlayer (room confirmed alive)");
|
||||
} else {
|
||||
// connection.room is null — this happens when joinVoiceChannel returns
|
||||
// a stale/recycled connection object before the LiveKit room is assigned,
|
||||
|
||||
+38
-13
@@ -86,6 +86,8 @@ export class PlayerManager {
|
||||
this.playerConfig = config.player;
|
||||
this.dashboard = config.dashboard ?? null;
|
||||
this.locale = config.locale ?? null;
|
||||
this.spawnPlayer = config.spawnPlayer ?? null; // RecoveryManager.spawnPlayer — for 24/7 rejoin on autoleave
|
||||
this.timers = config.timers ?? {};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -596,25 +598,48 @@ export class PlayerManager {
|
||||
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
|
||||
const ch = player.textChannel;
|
||||
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
|
||||
const is247 = (() => {
|
||||
try {
|
||||
const raw = this.settings.getServer(guildId)?.get("stay_247");
|
||||
return raw && raw !== "none";
|
||||
} catch (_) { return false; }
|
||||
|
||||
// Check 24/7 settings for this channel
|
||||
const raw247 = (() => {
|
||||
try { return this.settings.getServer(guildId)?.get("stay_247"); } catch (_) { return null; }
|
||||
})();
|
||||
const prefix = (() => {
|
||||
try {
|
||||
return this.settings.getServer(guildId)?.get("prefix") ?? "%";
|
||||
} catch (_) { return "%"; }
|
||||
const mode247 = (() => {
|
||||
try { return this.settings.getServer(guildId)?.get("stay_247_mode") ?? "off"; } catch (_) { return "off"; }
|
||||
})();
|
||||
const desc = is247
|
||||
? this.locale?.translate(guildId, "responses.join.autoLeaveInactive", { channel: `<#${activeChannelId}>` }) ?? `Left channel <#${activeChannelId}> because of inactivity.`
|
||||
: 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\``;
|
||||
ch?.send(mkEmbed(desc));
|
||||
const isIn247List = (() => {
|
||||
if (!raw247 || raw247 === "none") return false;
|
||||
const channels = Array.isArray(raw247)
|
||||
? raw247.map(id => String(id).replace(/\D/g, "")).filter(Boolean)
|
||||
: [String(raw247).replace(/\D/g, "")].filter(Boolean);
|
||||
return channels.includes(homeChannelId) || channels.includes(activeChannelId);
|
||||
})();
|
||||
|
||||
// Remove player from map and destroy
|
||||
this.playerMap.delete(activeChannelId);
|
||||
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
|
||||
if (homeChannelId !== activeChannelId) this.playerMap.delete(homeChannelId);
|
||||
player.destroy();
|
||||
|
||||
if (isIn247List && (mode247 === "on" || mode247 === "auto")) {
|
||||
// 24/7 is active — rejoin after a short delay (same as RecoveryManager.spawnPlayer autoleave)
|
||||
const delay = this.timers?.rejoin247Delay ?? 3000;
|
||||
if (this.spawnPlayer) {
|
||||
logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} in ${delay}ms`);
|
||||
setTimeout(() => {
|
||||
this.spawnPlayer(guildId, homeChannelId, 0, null, "initplayer-autoleave").catch(e =>
|
||||
logger.warn("[AutoLeave] 24/7 rejoin failed for", homeChannelId, e.message)
|
||||
);
|
||||
}, delay);
|
||||
}
|
||||
} else {
|
||||
// Not 24/7 — send inactivity message
|
||||
const prefix = (() => {
|
||||
try { return this.settings.getServer(guildId)?.get("prefix") ?? "%"; } catch (_) { return "%"; }
|
||||
})();
|
||||
const 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\``;
|
||||
ch?.send(mkEmbed(desc));
|
||||
}
|
||||
});
|
||||
|
||||
player.on("leave", () => {});
|
||||
|
||||
+159
-29
@@ -30,10 +30,14 @@ export class RecoveryManager {
|
||||
// ── Internal state ────────────────────────────────────────────────────────
|
||||
/** @type {Set<string>} Per-channel spawn mutex */
|
||||
this.pendingSpawns = new Set();
|
||||
/** @type {Map<string, {timer, guildId, recoveryData, reason}>} Scheduled delayed spawns */
|
||||
/** @type {Map<string, {timer, guildId, recoveryData, reason, retryCount}>} Scheduled delayed spawns */
|
||||
this.scheduledSpawns = new Map();
|
||||
/** @type {string} Path to the recovery JSON file */
|
||||
this.recoveryPath = "./storage/recovery.json";
|
||||
/** @type {number} Maximum transient retry attempts per channel before giving up */
|
||||
this.maxTransientRetries = remix.config.timers?.maxTransientRetries ?? 5;
|
||||
/** @type {number} Base delay multiplier for exponential backoff (ms) */
|
||||
this.retryBaseDelay = remix.config.timers?.retryBaseDelay ?? 15_000;
|
||||
|
||||
// ── Ready flags ───────────────────────────────────────────────────────────
|
||||
this.botReady = false;
|
||||
@@ -92,7 +96,9 @@ export class RecoveryManager {
|
||||
preferredVolume: player.preferredVolume ?? 1,
|
||||
savedAt: Date.now(),
|
||||
});
|
||||
} catch (_) {}
|
||||
} catch (e) {
|
||||
logger.warn(`[Recovery] Failed to serialize session for channel ${channelKey}:`, e?.message ?? e);
|
||||
}
|
||||
}
|
||||
|
||||
return sessions;
|
||||
@@ -125,7 +131,9 @@ export class RecoveryManager {
|
||||
guildId,
|
||||
channelId,
|
||||
home247ChannelId: this.normalizeChannelId(session?.home247ChannelId) || channelId,
|
||||
queue: Array.isArray(session?.queue) ? session.queue : [],
|
||||
queue: Array.isArray(session?.queue)
|
||||
? session.queue.filter(t => t && (t.encoded || t.uri || t.url))
|
||||
: [],
|
||||
loopQueue: !!session?.loopQueue,
|
||||
loopSong: !!session?.loopSong,
|
||||
});
|
||||
@@ -134,27 +142,90 @@ export class RecoveryManager {
|
||||
return [...deduped.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up all state for a guild the bot is no longer a member of.
|
||||
* Mirrors the GUILD_DELETE handler in GatewayHandler so that servers
|
||||
* kicked while offline are fully purged on the next boot.
|
||||
*
|
||||
* @param {string} guildId
|
||||
* @param {string} [reason="bot no longer in guild"]
|
||||
*/
|
||||
cleanStaleGuild(guildId, reason = "bot no longer in guild") {
|
||||
const { remix } = this;
|
||||
const cleanId = String(guildId).replace(/\D/g, "");
|
||||
logger.recovery(`[Recovery] Cleaning stale guild ${cleanId} (${reason}).`);
|
||||
|
||||
// Destroy any active players for this guild
|
||||
for (const [channelId, player] of remix.players.playerMap) {
|
||||
if (!player._guildId || String(player._guildId).replace(/\D/g, "") === cleanId) {
|
||||
remix.players.playerMap.delete(channelId);
|
||||
try { player.leave().catch(() => {}); } catch (_) {}
|
||||
try { player.destroy(); } catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
// Cancel any scheduled spawns for this guild
|
||||
for (const [channelId, entry] of this.scheduledSpawns) {
|
||||
if (String(entry.guildId).replace(/\D/g, "") === cleanId) {
|
||||
clearTimeout(entry.timer);
|
||||
this.scheduledSpawns.delete(channelId);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean voice-user observations
|
||||
for (const [userId, info] of [...remix.observedVoiceUsers]) {
|
||||
if (String(info.guildId).replace(/\D/g, "") === cleanId) remix.observedVoiceUsers.delete(userId);
|
||||
}
|
||||
for (const [userId, info] of [...remix.observedVoiceBots]) {
|
||||
if (String(info.guildId).replace(/\D/g, "") === cleanId) remix.observedVoiceBots.delete(userId);
|
||||
}
|
||||
|
||||
// Remove from settings cache
|
||||
remix.settingsMgr.removeServer(cleanId);
|
||||
remix._announcementChannelCache?.delete?.(cleanId);
|
||||
}
|
||||
|
||||
// ── Spawn scheduling ─────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Schedule a delayed player spawn. Cancels any previous scheduled spawn for
|
||||
* the same channel.
|
||||
*
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @param {number} [delayMs=0]
|
||||
* @param {Object|null} [recoveryData=null]
|
||||
* @param {string} [reason="spawn"]
|
||||
* @param {number} [retryCount=0] Current retry attempt number (0 = first try).
|
||||
*/
|
||||
scheduleSpawn(guildId, channelId, delayMs = 0, recoveryData = null, reason = "spawn") {
|
||||
scheduleSpawn(guildId, channelId, delayMs = 0, recoveryData = null, reason = "spawn", retryCount = 0) {
|
||||
const cleanChannelId = this.normalizeChannelId(channelId);
|
||||
if (!cleanChannelId) return;
|
||||
|
||||
const existing = this.scheduledSpawns.get(cleanChannelId);
|
||||
if (existing) clearTimeout(existing.timer);
|
||||
|
||||
// Capture retryCount in the closure BEFORE the entry is deleted,
|
||||
// so spawnPlayer receives the correct count for exponential backoff.
|
||||
const capturedRetryCount = retryCount;
|
||||
const timer = setTimeout(() => {
|
||||
this.scheduledSpawns.delete(cleanChannelId);
|
||||
this.spawnPlayer(guildId, cleanChannelId, 0, recoveryData).catch(e => {
|
||||
this.spawnPlayer(guildId, cleanChannelId, 0, recoveryData, capturedRetryCount).catch(e => {
|
||||
logger.warn(`[PlayerSpawn] Scheduled ${reason} failed for ${cleanChannelId}:`, e?.message ?? e);
|
||||
});
|
||||
}, Math.max(0, delayMs));
|
||||
|
||||
this.scheduledSpawns.set(cleanChannelId, { timer, guildId, recoveryData, reason });
|
||||
this.scheduledSpawns.set(cleanChannelId, { timer, guildId, recoveryData, reason, retryCount });
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the exponential backoff delay for a given retry attempt.
|
||||
* Delay doubles each attempt: base, base*2, base*4, base*8, …
|
||||
* Capped at 5 minutes to avoid excessive waits.
|
||||
*/
|
||||
getRetryDelay(retryCount) {
|
||||
const delay = this.retryBaseDelay * Math.pow(2, retryCount);
|
||||
return Math.min(delay, 300_000); // cap at 5 minutes
|
||||
}
|
||||
|
||||
// ── Player spawning ──────────────────────────────────────────────────────────
|
||||
@@ -163,7 +234,7 @@ export class RecoveryManager {
|
||||
* Create a new Player, join the target voice channel, and optionally restore
|
||||
* recovery state.
|
||||
*/
|
||||
async spawnPlayer(guildId, channelId, delayMs = 0, recoveryData = null) {
|
||||
async spawnPlayer(guildId, channelId, delayMs = 0, recoveryData = null, retryCount = 0) {
|
||||
const { remix } = this;
|
||||
|
||||
if (delayMs > 0) await new Promise(r => setTimeout(r, delayMs));
|
||||
@@ -171,12 +242,16 @@ export class RecoveryManager {
|
||||
const cleanChannelId = this.normalizeChannelId(channelId);
|
||||
if (!cleanChannelId) return;
|
||||
|
||||
// Clean up any previously scheduled spawn for this channel.
|
||||
const scheduled = this.scheduledSpawns.get(cleanChannelId);
|
||||
if (scheduled) {
|
||||
clearTimeout(scheduled.timer);
|
||||
this.scheduledSpawns.delete(cleanChannelId);
|
||||
}
|
||||
|
||||
// Use the passed-in retryCount (from scheduleSpawn's closure) rather
|
||||
// than reading from the now-deleted scheduledSpawns entry.
|
||||
|
||||
// Only enforce 24/7 check if we are NOT recovering from a reboot
|
||||
if (!recoveryData) {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
@@ -292,12 +367,15 @@ export class RecoveryManager {
|
||||
ch?.send({ embeds: [{ description: String(m), color: getGlobalColor() }] }).catch(() => {});
|
||||
});
|
||||
|
||||
remix.players.playerMap.set(cleanChannelId, p);
|
||||
|
||||
// ── Join channel ───────────────────────────────────────────────────────
|
||||
// NOTE: playerMap.set happens AFTER join() succeeds so that other code
|
||||
// (alone-check, voice state handlers) never sees a non-connected player.
|
||||
try {
|
||||
await p.join(cleanChannelId);
|
||||
|
||||
// Only add to playerMap once the join is confirmed successful.
|
||||
remix.players.playerMap.set(cleanChannelId, p);
|
||||
|
||||
// Record the intended 247 home channel for this player.
|
||||
p._home247Channel = cleanChannelId;
|
||||
|
||||
@@ -337,24 +415,55 @@ export class RecoveryManager {
|
||||
try { p.destroy(); } catch (_) {}
|
||||
logger.warn("[PlayerSpawn] Failed to join channel", cleanChannelId, "guild", guildId, e.message);
|
||||
|
||||
// Retry if the failure is a transient LiveKit race
|
||||
// ── Guild membership check for 401 errors ───────────────────────────
|
||||
// If the bot was kicked while offline (or between retries), the 401 will
|
||||
// keep repeating. Verify the bot is still in the guild — if not, clean
|
||||
// up all state and skip retries entirely.
|
||||
if (e.message?.includes("401 Unauthorized") && !remix.client.guilds.has(guildId)) {
|
||||
logger.warn(
|
||||
`[PlayerSpawn] 401 on guild ${guildId} — bot no longer in server. ` +
|
||||
`Cleaning up and skipping retries.`
|
||||
);
|
||||
this.cleanStaleGuild(guildId, "401 and bot not in guild");
|
||||
return;
|
||||
}
|
||||
|
||||
// Retry if the failure is a transient LiveKit race (with max retries + backoff)
|
||||
const isTransient = e.message?.includes("engine is closed") ||
|
||||
e.message?.includes("MediaPlayer after retry") ||
|
||||
e.message?.includes("LiveKit connection timeout") ||
|
||||
e.message?.includes("LiveKit failed") ||
|
||||
e.message?.includes("No room available");
|
||||
const shouldRetry = isTransient && !recoveryData?.queue?.length
|
||||
? (() => {
|
||||
try {
|
||||
const raw = remix.settingsMgr.getServer(guildId)?.get("stay_247");
|
||||
return raw && raw !== "none";
|
||||
} catch (_) { return false; }
|
||||
})()
|
||||
: isTransient && !!recoveryData;
|
||||
e.message?.includes("No room available") ||
|
||||
e.message?.includes("401 Unauthorized") ||
|
||||
e.message?.includes("signal failure");
|
||||
|
||||
// Use the retryCount passed into spawnPlayer from scheduleSpawn's closure.
|
||||
const prevRetryCount = retryCount;
|
||||
|
||||
const shouldRetry = isTransient && prevRetryCount < this.maxTransientRetries
|
||||
&& (
|
||||
!recoveryData?.queue?.length
|
||||
? (() => {
|
||||
try {
|
||||
const raw = remix.settingsMgr.getServer(guildId)?.get("stay_247");
|
||||
return raw && raw !== "none";
|
||||
} catch (_) { return false; }
|
||||
})()
|
||||
: !!recoveryData
|
||||
);
|
||||
if (shouldRetry) {
|
||||
const retryDelay = this.T.rejoin247Delay * 3;
|
||||
logger.warn(`[PlayerSpawn] Transient join failure — retrying in ${retryDelay}ms`);
|
||||
this.scheduleSpawn(guildId, cleanChannelId, retryDelay, recoveryData ?? null, "transient-join-retry");
|
||||
const nextRetry = prevRetryCount + 1;
|
||||
const retryDelay = this.getRetryDelay(prevRetryCount);
|
||||
logger.warn(
|
||||
`[PlayerSpawn] Transient join failure — retry ${nextRetry}/${this.maxTransientRetries} ` +
|
||||
`in ${retryDelay}ms (channel=${cleanChannelId})`
|
||||
);
|
||||
this.scheduleSpawn(guildId, cleanChannelId, retryDelay, recoveryData ?? null, "transient-join-retry", nextRetry);
|
||||
} else if (isTransient) {
|
||||
logger.error(
|
||||
`[PlayerSpawn] Giving up on channel ${cleanChannelId} after ${prevRetryCount} retry(es). ` +
|
||||
`Last error: ${e.message}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,16 +548,18 @@ export class RecoveryManager {
|
||||
const joinList = [];
|
||||
|
||||
// 1. Recover standard reboot sessions
|
||||
let recoveryFileExisted = false;
|
||||
if (fs.existsSync(this.recoveryPath)) {
|
||||
logger.recovery("[Recovery] Found previous session data, restoring...");
|
||||
recoveryFileExisted = true;
|
||||
let data = null;
|
||||
try {
|
||||
data = JSON.parse(fs.readFileSync(this.recoveryPath, "utf8"));
|
||||
fs.unlinkSync(this.recoveryPath);
|
||||
} catch (e) {
|
||||
logger.error("[Recovery] Failed to read/parse recovery file:", e);
|
||||
try { fs.unlinkSync(this.recoveryPath); } catch (_) {}
|
||||
}
|
||||
// NOTE: File is deleted AFTER all spawns complete (see below).
|
||||
// This prevents data loss if the process crashes mid-recovery.
|
||||
const sessions = this.normalizeRecoverySessions(data);
|
||||
for (const session of sessions) {
|
||||
joinList.push({
|
||||
@@ -479,16 +590,29 @@ export class RecoveryManager {
|
||||
}
|
||||
}
|
||||
|
||||
if (joinList.length === 0) return;
|
||||
// ── Filter out guilds the bot is no longer a member of ────────────────
|
||||
const filteredList = [];
|
||||
for (const item of joinList) {
|
||||
if (!remix.client.guilds.has(item.guildId)) {
|
||||
logger.recovery(
|
||||
`[Recovery] Skipping guild ${item.guildId} channel ${item.channelId} — bot is no longer in the server.`
|
||||
);
|
||||
this.cleanStaleGuild(item.guildId);
|
||||
} else {
|
||||
filteredList.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
if (filteredList.length === 0) return;
|
||||
|
||||
const startTime = Date.now();
|
||||
logger.recovery(
|
||||
`[Recovery] Joining ${joinList.length} session(s) ` +
|
||||
`[Recovery] Joining ${filteredList.length} session(s) ` +
|
||||
`(concurrency: ${this.T.recoveryConcurrency}, stagger: ${this.T.recoveryStaggerMs}ms)...`
|
||||
);
|
||||
|
||||
const errors = await this.runWithConcurrency(
|
||||
joinList,
|
||||
filteredList,
|
||||
this.T.recoveryConcurrency,
|
||||
this.T.recoveryStaggerMs,
|
||||
async (item) => {
|
||||
@@ -502,15 +626,21 @@ export class RecoveryManager {
|
||||
);
|
||||
|
||||
const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
|
||||
const ok = joinList.length - errors.length;
|
||||
const ok = filteredList.length - errors.length;
|
||||
if (errors.length > 0) {
|
||||
for (const err of errors) {
|
||||
logger.error("[Recovery] Failed to join channel", err.channelId, "guild", err.guildId, err.error);
|
||||
}
|
||||
}
|
||||
logger.recovery(
|
||||
`[Recovery] Processed ${joinList.length} session(s) in ${elapsed}s ` +
|
||||
`[Recovery] Processed ${filteredList.length} session(s) in ${elapsed}s ` +
|
||||
`(${ok} ok, ${errors.length} failed).`
|
||||
);
|
||||
|
||||
// Delete recovery file AFTER all spawns have been attempted (success or fail).
|
||||
// If the process crashes mid-recovery, the file still exists for next boot.
|
||||
if (recoveryFileExisted) {
|
||||
try { fs.unlinkSync(this.recoveryPath); } catch (_) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user