mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
Compare commits
73
Commits
91e7812c30
...
495970ffe9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
495970ffe9 | ||
|
|
98a69d471a | ||
|
|
2e631c0213 | ||
|
|
c90f591ec1 | ||
|
|
b2af315240 | ||
|
|
6bca127365 | ||
|
|
c3ff07093f | ||
|
|
c9332a15af | ||
|
|
da477ebf03 | ||
|
|
d78af55f10 | ||
|
|
bdee46b7f2 | ||
|
|
2907749bac | ||
|
|
ade75a4a79 | ||
|
|
452c080224 | ||
|
|
04ce02f672 | ||
|
|
22f48cfaab | ||
|
|
a99e5bca37 | ||
|
|
e501fc62fb | ||
|
|
1cfe577055 | ||
|
|
7c7d94b3fb | ||
|
|
cc91e602fc | ||
|
|
5866dbf8d8 | ||
|
|
dc65627d82 | ||
|
|
c7ce4045ed | ||
|
|
028e31af14 | ||
|
|
7b217ae790 | ||
|
|
43eb97d57c | ||
|
|
6936060ec8 | ||
|
|
3815f131cf | ||
|
|
0c8349f44b | ||
|
|
5e39679f45 | ||
|
|
5ac04535f3 | ||
|
|
755efa5afd | ||
|
|
c9d932067e | ||
|
|
21197e7f22 | ||
|
|
f1b2e43f8a | ||
|
|
84c597ec3c | ||
|
|
954e7c6b73 | ||
|
|
0d084bf127 | ||
|
|
9ddbcb682f | ||
|
|
c188aac903 | ||
|
|
e51d89bd14 | ||
|
|
4bade0869d | ||
|
|
a319257abc | ||
|
|
03cc3c2606 | ||
|
|
36139837ba | ||
|
|
e3dd7ad914 | ||
|
|
3ea54939b9 | ||
|
|
6c826891eb | ||
|
|
cc07c35f2a | ||
|
|
8b99bd01dc | ||
|
|
aa56d98809 | ||
|
|
36ad89b1d2 | ||
|
|
1251d8a53f | ||
|
|
ed76a6ebfe | ||
|
|
7df4e0cd36 | ||
|
|
26aed399fc | ||
|
|
08634adb88 | ||
|
|
357197016b | ||
|
|
f939878028 | ||
|
|
a5afb6651a | ||
|
|
37fe5146cb | ||
|
|
f28b798084 | ||
|
|
71bd628549 | ||
|
|
69b158f7f6 | ||
|
|
975eeca389 | ||
|
|
36dcbd6687 | ||
|
|
cc679f5735 | ||
|
|
65aa23049e | ||
|
|
c419e9e7c6 | ||
|
|
0ec41c9bb5 | ||
|
|
a0d6f32ea8 | ||
|
|
7c5fb1e468 |
No files matched your search
@@ -53,6 +53,9 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
mkdir -p "$HOME/.kube"
|
mkdir -p "$HOME/.kube"
|
||||||
echo "${{ secrets.KUBE_CONFIG }}" | base64 --decode > "$HOME/.kube/config"
|
echo "${{ secrets.KUBE_CONFIG }}" | base64 --decode > "$HOME/.kube/config"
|
||||||
|
CLUSTER_NAME=$(kubectl config view -o jsonpath='{.clusters[0].name}')
|
||||||
|
kubectl config unset "clusters.${CLUSTER_NAME}.certificate-authority-data"
|
||||||
|
kubectl config set-cluster "$CLUSTER_NAME" --insecure-skip-tls-verify=true
|
||||||
|
|
||||||
- name: Verify cluster connectivity
|
- name: Verify cluster connectivity
|
||||||
run: kubectl get deployment fluxer -n fh-nologicalan-remix
|
run: kubectl get deployment fluxer -n fh-nologicalan-remix
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://web.fluxer.app/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208">Invite Remix</a> ·
|
<a href="https://fluxer.com/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208">Invite Remix</a> ·
|
||||||
<a href="https://fluxer.gg/remix">Join Support Server</a> ·
|
<a href="https://fluxer.gg/remix">Join Support Server</a> ·
|
||||||
<a href="https://github.com/remix-bot/fluxer/issues">Report an Issue</a>
|
<a href="https://github.com/remix-bot/fluxer/issues">Report an Issue</a>
|
||||||
</p>
|
</p>
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
<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/Node.js-%3E%3D22.13.0-339933.svg" alt="Node.js">
|
||||||
<img src="https://img.shields.io/badge/Voice-LiveKit%20%2B%20NodeLink-orange.svg" alt="Audio Engine">
|
<img src="https://img.shields.io/badge/Voice-LiveKit%20%2B%20NodeLink-orange.svg" alt="Audio Engine">
|
||||||
<img src="https://img.shields.io/badge/Database-MySQL-4479A1.svg" alt="Database">
|
<img src="https://img.shields.io/badge/Database-MySQL-4479A1.svg" alt="Database">
|
||||||
<img src="https://img.shields.io/badge/Languages-6%20Locales-9b59b6.svg" alt="Localization">
|
<img src="https://img.shields.io/badge/Languages-8%20Locales-9b59b6.svg" alt="Localization">
|
||||||
<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>
|
||||||
|
|
||||||
@@ -29,7 +29,7 @@
|
|||||||
|
|
||||||
## 🌟 Overview
|
## 🌟 Overview
|
||||||
|
|
||||||
**Remix** is a feature-rich, self-hostable music bot built specifically for [Fluxer](https://fluxer.app). Built on [`@fluxerjs/core`](https://github.com/fluxerjs/core) and [`@fluxerjs/voice`](https://github.com/fluxerjs/voice), it streams ultra-low-latency Opus audio directly to LiveKit voice channels using an optimized [NodeLink](https://github.com/PerformanC/NodeLink) backend.
|
**Remix** is a feature-rich, self-hostable music bot built specifically for [Fluxer](https://fluxer.com). Built on [`@fluxerjs/core`](https://github.com/fluxerjs/core) and [`@fluxerjs/voice`](https://github.com/fluxerjs/voice), it streams ultra-low-latency Opus audio directly to LiveKit voice channels using an optimized [NodeLink](https://github.com/PerformanC/NodeLink) backend.
|
||||||
|
|
||||||
We believe essential music features should never be locked behind a paywall — **every feature on Remix is 100% free and open-source.**
|
We believe essential music features should never be locked behind a paywall — **every feature on Remix is 100% free and open-source.**
|
||||||
|
|
||||||
@@ -47,7 +47,9 @@ We believe essential music features should never be locked behind a paywall —
|
|||||||
* 📊 **Loudness Normalization** — Built-in EBU R128 / ReplayGain leveling (`%normalize`) to eliminate volume jumps between quiet acoustic songs and loud EDM tracks.
|
* 📊 **Loudness Normalization** — Built-in EBU R128 / ReplayGain leveling (`%normalize`) to eliminate volume jumps between quiet acoustic songs and loud EDM tracks.
|
||||||
* 📈 **Comprehensive Last.fm Suite** — Real-time scrobbling, loved tracks synchronization, artist crowns, server leaderboards, profile cards, and automated similar-track autoplay.
|
* 📈 **Comprehensive Last.fm Suite** — Real-time scrobbling, loved tracks synchronization, artist crowns, server leaderboards, profile cards, and automated similar-track autoplay.
|
||||||
* 📑 **Massive Playlist Ingestion** — Asynchronous chunked ingestion for large Spotify and SoundCloud playlists (>100 tracks) with instant playback start on song #1.
|
* 📑 **Massive Playlist Ingestion** — Asynchronous chunked ingestion for large Spotify and SoundCloud playlists (>100 tracks) with instant playback start on song #1.
|
||||||
* 🌐 **Full 6-Language Localization** — English, Arabic, Kurdish (Sorani), Turkish, German, and Brazilian Portuguese.
|
* 🌐 **Full 8-Language Localization** — English, Arabic, Kurdish (Sorani), Turkish, German, Brazilian Portuguese, Simplified Chinese, and Traditional Chinese.
|
||||||
|
* 💾 **Personal Saved Playlists & Favorites** — Bookmark favorite tracks (`%fav`) and save custom queue snapshots (`%playlist save <name>`) stored per-user in MySQL for seamless playback across all servers.
|
||||||
|
* 📊 **Community & Personal Music Analytics** — Server leaderboards (`%top`) with custom timeframes (`24h`, `week`, `month`, `year`, `all`, `global`), Server Music Wrapped (`%wrapped`), and personal listening recap profiles (`%mywrapped` / `%top me`) backed by permanent MySQL analytics.
|
||||||
* 🛡️ **Hardened Security & Reliability** — Built-in SSRF protection with DNS-rebinding guards (`SafeHttp`) and automated credential redaction (`[REDACTED]`) in owner diagnostics.
|
* 🛡️ **Hardened Security & Reliability** — Built-in SSRF protection with DNS-rebinding guards (`SafeHttp`) and automated credential redaction (`[REDACTED]`) in owner diagnostics.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -55,7 +57,7 @@ We believe essential music features should never be locked behind a paywall —
|
|||||||
## 🚀 Getting Started
|
## 🚀 Getting Started
|
||||||
|
|
||||||
### Invite to Your Server
|
### Invite to Your Server
|
||||||
1. Click here to **[Invite Remix](https://web.fluxer.app/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208)** to your Fluxer server.
|
1. Click here to **[Invite Remix](https://fluxer.com/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208)** to your Fluxer server.
|
||||||
2. Join any voice channel.
|
2. Join any voice channel.
|
||||||
3. Type `%play <song title or URL>` to start listening!
|
3. Type `%play <song title or URL>` to start listening!
|
||||||
|
|
||||||
@@ -96,6 +98,13 @@ The default prefix is `%`. Server administrators can customize the prefix at any
|
|||||||
| `loop` | — | Toggle repeat mode (`song`, `queue`, or `off`) | `%loop queue` |
|
| `loop` | — | Toggle repeat mode (`song`, `queue`, or `off`) | `%loop queue` |
|
||||||
| `trackopt` | `to` | Configure custom start/end timestamps | `%trackopt set 0:30 3:15` |
|
| `trackopt` | `to` | Configure custom start/end timestamps | `%trackopt set 0:30 3:15` |
|
||||||
|
|
||||||
|
### 💾 Personal Playlists & Favorites
|
||||||
|
|
||||||
|
| Command | Aliases | Description | Example |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `fav` | `favorite`, `favorites`, `bookmark` | Save or remove playing track from personal favorites, list, or play | `%fav` / `%fav play` / `%fav list` |
|
||||||
|
| `playlist` | `pl`, `playlists` | Save active queue as a named playlist, play, list, or manage personal playlists | `%playlist save chill` / `%playlist play chill` / `%playlist list` |
|
||||||
|
|
||||||
### 🎛️ Audio Effects & Filters
|
### 🎛️ Audio Effects & Filters
|
||||||
|
|
||||||
| Command | Aliases | Description | Example |
|
| Command | Aliases | Description | Example |
|
||||||
@@ -117,6 +126,14 @@ The default prefix is `%`. Server administrators can customize the prefix at any
|
|||||||
| `lastfm top` | — | View your top tracks, artists, or albums | `%lastfm top artists` |
|
| `lastfm top` | — | View your top tracks, artists, or albums | `%lastfm top artists` |
|
||||||
| `lastfm lb` | — | View server-wide scrobble leaderboard | `%lastfm lb` |
|
| `lastfm lb` | — | View server-wide scrobble leaderboard | `%lastfm lb` |
|
||||||
|
|
||||||
|
### 🏆 Leaderboards & Community Stats
|
||||||
|
|
||||||
|
| Command | Aliases | Description | Example |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `top` | `leaderboard`, `chart`, `toptracks` | Most played tracks and top artists with interactive pagination and timeframes (`24h`, `week`, `month`, `year`, `all`, `global`) | `%top` / `%top 24h` / `%top global` |
|
||||||
|
| `wrapped` | `recap`, `summary` | Server or network-wide music listening recap and personality card | `%wrapped` / `%wrapped global` |
|
||||||
|
| `mywrapped` | `myrecap`, `personalwrapped`, `me`, `djstats` | Personal listening recap, personal top 5 tracks, favorite artist, and server DJ rank | `%mywrapped` / `%top me` |
|
||||||
|
|
||||||
### ⚙️ Server & Voice Settings
|
### ⚙️ Server & Voice Settings
|
||||||
|
|
||||||
| Command | Aliases | Description | Example |
|
| Command | Aliases | Description | Example |
|
||||||
@@ -159,6 +176,7 @@ Open `docker/config.json` and insert your bot token:
|
|||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"token": "YOUR_FLUXER_BOT_TOKEN",
|
"token": "YOUR_FLUXER_BOT_TOKEN",
|
||||||
|
"instanceUrl": null,
|
||||||
"prefix": "%",
|
"prefix": "%",
|
||||||
"owners": ["YOUR_USER_ID"],
|
"owners": ["YOUR_USER_ID"],
|
||||||
"mysql": {
|
"mysql": {
|
||||||
@@ -176,6 +194,9 @@ Open `docker/config.json` and insert your bot token:
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> Set `"instanceUrl": "https://chat.example.com/api"` if connecting Remix to a self-hosted Fluxer instance instead of the official platform (include `/api` if your instance mounts REST endpoints under `/api`).
|
||||||
|
|
||||||
### 3. Start the Stack
|
### 3. Start the Stack
|
||||||
```bash
|
```bash
|
||||||
docker compose up -d
|
docker compose up -d
|
||||||
@@ -216,14 +237,16 @@ User (%play) ──► Command Handler ──► LavalinkManager (NodeLink Searc
|
|||||||
|
|
||||||
Remix automatically adapts to each server's configured locale (`%settings set locale <code>`):
|
Remix automatically adapts to each server's configured locale (`%settings set locale <code>`):
|
||||||
|
|
||||||
| Code | Language | Native Name |
|
| Flag | Code | Language | Native Name |
|
||||||
| :---: | :--- | :--- |
|
| :---:| :---: | :--- | :--- |
|
||||||
| `en` | English | English (Default) |
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/bcbcbdfb-8bbf-4fcf-a778-5d324ad47c9f" />| `en` | English | English (Default) |
|
||||||
| `ar-SA` | Arabic | العربية |
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/2e3cc42a-47e5-4d6e-9b99-c6f5534cee87" />| `ar-SA` | Arabic | العربية |
|
||||||
| `ckb` | Kurdish (Sorani) | کوردیی ناوەندی |
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/44bc9ba4-0bee-4141-96b6-d144e4c5089a" />| `ckb` | Central Kurdish (Sorani) | کوردیی ناوەندی |
|
||||||
| `tr` | Turkish | Türkçe |
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/6dddb041-52ec-4dca-ab37-22d1ef3cc78d" />| `tr` | Turkish | Türkçe |
|
||||||
| `de-DE` | German | Deutsch |
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/558a97e5-579e-4bca-8cbb-a684a5678a1a" />| `de-DE` | German | Deutsch |
|
||||||
| `pt-BR` | Portuguese (Brazil) | Português Brasileiro |
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/d7177647-d53c-418e-b4c1-cb16aaa77323" />| `pt-BR` | Portuguese (Brazil) | Português Brasileiro |
|
||||||
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/53d34c41-6a4c-4f69-88e7-32a09d6f4945" />| `zh-CN` | Simplified Chinese | 简体中文 |
|
||||||
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/4ee1d3a2-c047-442f-9710-0e43cdb2baf7" />| `zh-TW` | Traditional Chinese | 繁體中文 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
+90
-54
@@ -15,19 +15,19 @@ export const command = new CommandBuilder()
|
|||||||
.addAliases("ap");
|
.addAliases("ap");
|
||||||
|
|
||||||
/** How many candidate results are considered for random picking. */
|
/** How many candidate results are considered for random picking. */
|
||||||
const PICK_POOL = 8;
|
const PICK_POOL = 20;
|
||||||
/** Tracks considered "recently played" and excluded from re-picking. */
|
/** Tracks considered "recently played" and excluded from re-picking. */
|
||||||
const HISTORY_SIZE = 30;
|
const HISTORY_SIZE = 30;
|
||||||
/** Sanity bounds for candidate durations (ms) — skip hour-long mixes and jingles. */
|
/** Sanity bounds for candidate durations (ms) — skip hour-long mixes and jingles. */
|
||||||
const MIN_DURATION_MS = 45_000;
|
const MIN_DURATION_MS = 45_000;
|
||||||
const MAX_DURATION_MS = 15 * 60_000;
|
const MAX_DURATION_MS = 15 * 60_000;
|
||||||
/** Resolved mix candidate pools older than this are discarded. */
|
/** Resolved mix candidate pools older than this are discarded (2 hours). */
|
||||||
const MIX_POOL_TTL_MS = 5 * 60_000;
|
const MIX_POOL_TTL_MS = 2 * 60 * 60_000;
|
||||||
/** Max mix pools cached per player (LRU-style eviction). */
|
/** Max mix pools cached per player (LRU-style eviction). */
|
||||||
const MAX_MIX_POOLS = 4;
|
const MAX_MIX_POOLS = 8;
|
||||||
|
|
||||||
/** Max Last.fm tag lookups per pick (each uncached lookup is a network call). */
|
/** Max Last.fm tag lookups per pick (each uncached lookup is a network call). */
|
||||||
const MAX_TAG_CHECKS = 8;
|
const MAX_TAG_CHECKS = 16;
|
||||||
/** Last.fm tag weights are 0-100 relative to the top tag; ignore the long tail. */
|
/** Last.fm tag weights are 0-100 relative to the top tag; ignore the long tail. */
|
||||||
const TAG_MIN_COUNT = 30;
|
const TAG_MIN_COUNT = 30;
|
||||||
/** Number of genre tags kept per artist. */
|
/** Number of genre tags kept per artist. */
|
||||||
@@ -255,16 +255,19 @@ function rememberTrack(p, track) {
|
|||||||
* Check whether a candidate track is acceptable: not recently played, sane duration.
|
* Check whether a candidate track is acceptable: not recently played, sane duration.
|
||||||
* @param {object} p - The player instance.
|
* @param {object} p - The player instance.
|
||||||
* @param {object} t - Candidate internal track object.
|
* @param {object} t - Candidate internal track object.
|
||||||
|
* @param {boolean} [allowOldHistory=false] - When true, only avoids the most recent 5 songs.
|
||||||
* @returns {boolean} True if the candidate is playable and not a recent repeat.
|
* @returns {boolean} True if the candidate is playable and not a recent repeat.
|
||||||
*/
|
*/
|
||||||
function isCandidateOk(p, t) {
|
function isCandidateOk(p, t, allowOldHistory = false) {
|
||||||
if (!t) return false;
|
if (!t) return false;
|
||||||
const ms = Number(t._durationMs) || (Number(t.duration?.seconds) * 1000) || 0;
|
const ms = Number(t._durationMs) || (Number(t.duration?.seconds) * 1000) || 0;
|
||||||
if (ms && (ms < MIN_DURATION_MS || ms > MAX_DURATION_MS)) return false;
|
if (ms && (ms < MIN_DURATION_MS || ms > MAX_DURATION_MS)) return false;
|
||||||
const vid = extractVideoId(t);
|
const vid = extractVideoId(t);
|
||||||
if (vid && (p._autoplayHistory ?? []).some(h => h.vid === vid)) return false;
|
const history = p._autoplayHistory ?? [];
|
||||||
|
const historySlice = allowOldHistory ? history.slice(-5) : history;
|
||||||
|
if (vid && historySlice.some(h => h.vid === vid)) return false;
|
||||||
const title = String(t?.title ?? "").toLowerCase().trim();
|
const title = String(t?.title ?? "").toLowerCase().trim();
|
||||||
if (title && (p._autoplayHistory ?? []).some(h => h.title && h.title === title)) return false;
|
if (title && historySlice.some(h => h.title && h.title === title)) return false;
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -275,9 +278,10 @@ function isCandidateOk(p, t) {
|
|||||||
* @param {object} p - The player instance.
|
* @param {object} p - The player instance.
|
||||||
* @param {string} videoId - The video ID the pool was resolved from.
|
* @param {string} videoId - The video ID the pool was resolved from.
|
||||||
* @param {(t: object) => Promise<boolean>} [guard] - Optional genre guard.
|
* @param {(t: object) => Promise<boolean>} [guard] - Optional genre guard.
|
||||||
|
* @param {boolean} [allowOldHistory=false] - Whether to relax history exclusion.
|
||||||
* @returns {Promise<object|null>} An acceptable track from the pool, or null.
|
* @returns {Promise<object|null>} An acceptable track from the pool, or null.
|
||||||
*/
|
*/
|
||||||
async function takeFromPool(p, videoId, guard) {
|
async function takeFromPool(p, videoId, guard, allowOldHistory = false) {
|
||||||
const pools = p._autoplayMixPools;
|
const pools = p._autoplayMixPools;
|
||||||
if (!pools) return null;
|
if (!pools) return null;
|
||||||
const pool = pools.get(videoId);
|
const pool = pools.get(videoId);
|
||||||
@@ -286,7 +290,7 @@ async function takeFromPool(p, videoId, guard) {
|
|||||||
pools.delete(videoId);
|
pools.delete(videoId);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const ok = shuffle(pool.tracks.filter(t => isCandidateOk(p, t)));
|
const ok = shuffle(pool.tracks.filter(t => isCandidateOk(p, t, allowOldHistory)));
|
||||||
const rejected = new Set();
|
const rejected = new Set();
|
||||||
let found = null;
|
let found = null;
|
||||||
for (const t of ok) {
|
for (const t of ok) {
|
||||||
@@ -294,7 +298,7 @@ async function takeFromPool(p, videoId, guard) {
|
|||||||
rejected.add(t);
|
rejected.add(t);
|
||||||
}
|
}
|
||||||
if (rejected.size) pool.tracks = pool.tracks.filter(t => !rejected.has(t));
|
if (rejected.size) pool.tracks = pool.tracks.filter(t => !rejected.has(t));
|
||||||
if (!found && !pool.tracks.some(t => isCandidateOk(p, t))) pools.delete(videoId);
|
if (!found && !pool.tracks.some(t => isCandidateOk(p, t, allowOldHistory))) pools.delete(videoId);
|
||||||
return found;
|
return found;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -320,13 +324,14 @@ function storePool(p, videoId, candidates) {
|
|||||||
* @param {object} p - The player instance.
|
* @param {object} p - The player instance.
|
||||||
* @param {string} query - The search query or URL.
|
* @param {string} query - The search query or URL.
|
||||||
* @param {string} provider - Provider shorthand key ("yt", "ytm", ...).
|
* @param {string} provider - Provider shorthand key ("yt", "ytm", ...).
|
||||||
|
* @param {boolean} [allowOldHistory=false] - Whether to relax history exclusion.
|
||||||
* @returns {Promise<Array<object>>} Acceptable candidate tracks.
|
* @returns {Promise<Array<object>>} Acceptable candidate tracks.
|
||||||
*/
|
*/
|
||||||
async function resolveCandidates(p, query, provider = "ytm") {
|
async function resolveCandidates(p, query, provider = "ytm", allowOldHistory = false) {
|
||||||
const resolved = await p.generalQuery({ query, provider });
|
const resolved = await p.generalQuery({ query, provider });
|
||||||
const list = resolved?.type === "list" ? (resolved.data ?? [])
|
const list = resolved?.type === "list" ? (resolved.data ?? [])
|
||||||
: resolved?.type === "video" && resolved.data ? [resolved.data] : [];
|
: resolved?.type === "video" && resolved.data ? [resolved.data] : [];
|
||||||
return list.filter(t => isCandidateOk(p, t));
|
return list.filter(t => isCandidateOk(p, t, allowOldHistory));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -335,10 +340,11 @@ async function resolveCandidates(p, query, provider = "ytm") {
|
|||||||
* @param {string} query - The search query.
|
* @param {string} query - The search query.
|
||||||
* @param {(t: object) => (boolean|Promise<boolean>)} accept - Extra acceptance test (artist/genre).
|
* @param {(t: object) => (boolean|Promise<boolean>)} accept - Extra acceptance test (artist/genre).
|
||||||
* @param {string} [provider="ytm"] - Provider shorthand key.
|
* @param {string} [provider="ytm"] - Provider shorthand key.
|
||||||
|
* @param {boolean} [allowOldHistory=false] - Whether to relax history exclusion.
|
||||||
* @returns {Promise<object|null>} A passing track, or null.
|
* @returns {Promise<object|null>} A passing track, or null.
|
||||||
*/
|
*/
|
||||||
async function searchAccepted(p, query, accept, provider = "ytm") {
|
async function searchAccepted(p, query, accept, provider = "ytm", allowOldHistory = false) {
|
||||||
const found = await resolveCandidates(p, query, provider);
|
const found = await resolveCandidates(p, query, provider, allowOldHistory);
|
||||||
for (const t of shuffle(found.slice(0, PICK_POOL))) {
|
for (const t of shuffle(found.slice(0, PICK_POOL))) {
|
||||||
if (await accept(t)) return t;
|
if (await accept(t)) return t;
|
||||||
}
|
}
|
||||||
@@ -346,12 +352,8 @@ async function searchAccepted(p, query, accept, provider = "ytm") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Choose the next track. Everything is anchored to the "seed" — the last track a
|
* Choose the next track. Anchored to the seed while allowing smooth progression
|
||||||
* person actually chose — and, when Last.fm is available, every candidate's
|
* and infinite fallback so playback never halts after a handful of tracks.
|
||||||
* artist must share the seed artist's genre tags. Search results must also be by
|
|
||||||
* the artist we asked for, so a title collision (a different band's song with the
|
|
||||||
* same name) can no longer slip through. The old title-only search fallback was
|
|
||||||
* removed for the same reason.
|
|
||||||
* @param {object} p - The player instance.
|
* @param {object} p - The player instance.
|
||||||
* @param {object} ctx - The bot context (needs .lastfm).
|
* @param {object} ctx - The bot context (needs .lastfm).
|
||||||
* @param {object|null} lastTrack - The last played internal track.
|
* @param {object|null} lastTrack - The last played internal track.
|
||||||
@@ -363,6 +365,7 @@ export async function pickAutoplayTrack(p, ctx, lastTrack) {
|
|||||||
const seedArtist = artistOf(seed);
|
const seedArtist = artistOf(seed);
|
||||||
const seedName = titleOf(seed);
|
const seedName = titleOf(seed);
|
||||||
const seedVid = extractVideoId(seed);
|
const seedVid = extractVideoId(seed);
|
||||||
|
const lastVid = extractVideoId(lastTrack);
|
||||||
const lf = ctx?.lastfm?.enabled ? ctx.lastfm : null;
|
const lf = ctx?.lastfm?.enabled ? ctx.lastfm : null;
|
||||||
|
|
||||||
let seedTags = p._autoplaySeedTags ?? null;
|
let seedTags = p._autoplaySeedTags ?? null;
|
||||||
@@ -372,14 +375,14 @@ export async function pickAutoplayTrack(p, ctx, lastTrack) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const budget = { left: MAX_TAG_CHECKS };
|
const budget = { left: MAX_TAG_CHECKS };
|
||||||
/** True if the candidate belongs to the seed's genre (or genre can't be judged). */
|
/** True if candidate matches genre tags or tag budget is exhausted. */
|
||||||
const genreOk = async (t) => {
|
const genreOk = async (t) => {
|
||||||
if (!lf || !seedTags?.size) return true;
|
if (!lf || !seedTags?.size) return true;
|
||||||
const ca = artistOf(t);
|
const ca = artistOf(t);
|
||||||
if (!ca) return false;
|
if (!ca) return true;
|
||||||
if (artistMatches(ca, seedArtist)) return true;
|
if (artistMatches(ca, seedArtist)) return true;
|
||||||
if (!hasFreshTags(ca)) {
|
if (!hasFreshTags(ca)) {
|
||||||
if (budget.left <= 0) return false;
|
if (budget.left <= 0) return true;
|
||||||
budget.left--;
|
budget.left--;
|
||||||
}
|
}
|
||||||
return genreOverlaps(seedTags, await getGenreTags(lf, ca));
|
return genreOverlaps(seedTags, await getGenreTags(lf, ca));
|
||||||
@@ -390,14 +393,18 @@ export async function pickAutoplayTrack(p, ctx, lastTrack) {
|
|||||||
return track;
|
return track;
|
||||||
};
|
};
|
||||||
|
|
||||||
if (seedVid) {
|
/* Check pre-resolved mix pools first */
|
||||||
const pooled = await takeFromPool(p, seedVid, genreOk);
|
const vidsToCheck = [seedVid, lastVid].filter(Boolean);
|
||||||
if (pooled) { p._autoplayPreferredPoolVid = seedVid; return pooled; }
|
for (const v of vidsToCheck) {
|
||||||
|
const pooled = await takeFromPool(p, v, genreOk);
|
||||||
|
if (pooled) { p._autoplayPreferredPoolVid = v; return pooled; }
|
||||||
}
|
}
|
||||||
|
|
||||||
const tryLastfmSimilar = async () => {
|
const tryLastfmSimilar = async () => {
|
||||||
const bases = [seed];
|
const bases = [seed];
|
||||||
if (lastWasPicked && lastTrack && artistOf(lastTrack) && !artistMatches(artistOf(lastTrack), seedArtist)) bases.push(lastTrack);
|
if (lastTrack && (artistOf(lastTrack) !== seedArtist || titleOf(lastTrack) !== seedName)) {
|
||||||
|
bases.push(lastTrack);
|
||||||
|
}
|
||||||
for (const base of bases) {
|
for (const base of bases) {
|
||||||
const bArtist = artistOf(base), bName = titleOf(base);
|
const bArtist = artistOf(base), bName = titleOf(base);
|
||||||
if (!bArtist || !bName) continue;
|
if (!bArtist || !bName) continue;
|
||||||
@@ -417,45 +424,71 @@ export async function pickAutoplayTrack(p, ctx, lastTrack) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const tryLastfmArtists = async () => {
|
const tryLastfmArtists = async () => {
|
||||||
if (!seedArtist) return null;
|
const artists = [seedArtist, artistOf(lastTrack)].filter(Boolean);
|
||||||
try {
|
for (const aName of artists) {
|
||||||
const similar = await lf.getSimilarArtists(seedArtist, 12);
|
try {
|
||||||
for (const a of shuffle(similar.filter(x => x.name)).slice(0, 4)) {
|
const similar = await lf.getSimilarArtists(aName, 12);
|
||||||
const track = await searchAccepted(
|
for (const a of shuffle(similar.filter(x => x.name)).slice(0, 4)) {
|
||||||
p, `${a.name} songs`,
|
const track = await searchAccepted(
|
||||||
async (t) => artistMatches(artistOf(t), a.name) && await genreOk(t),
|
p, `${a.name} songs`,
|
||||||
);
|
async (t) => artistMatches(artistOf(t), a.name) && await genreOk(t),
|
||||||
if (track) return track;
|
);
|
||||||
}
|
if (track) return track;
|
||||||
} catch (e) { logger.warn("[Autoplay] Last.fm similar-artists strategy failed:", e?.message); }
|
}
|
||||||
|
} catch (e) { logger.warn("[Autoplay] Last.fm similar-artists strategy failed:", e?.message); }
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const trySameArtist = async () => {
|
const trySameArtist = async () => {
|
||||||
if (!seedArtist) return null;
|
const artists = [seedArtist, artistOf(lastTrack)].filter(Boolean);
|
||||||
try {
|
for (const a of artists) {
|
||||||
return await searchAccepted(p, `${seedArtist} songs`, (t) => artistMatches(artistOf(t), seedArtist));
|
try {
|
||||||
} catch (e) { logger.warn("[Autoplay] Artist strategy failed:", e?.message); }
|
const track = await searchAccepted(p, `${a} songs`, (t) => artistMatches(artistOf(t), a));
|
||||||
|
if (track) return track;
|
||||||
|
const trackHits = await searchAccepted(p, `${a} top tracks`, (t) => artistMatches(artistOf(t), a));
|
||||||
|
if (trackHits) return trackHits;
|
||||||
|
} catch (e) { logger.warn("[Autoplay] Artist strategy failed:", e?.message); }
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const tryMix = async () => {
|
const tryMix = async () => {
|
||||||
if (!seedVid) return null;
|
for (const v of vidsToCheck) {
|
||||||
|
try {
|
||||||
|
const mixUrl = `https://www.youtube.com/watch?v=${v}&list=RD${v}`;
|
||||||
|
const candidates = await resolveCandidates(p, mixUrl, "yt");
|
||||||
|
if (candidates.length) {
|
||||||
|
storePool(p, v, candidates);
|
||||||
|
const track = await takeFromPool(p, v, genreOk);
|
||||||
|
if (track) { p._autoplayPreferredPoolVid = v; return track; }
|
||||||
|
}
|
||||||
|
} catch (e) { logger.warn("[Autoplay] Mix strategy failed:", e?.message); }
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* Robust safety net fallback so playback never dies */
|
||||||
|
const tryFallback = async () => {
|
||||||
try {
|
try {
|
||||||
const mixUrl = `https://www.youtube.com/watch?v=${seedVid}&list=RD${seedVid}`;
|
for (const v of vidsToCheck) {
|
||||||
const candidates = await resolveCandidates(p, mixUrl, "yt");
|
const pooled = await takeFromPool(p, v, null, true);
|
||||||
if (!candidates.length) return null;
|
if (pooled) return pooled;
|
||||||
storePool(p, seedVid, candidates);
|
}
|
||||||
const track = await takeFromPool(p, seedVid, genreOk);
|
const q = lastTrack ? `${artistOf(lastTrack) || seedArtist} radio` : `${seedArtist} music`;
|
||||||
if (track) p._autoplayPreferredPoolVid = seedVid;
|
const fallbackTrack = await searchAccepted(p, q, () => true, "ytm", true);
|
||||||
return track;
|
if (fallbackTrack) return fallbackTrack;
|
||||||
} catch (e) { logger.warn("[Autoplay] Mix strategy failed:", e?.message); }
|
const ytTrack = await searchAccepted(p, `${seedArtist || artistOf(lastTrack)} songs`, () => true, "yt", true);
|
||||||
|
if (ytTrack) return ytTrack;
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Autoplay] Fallback strategy failed:", e?.message);
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const order = lf
|
const order = lf
|
||||||
? [tryLastfmSimilar, tryLastfmArtists, trySameArtist, tryMix]
|
? [tryLastfmSimilar, tryLastfmArtists, trySameArtist, tryMix, tryFallback]
|
||||||
: [tryMix, trySameArtist];
|
: [tryMix, trySameArtist, tryFallback];
|
||||||
|
|
||||||
for (const strat of order) {
|
for (const strat of order) {
|
||||||
const track = await strat();
|
const track = await strat();
|
||||||
@@ -517,6 +550,7 @@ function buildQueueEndHandler(p, ctx) {
|
|||||||
p.addToQueue(track, false);
|
p.addToQueue(track, false);
|
||||||
logger.player(`[Autoplay] Queue ended — added and playing: ${track.title}`);
|
logger.player(`[Autoplay] Queue ended — added and playing: ${track.title}`);
|
||||||
if (!p.queue.getCurrent()) {
|
if (!p.queue.getCurrent()) {
|
||||||
|
p._playingNext = false;
|
||||||
p.playNext().catch(() => {});
|
p.playNext().catch(() => {});
|
||||||
}
|
}
|
||||||
} else if (!track && !p.queue?.getCurrent() && p.queue?.isEmpty() && !p._is247Enabled() && p._autoplay) {
|
} else if (!track && !p.queue?.getCurrent() && p.queue?.isEmpty() && !p._is247Enabled() && p._autoplay) {
|
||||||
@@ -585,6 +619,7 @@ export async function run(msg, data) {
|
|||||||
if (p._autoplay) {
|
if (p._autoplay) {
|
||||||
p._autoplayHistory = p._autoplayHistory ?? [];
|
p._autoplayHistory = p._autoplayHistory ?? [];
|
||||||
attachAutoplay(p, this);
|
attachAutoplay(p, this);
|
||||||
|
this.playerState?.saveSnapshot?.(p)?.catch?.(() => {});
|
||||||
|
|
||||||
if (!p.queue.getCurrent() && p.queue.isEmpty() && p._lastPlayedTrack) {
|
if (!p.queue.getCurrent() && p.queue.isEmpty() && p._lastPlayedTrack) {
|
||||||
p._autoplayHandler().catch(() => {});
|
p._autoplayHandler().catch(() => {});
|
||||||
@@ -600,6 +635,7 @@ export async function run(msg, data) {
|
|||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
} else {
|
} else {
|
||||||
detachAutoplay(p);
|
detachAutoplay(p);
|
||||||
|
this.playerState?.saveSnapshot?.(p)?.catch?.(() => {});
|
||||||
p._autoplayHistory = [];
|
p._autoplayHistory = [];
|
||||||
p._autoplayMixPools?.clear();
|
p._autoplayMixPools?.clear();
|
||||||
p._autoplayPreferredPoolVid = null;
|
p._autoplayPreferredPoolVid = null;
|
||||||
|
|||||||
@@ -0,0 +1,315 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/fav
|
||||||
|
* @description Bookmark personal favorite tracks and queue them across any server.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { Utils, cleanId } from "../src/utils/Utils.mjs";
|
||||||
|
import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs";
|
||||||
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
|
||||||
|
const PAGE_SIZE = 10;
|
||||||
|
const COLOR_PRIMARY = 0xe9196c;
|
||||||
|
const COLOR_SUCCESS = 0x2ecc71;
|
||||||
|
const COLOR_ERROR = 0xe74c3c;
|
||||||
|
|
||||||
|
/** @type {CommandBuilder} */
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("fav")
|
||||||
|
.setDescription("Bookmark your favorite tracks and load them into voice channels.", "commands.fav")
|
||||||
|
.addAliases("favorite", "favorites", "bookmark", "bookmarks")
|
||||||
|
.setCategory("music")
|
||||||
|
.addTextOption((o) =>
|
||||||
|
o
|
||||||
|
.setName("args")
|
||||||
|
.setDescription("Subcommand or track: play, list, remove, clear, or leave empty to toggle favorite.", "options.fav.args")
|
||||||
|
.setRequired(false)
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run handler for the fav command.
|
||||||
|
* @param {object} msg
|
||||||
|
* @param {object} [data]
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(msg, data) {
|
||||||
|
const pm = this.playlists;
|
||||||
|
if (!pm) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.notAvailable"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = cleanId(msg.author?.id ?? msg.message?.author?.id ?? msg.member?.user?.id ?? msg.user?.id);
|
||||||
|
const authorName = msg.author?.username ?? msg.message?.author?.username ?? "User";
|
||||||
|
const guildId = cleanId(getMessageGuildId(msg));
|
||||||
|
const prefix = this.handler.getPrefix(guildId) || "%";
|
||||||
|
const embedColor = getGlobalColor() || COLOR_PRIMARY;
|
||||||
|
|
||||||
|
/* Parse raw arguments for text-command dispatch */
|
||||||
|
const rawContent = (msg.message?.content || msg.content || "").trim();
|
||||||
|
const rawParts = rawContent.split(/\s+/).slice(1);
|
||||||
|
const firstToken = (rawParts[0] || "").toLowerCase();
|
||||||
|
|
||||||
|
let sub = data?.action || "";
|
||||||
|
if (!sub) {
|
||||||
|
if (["list", "view", "all"].includes(firstToken)) sub = "list";
|
||||||
|
else if (["play", "p", "queue"].includes(firstToken)) sub = "play";
|
||||||
|
else if (["remove", "delete", "rm", "del"].includes(firstToken)) sub = "remove";
|
||||||
|
else if (["clear", "reset"].includes(firstToken)) sub = "clear";
|
||||||
|
else if (["add", "save"].includes(firstToken)) sub = "add";
|
||||||
|
else if (firstToken && !isNaN(parseInt(firstToken, 10))) sub = "list";
|
||||||
|
else if (!firstToken) sub = "toggle";
|
||||||
|
else sub = "toggle";
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: PLAY
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "play" || sub === "p" || sub === "queue") {
|
||||||
|
const p = await this.getPlayer(msg, true, true, true);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
const favs = await pm.getFavorites(userId, 250, 0);
|
||||||
|
if (favs.length === 0) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.empty", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Check if a specific track number was requested */
|
||||||
|
let trackNum = null;
|
||||||
|
if (rawParts.length > 1) {
|
||||||
|
const parsedNum = parseInt(rawParts[1], 10);
|
||||||
|
if (!isNaN(parsedNum)) trackNum = parsedNum;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackNum != null) {
|
||||||
|
const idx = parseInt(trackNum, 10) - 1;
|
||||||
|
if (isNaN(idx) || idx < 0 || idx >= favs.length) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.invalidIndex", { max: favs.length }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const target = favs[idx];
|
||||||
|
const video = {
|
||||||
|
videoId: "",
|
||||||
|
encoded: "",
|
||||||
|
sourceName: target.source_name || "unknown",
|
||||||
|
isLive: false,
|
||||||
|
isStream: false,
|
||||||
|
title: target.title,
|
||||||
|
url: target.uri,
|
||||||
|
thumbnail: target.thumbnail || null,
|
||||||
|
spotifyUrl: null,
|
||||||
|
_durationMs: Number(target.duration_ms) || 0,
|
||||||
|
duration: {
|
||||||
|
timestamp: Utils.prettifyMS(Number(target.duration_ms) || 0),
|
||||||
|
seconds: Math.floor((Number(target.duration_ms) || 0) / 1000),
|
||||||
|
},
|
||||||
|
author: {
|
||||||
|
name: target.author || "Unknown",
|
||||||
|
url: target.uri || null,
|
||||||
|
},
|
||||||
|
artists: null,
|
||||||
|
requester: userId,
|
||||||
|
requesterName: authorName,
|
||||||
|
};
|
||||||
|
|
||||||
|
p.addToQueue(video, false);
|
||||||
|
if (!p.queue.getCurrent()) {
|
||||||
|
p.playNext().catch((e) => logger.error("[fav] playNext error:", e?.message));
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.queuedOne", {
|
||||||
|
title: target.title,
|
||||||
|
url: target.uri,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Queue all favorite tracks */
|
||||||
|
const videos = favs.map((f) => ({
|
||||||
|
videoId: "",
|
||||||
|
encoded: "",
|
||||||
|
sourceName: f.source_name || "unknown",
|
||||||
|
isLive: false,
|
||||||
|
isStream: false,
|
||||||
|
title: f.title,
|
||||||
|
url: f.uri,
|
||||||
|
thumbnail: f.thumbnail || null,
|
||||||
|
spotifyUrl: null,
|
||||||
|
_durationMs: Number(f.duration_ms) || 0,
|
||||||
|
duration: {
|
||||||
|
timestamp: Utils.prettifyMS(Number(f.duration_ms) || 0),
|
||||||
|
seconds: Math.floor((Number(f.duration_ms) || 0) / 1000),
|
||||||
|
},
|
||||||
|
author: {
|
||||||
|
name: f.author || "Unknown",
|
||||||
|
url: f.uri || null,
|
||||||
|
},
|
||||||
|
artists: null,
|
||||||
|
requester: userId,
|
||||||
|
requesterName: authorName,
|
||||||
|
}));
|
||||||
|
|
||||||
|
p.addManyToQueue(videos, false);
|
||||||
|
if (!p.queue.getCurrent()) {
|
||||||
|
p.playNext().catch((e) => logger.error("[fav] playNext error:", e?.message));
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.queuedAll", { count: videos.length }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: REMOVE
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "remove" || sub === "delete" || sub === "rm" || sub === "del") {
|
||||||
|
let target = null;
|
||||||
|
if (rawParts.length > 1) {
|
||||||
|
target = rawParts.slice(1).join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!target) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.removeUsage", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await pm.removeFavorite(userId, target);
|
||||||
|
if (!res.removed || !res.track) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.notFound"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.removed", {
|
||||||
|
title: res.track.title,
|
||||||
|
url: res.track.uri,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: CLEAR
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "clear" || sub === "reset") {
|
||||||
|
const count = await pm.clearFavorites(userId);
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.cleared", { count }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: LIST
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "list" || sub === "view" || sub === "all") {
|
||||||
|
const totalCount = await pm.getFavoriteCount(userId);
|
||||||
|
if (totalCount === 0) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.fav.listTitle", { user: authorName }) })
|
||||||
|
.setDescription(this.t(msg, "responses.fav.empty", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(totalCount / PAGE_SIZE));
|
||||||
|
let page = null;
|
||||||
|
if (rawParts.length > 1) {
|
||||||
|
const parsed = parseInt(rawParts[1], 10);
|
||||||
|
if (!isNaN(parsed)) page = parsed;
|
||||||
|
} else if (rawParts.length === 1 && !isNaN(parseInt(rawParts[0], 10))) {
|
||||||
|
page = parseInt(rawParts[0], 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
const safePage = Math.max(1, Math.min(parseInt(page, 10) || 1, totalPages));
|
||||||
|
const offset = (safePage - 1) * PAGE_SIZE;
|
||||||
|
|
||||||
|
const favs = await pm.getFavorites(userId, PAGE_SIZE, offset);
|
||||||
|
|
||||||
|
let desc = "";
|
||||||
|
favs.forEach((f, i) => {
|
||||||
|
const num = offset + i + 1;
|
||||||
|
const dur = Utils.prettifyMS(Number(f.duration_ms) || 0);
|
||||||
|
const authorText = f.author ? ` • ${f.author}` : "";
|
||||||
|
desc += `\`${num}.\` **[${f.title}](${f.uri})**${authorText} \`[${dur}]\`\n`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.fav.listTitle", { user: authorName }) })
|
||||||
|
.setDescription(desc || this.t(msg, "responses.fav.empty", { prefix }))
|
||||||
|
.setFooter({
|
||||||
|
text: this.t(msg, "responses.fav.listFooter", {
|
||||||
|
page: safePage,
|
||||||
|
totalPages,
|
||||||
|
total: totalCount,
|
||||||
|
prefix,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: TOGGLE / DEFAULT
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
const p = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = p?.queue?.getCurrent();
|
||||||
|
|
||||||
|
/* If no track is currently playing and user typed plain %fav, show the list */
|
||||||
|
if (!current) {
|
||||||
|
const totalCount = await pm.getFavoriteCount(userId);
|
||||||
|
if (totalCount === 0) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.empty", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
return run.call(this, msg, { action: "list" });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Toggle the currently playing track in favorites */
|
||||||
|
const toggleRes = await pm.toggleFavorite(userId, current);
|
||||||
|
|
||||||
|
if (toggleRes.action === "limit") {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.limitReached", { max: 250 }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (toggleRes.action === "added") {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.added", {
|
||||||
|
title: current.title,
|
||||||
|
url: current.url || current.uri,
|
||||||
|
count: toggleRes.count,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_PRIMARY)
|
||||||
|
.setDescription(this.t(msg, "responses.fav.removed", {
|
||||||
|
title: current.title,
|
||||||
|
url: current.url || current.uri,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/mywrapped
|
||||||
|
* @description View personal listening recap, personal top songs, favorite artist, and server DJ rank.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { GuildStats } from "../src/music/GuildStats.mjs";
|
||||||
|
import { cleanId, Utils } from "../src/utils/Utils.mjs";
|
||||||
|
import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
|
/** @type {CommandBuilder} */
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("mywrapped")
|
||||||
|
.setDescription("View your personal music listening recap, top tracks, and server DJ rank.", "commands.mywrapped")
|
||||||
|
.addAliases("myrecap", "personalwrapped", "mytracks", "me", "djstats")
|
||||||
|
.setCategory("music")
|
||||||
|
.addTextOption((o) =>
|
||||||
|
o
|
||||||
|
.setName("target")
|
||||||
|
.setDescription("The user whose listening recap you want to view.", "options.mywrapped.user")
|
||||||
|
.setRequired(false)
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run handler for the mywrapped command.
|
||||||
|
* @param {object} message
|
||||||
|
* @param {object} [data]
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message, data) {
|
||||||
|
const guildId = cleanId(getMessageGuildId(message));
|
||||||
|
const prefix = this.handler.getPrefix(guildId) || "%";
|
||||||
|
|
||||||
|
const rawAuthor = message.message?.author ?? message.author;
|
||||||
|
const authorId = cleanId(rawAuthor?.id ?? message.authorId ?? message.message?.authorId ?? "");
|
||||||
|
|
||||||
|
const rawArg = (
|
||||||
|
data?.get?.("target")?.value ??
|
||||||
|
(message.message?.content || message.content || "")
|
||||||
|
.trim()
|
||||||
|
.split(/\s+/)
|
||||||
|
.slice(1)
|
||||||
|
.join(" ") ??
|
||||||
|
""
|
||||||
|
).trim();
|
||||||
|
|
||||||
|
let targetId = authorId;
|
||||||
|
let targetUser = rawAuthor;
|
||||||
|
|
||||||
|
const mentionMatch = rawArg.match(/<@!?(\d+)>/) || rawArg.match(/\b\d{17,20}\b/);
|
||||||
|
if (mentionMatch && mentionMatch[1]) {
|
||||||
|
const parsedId = cleanId(mentionMatch[1]);
|
||||||
|
if (parsedId && parsedId !== authorId) {
|
||||||
|
targetId = parsedId;
|
||||||
|
const resolved = this.client?.users?.resolve?.(targetId) ?? message.message?.guild?.members?.resolve?.(targetId)?.user;
|
||||||
|
if (resolved) {
|
||||||
|
targetUser = resolved;
|
||||||
|
} else {
|
||||||
|
targetUser = { id: targetId, username: `<@${targetId}>` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const isSelf = targetId === authorId;
|
||||||
|
const username = targetUser?.username ?? (isSelf ? "You" : `<@${targetId}>`);
|
||||||
|
|
||||||
|
let stats = await GuildStats.getUserStats(guildId, targetId);
|
||||||
|
let isGlobalFallback = false;
|
||||||
|
|
||||||
|
if (!stats) {
|
||||||
|
stats = await GuildStats.getUserStats("global", targetId);
|
||||||
|
if (stats) {
|
||||||
|
isGlobalFallback = true;
|
||||||
|
}
|
||||||
|
} else if (stats.isGlobalFallback) {
|
||||||
|
isGlobalFallback = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!stats || stats.totalTracks === 0) {
|
||||||
|
const noDataText = isSelf
|
||||||
|
? this.t(message, "responses.mywrapped.noDataSelf", { prefix })
|
||||||
|
: this.t(message, "responses.mywrapped.noDataOther", { username, prefix });
|
||||||
|
|
||||||
|
const emptyEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({
|
||||||
|
name: isSelf
|
||||||
|
? `🎧 ${this.t(message, "responses.mywrapped.authorSelf")}`
|
||||||
|
: `🎧 ${this.t(message, "responses.mywrapped.authorOther", { username })}`,
|
||||||
|
})
|
||||||
|
.setTitle(isSelf
|
||||||
|
? this.t(message, "responses.mywrapped.titleSelf")
|
||||||
|
: this.t(message, "responses.mywrapped.titleOther", { username }))
|
||||||
|
.setDescription(noDataText)
|
||||||
|
.setFooter({ text: this.t(message, "responses.mywrapped.footer", { prefix }) });
|
||||||
|
|
||||||
|
return message.reply({ embeds: [emptyEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const playsLabel = this.t(message, "responses.top.plays");
|
||||||
|
const medals = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣"];
|
||||||
|
|
||||||
|
let topSongsText = "";
|
||||||
|
if (stats.topTracks && stats.topTracks.length > 0) {
|
||||||
|
topSongsText = stats.topTracks
|
||||||
|
.map((t, i) => `${medals[i] || "•"} **${Utils.truncate(t.title, 35)}** — *${Utils.truncate(t.artist, 25)}* (\`${t.count} ${playsLabel}\`)`)
|
||||||
|
.join("\n");
|
||||||
|
} else {
|
||||||
|
topSongsText = "_No track history recorded yet._";
|
||||||
|
}
|
||||||
|
|
||||||
|
const djRankValue = this.t(message, "responses.mywrapped.djRankValue", {
|
||||||
|
rank: stats.djRank,
|
||||||
|
total: stats.totalDjs,
|
||||||
|
});
|
||||||
|
|
||||||
|
const fields = [
|
||||||
|
{
|
||||||
|
name: `⏱️ ${this.t(message, "responses.mywrapped.totalStreamed")}`,
|
||||||
|
value: `**${stats.totalHours}** hours`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `🎵 ${this.t(message, "responses.mywrapped.tracksQueued")}`,
|
||||||
|
value: `**${stats.totalTracks.toLocaleString()}** tracks`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `⏰ ${this.t(message, "responses.mywrapped.peakHour")}`,
|
||||||
|
value: `**${stats.peakHour}**`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `👑 ${this.t(message, "responses.mywrapped.djRank")}`,
|
||||||
|
value: `**${djRankValue}**`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
if (stats.topArtist) {
|
||||||
|
fields.push({
|
||||||
|
name: `⭐ ${this.t(message, "responses.mywrapped.topArtist")}`,
|
||||||
|
value: `**${stats.topArtist.name}** (\`${stats.topArtist.count} ${playsLabel}\`)`,
|
||||||
|
inline: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fields.push({
|
||||||
|
name: `🏆 ${this.t(message, "responses.mywrapped.topSongs")}`,
|
||||||
|
value: topSongsText,
|
||||||
|
inline: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
let footerText = this.t(message, "responses.mywrapped.footer", { prefix });
|
||||||
|
if (isGlobalFallback) {
|
||||||
|
footerText = `${this.t(message, "responses.mywrapped.globalNotice")} • ${footerText}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({
|
||||||
|
name: isSelf
|
||||||
|
? `🎧 ${this.t(message, "responses.mywrapped.authorSelf")}`
|
||||||
|
: `🎧 ${this.t(message, "responses.mywrapped.authorOther", { username })}`,
|
||||||
|
})
|
||||||
|
.setTitle(isSelf
|
||||||
|
? this.t(message, "responses.mywrapped.titleSelf")
|
||||||
|
: this.t(message, "responses.mywrapped.titleOther", { username }))
|
||||||
|
.addFields(...fields)
|
||||||
|
.setFooter({ text: footerText });
|
||||||
|
|
||||||
|
const avatarUrl = typeof targetUser?.avatarURL === "function"
|
||||||
|
? targetUser.avatarURL()
|
||||||
|
: (targetUser?.avatar ? `https://cdn.discordapp.com/avatars/${targetId}/${targetUser.avatar}.png` : null);
|
||||||
|
|
||||||
|
if (avatarUrl) {
|
||||||
|
embed.setThumbnail(avatarUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
+41
-3
@@ -12,6 +12,11 @@ import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mj
|
|||||||
import { playLastFmCategory } from "./lastfm.mjs";
|
import { playLastFmCategory } from "./lastfm.mjs";
|
||||||
import { parseLastFmUrl, isLastFmUrl } from "../src/services/lastfm/LastFmManager.mjs";
|
import { parseLastFmUrl, isLastFmUrl } from "../src/services/lastfm/LastFmManager.mjs";
|
||||||
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||||
|
import {
|
||||||
|
getPlayableAttachment,
|
||||||
|
isFluxerAttachmentUrl,
|
||||||
|
extractMediaTitle,
|
||||||
|
} from "../src/utils/AttachmentUtils.mjs";
|
||||||
|
|
||||||
const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
|
const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
|
||||||
|
|
||||||
@@ -102,7 +107,7 @@ const KNOWN_SERVICE_HOSTS = /(?:youtu(?:be\.com|\.be)|youtube\.com|music\.youtub
|
|||||||
const NATIVE_AUDIO_EXTENSIONS = /\.(?:opus|webm|ogg)(?:\?|$)/i;
|
const NATIVE_AUDIO_EXTENSIONS = /\.(?:opus|webm|ogg)(?:\?|$)/i;
|
||||||
|
|
||||||
/** Audio file extensions that indicate any direct audio URL (broader set). */
|
/** Audio file extensions that indicate any direct audio URL (broader set). */
|
||||||
const AUDIO_EXTENSIONS = /\.(?:mp3|m4a|aac|ogg|opus|flac|wav|wma|webm|stream|m3u8|pls)(?:\?|$)/i;
|
const AUDIO_EXTENSIONS = /\.(?:mp3|m4a|aac|ogg|opus|flac|wav|wma|webm|mp4|mkv|mov|stream|m3u8|pls)(?:\?|$)/i;
|
||||||
|
|
||||||
/** Common stream/radio content-type paths or patterns. */
|
/** Common stream/radio content-type paths or patterns. */
|
||||||
const STREAM_PATH_HINTS = /\/(?:stream|live|radio|audio|playlist|play|listen|mp3|aac|ogg)/i;
|
const STREAM_PATH_HINTS = /\/(?:stream|live|radio|audio|playlist|play|listen|mp3|aac|ogg)/i;
|
||||||
@@ -139,6 +144,7 @@ function isDirectAudioUrl(str) {
|
|||||||
try {
|
try {
|
||||||
const url = new URL(trimmed);
|
const url = new URL(trimmed);
|
||||||
if (KNOWN_SERVICE_HOSTS.test(url.hostname)) return false;
|
if (KNOWN_SERVICE_HOSTS.test(url.hostname)) return false;
|
||||||
|
if (isFluxerAttachmentUrl(trimmed)) return true;
|
||||||
if (AUDIO_EXTENSIONS.test(url.pathname)) return true;
|
if (AUDIO_EXTENSIONS.test(url.pathname)) return true;
|
||||||
if (STREAM_PATH_HINTS.test(url.pathname) && !url.pathname.includes(".html") && !url.pathname.includes(".php")) {
|
if (STREAM_PATH_HINTS.test(url.pathname) && !url.pathname.includes(".html") && !url.pathname.includes(".php")) {
|
||||||
return true;
|
return true;
|
||||||
@@ -185,7 +191,7 @@ export const command = new CommandBuilder()
|
|||||||
.addTextOption(option =>
|
.addTextOption(option =>
|
||||||
option.setName("query")
|
option.setName("query")
|
||||||
.setDescription("A search query, music genre (for example `pop`), URL, or provider-prefixed query like `sp: song name`.", "options.play.query")
|
.setDescription("A search query, music genre (for example `pop`), URL, or provider-prefixed query like `sp: song name`.", "options.play.query")
|
||||||
.setRequired(true)
|
.setRequired(false)
|
||||||
)
|
)
|
||||||
.addChoiceOption(o =>
|
.addChoiceOption(o =>
|
||||||
o.setName("provider")
|
o.setName("provider")
|
||||||
@@ -229,7 +235,39 @@ function forwardPlayMessage(d, statusMsg, message) {
|
|||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const rawQuery = data.get("query").value;
|
const attachment = getPlayableAttachment(message);
|
||||||
|
const rawQuery = data.get("query")?.value?.trim() || "";
|
||||||
|
|
||||||
|
/* Handle case where neither a query nor an attachment was supplied */
|
||||||
|
if (!rawQuery && !attachment) {
|
||||||
|
const noQueryEmbed = new EmbedBuilder()
|
||||||
|
.setColor(ERROR_COLOR)
|
||||||
|
.setAuthor({ name: this.t(message, "responses.play.noQueryTitle") })
|
||||||
|
.setDescription(this.t(message, "responses.play.noQueryDesc"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.play.noQueryFooter") });
|
||||||
|
return message.reply({ embeds: [noQueryEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Handle direct Fluxer user attachment or fluxerusercontent.com URL */
|
||||||
|
const isAttachment = Boolean(attachment) || isFluxerAttachmentUrl(rawQuery);
|
||||||
|
if (isAttachment) {
|
||||||
|
const mediaUrl = attachment ? attachment.url : rawQuery;
|
||||||
|
const cleanTitle = attachment ? extractMediaTitle(attachment.filename) : extractMediaTitle(rawQuery);
|
||||||
|
const p = await this.getPlayer(message, true, true, true);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
const statusEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.play.streamPipelineAuthor") })
|
||||||
|
.setDescription(this.t(message, "responses.play.loadingAttachmentStream"));
|
||||||
|
let statusMsg = null;
|
||||||
|
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
||||||
|
|
||||||
|
const messages = p.playExternal(mediaUrl, cleanTitle, "Fluxer Attachment", false, "attachment");
|
||||||
|
messages.on("message", d => forwardPlayMessage(d, statusMsg, message));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const flagProvider = data.get("provider")?.value;
|
const flagProvider = data.get("provider")?.value;
|
||||||
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
|
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
|
||||||
const provider = inlineProvider ?? flagProvider ?? "ytm";
|
const provider = inlineProvider ?? flagProvider ?? "ytm";
|
||||||
|
|||||||
@@ -7,7 +7,6 @@
|
|||||||
|
|
||||||
import { Utils } from "../../src/utils/Utils.mjs";
|
import { Utils } from "../../src/utils/Utils.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../../src/ui/index.mjs";
|
|
||||||
import { STATES, PROGRESS } from "./consts.mjs";
|
import { STATES, PROGRESS } from "./consts.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -30,7 +29,7 @@ export function buildPlayerEmbed(bot, msg, player, timeout, state = {}) {
|
|||||||
if (current?.duration && player.startedPlaying) {
|
if (current?.duration && player.startedPlaying) {
|
||||||
const elapsed = Date.now() - player.startedPlaying;
|
const elapsed = Date.now() - player.startedPlaying;
|
||||||
const totalMs = typeof current.duration === "object"
|
const totalMs = typeof current.duration === "object"
|
||||||
? (current.duration.seconds ?? 0) * 1000
|
? (current.duration?.seconds ?? 0) * 1000
|
||||||
: current.duration;
|
: current.duration;
|
||||||
|
|
||||||
const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled);
|
const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled);
|
||||||
|
|||||||
@@ -0,0 +1,654 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/playlist
|
||||||
|
* @description Save the active queue or import playlists from YouTube, Spotify, SoundCloud, Apple Music and more.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { Utils, cleanId } from "../src/utils/Utils.mjs";
|
||||||
|
import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs";
|
||||||
|
import { MAX_PLAYLISTS_PER_USER, MAX_TRACKS_PER_PLAYLIST } from "../src/services/PlaylistManager.mjs";
|
||||||
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
|
||||||
|
const PAGE_SIZE = 10;
|
||||||
|
const COLOR_PRIMARY = 0xe9196c;
|
||||||
|
const COLOR_SUCCESS = 0x2ecc71;
|
||||||
|
const COLOR_ERROR = 0xe74c3c;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format raw source identifiers into friendly labels.
|
||||||
|
* @param {string} raw
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function formatSourceName(raw) {
|
||||||
|
const s = String(raw || "").toLowerCase();
|
||||||
|
if (s.includes("spotify")) return "Spotify";
|
||||||
|
if (s.includes("youtube") || s.includes("yt")) return "YouTube";
|
||||||
|
if (s.includes("soundcloud")) return "SoundCloud";
|
||||||
|
if (s.includes("apple") || s.includes("applemusic")) return "Apple Music";
|
||||||
|
if (s.includes("deezer")) return "Deezer";
|
||||||
|
if (s.includes("tidal")) return "Tidal";
|
||||||
|
if (s.includes("bandcamp")) return "Bandcamp";
|
||||||
|
return "External Source";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve tracks from an external URL (YouTube, Spotify, SoundCloud, Apple Music, Deezer, etc.) via Lavalink.
|
||||||
|
* @param {object} bot - The bot instance.
|
||||||
|
* @param {string} url - The URL to resolve.
|
||||||
|
* @returns {Promise<{name: string|null, tracks: Array<object>, source: string}>}
|
||||||
|
*/
|
||||||
|
async function resolveExternalPlaylist(bot, url) {
|
||||||
|
if (!bot.lavalink) return { name: null, tracks: [], source: "unknown" };
|
||||||
|
await bot.lavalink.waitForNode({ timeoutMs: 10_000 }).catch(() => {});
|
||||||
|
|
||||||
|
const cleanUrl = url.trim();
|
||||||
|
|
||||||
|
/* Canonicalize YouTube playlist queries if needed */
|
||||||
|
let searchQuery = cleanUrl;
|
||||||
|
const ytId = Utils.extractYouTubeId(cleanUrl);
|
||||||
|
const canonicalYt = ytId ? Utils.normalizeYouTubeUrl(cleanUrl) : null;
|
||||||
|
if (ytId && canonicalYt) {
|
||||||
|
try {
|
||||||
|
const listId = new URL(cleanUrl).searchParams.get("list");
|
||||||
|
if (listId) searchQuery = canonicalYt + "&list=" + listId;
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = null;
|
||||||
|
try {
|
||||||
|
result = await bot.lavalink.search(searchQuery);
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[playlist] External resolve failed:", err?.message);
|
||||||
|
return { name: null, tracks: [], source: "unknown" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawTracks = result?.tracks || [];
|
||||||
|
if (rawTracks.length === 0) {
|
||||||
|
return { name: null, tracks: [], source: "unknown" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const playlistName = result?.playlistInfo?.name ?? result?.info?.name ?? null;
|
||||||
|
const allRawTracks = [...rawTracks];
|
||||||
|
|
||||||
|
/* Support LavaSrc / NodeLink pagination for large external playlists */
|
||||||
|
let nextPageToken = result?.pluginInfo?.nextPageToken ?? result?.playlistInfo?.nextPageToken;
|
||||||
|
let page = 1;
|
||||||
|
const maxPages = 6;
|
||||||
|
while (nextPageToken && page < maxPages && allRawTracks.length < MAX_TRACKS_PER_PLAYLIST) {
|
||||||
|
try {
|
||||||
|
page++;
|
||||||
|
const nextResult = await bot.lavalink.search(searchQuery, {
|
||||||
|
page,
|
||||||
|
pageToken: nextPageToken,
|
||||||
|
});
|
||||||
|
const nextTracks = nextResult?.tracks || [];
|
||||||
|
if (nextTracks.length === 0) break;
|
||||||
|
allRawTracks.push(...nextTracks);
|
||||||
|
nextPageToken = nextResult?.pluginInfo?.nextPageToken ?? nextResult?.playlistInfo?.nextPageToken;
|
||||||
|
} catch (_) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const tracks = allRawTracks.slice(0, MAX_TRACKS_PER_PLAYLIST).map(t => {
|
||||||
|
const info = t.info ?? t ?? {};
|
||||||
|
let ms = info.length ?? t.length ?? info.durationMs ?? 0;
|
||||||
|
let trackUri = info.uri ?? ("https://www.youtube.com/watch?v=" + (info.identifier || ""));
|
||||||
|
if (typeof trackUri === "string" && trackUri.includes("music.youtube.com")) {
|
||||||
|
trackUri = trackUri.replace("music.youtube.com", "www.youtube.com");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
title: Utils.cleanTitle(info.title ?? "Unknown"),
|
||||||
|
author: info.author ?? "Unknown",
|
||||||
|
uri: trackUri,
|
||||||
|
durationMs: ms,
|
||||||
|
sourceName: info.sourceName ?? "unknown",
|
||||||
|
thumbnail: info.artworkUrl ?? null,
|
||||||
|
};
|
||||||
|
}).filter(t => t.uri.length > 0);
|
||||||
|
|
||||||
|
const detectedSource = tracks[0]?.sourceName || "external";
|
||||||
|
return { name: playlistName, tracks, source: detectedSource };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @type {CommandBuilder} */
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("playlist")
|
||||||
|
.setDescription("Save the current queue or import playlists from YouTube, Spotify, SoundCloud, Apple Music and more.", "commands.playlist")
|
||||||
|
.addAliases("pl", "playlists")
|
||||||
|
.setCategory("music")
|
||||||
|
.addTextOption((o) =>
|
||||||
|
o
|
||||||
|
.setName("args")
|
||||||
|
.setDescription("Subcommand and arguments: save, play, list, show, add, remove, delete.", "options.playlist.args")
|
||||||
|
.setRequired(false)
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run handler for the playlist command.
|
||||||
|
* @param {object} msg
|
||||||
|
* @param {object} [data]
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(msg, data) {
|
||||||
|
const pm = this.playlists;
|
||||||
|
if (!pm) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.notAvailable"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = cleanId(msg.author?.id ?? msg.message?.author?.id ?? msg.member?.user?.id ?? msg.user?.id);
|
||||||
|
const authorName = msg.author?.username ?? msg.message?.author?.username ?? "User";
|
||||||
|
const guildId = cleanId(getMessageGuildId(msg));
|
||||||
|
const prefix = this.handler.getPrefix(guildId) || "%";
|
||||||
|
const embedColor = getGlobalColor() || COLOR_PRIMARY;
|
||||||
|
|
||||||
|
/* Parse raw text tokens for fallback CLI syntax */
|
||||||
|
const rawContent = (msg.message?.content || msg.content || "").trim();
|
||||||
|
const rawParts = rawContent.split(/\s+/).slice(1);
|
||||||
|
const firstToken = (rawParts[0] || "").toLowerCase();
|
||||||
|
|
||||||
|
let sub = data?.action || "";
|
||||||
|
if (!sub) {
|
||||||
|
if (["save", "create", "new", "import"].includes(firstToken)) sub = "save";
|
||||||
|
else if (["play", "p", "load"].includes(firstToken)) sub = "play";
|
||||||
|
else if (["list", "all"].includes(firstToken)) sub = "list";
|
||||||
|
else if (["show", "view", "info"].includes(firstToken)) sub = "show";
|
||||||
|
else if (["add"].includes(firstToken)) sub = "add";
|
||||||
|
else if (["remove", "rm"].includes(firstToken)) sub = "remove";
|
||||||
|
else if (["delete", "del", "destroy"].includes(firstToken)) sub = "delete";
|
||||||
|
else if (rawParts.length > 0 && !["list", "play"].includes(firstToken)) {
|
||||||
|
/* If user typed %playlist <name>, interpret as play */
|
||||||
|
sub = "play";
|
||||||
|
} else {
|
||||||
|
sub = "list";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: SAVE / IMPORT
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "save" || sub === "create" || sub === "new" || sub === "import") {
|
||||||
|
let name = null;
|
||||||
|
let url = null;
|
||||||
|
|
||||||
|
/* Scan arguments to distinguish custom playlist name and optional source URL */
|
||||||
|
for (let i = 1; i < rawParts.length; i++) {
|
||||||
|
const part = rawParts[i];
|
||||||
|
if (Utils.isValidUrl(part)) {
|
||||||
|
url = part;
|
||||||
|
} else if (!name) {
|
||||||
|
name = part;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Case A: URL provided — import tracks from YouTube, Spotify, SoundCloud, Apple Music, etc. */
|
||||||
|
if (url) {
|
||||||
|
const sourceLabel = formatSourceName(url);
|
||||||
|
const loadingEmbed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.resolving", { source: sourceLabel }));
|
||||||
|
|
||||||
|
let statusMsg = null;
|
||||||
|
try {
|
||||||
|
statusMsg = await msg.reply({ embeds: [loadingEmbed] });
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
const resolved = await resolveExternalPlaylist(this, url);
|
||||||
|
if (resolved.tracks.length === 0) {
|
||||||
|
const errorEmbed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.noTracksFromSource"));
|
||||||
|
if (statusMsg) return statusMsg.edit({ embeds: [errorEmbed] });
|
||||||
|
return msg.reply({ embeds: [errorEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fallback to external playlist name if no custom name was given */
|
||||||
|
if (!name) {
|
||||||
|
name = resolved.name ? resolved.name.replace(/[^a-zA-Z0-9_\-\s]/g, "").slice(0, 32).trim() : null;
|
||||||
|
}
|
||||||
|
if (!name) name = `${sourceLabel.toLowerCase()}-import`;
|
||||||
|
|
||||||
|
const res = await pm.savePlaylist(userId, name, resolved.tracks);
|
||||||
|
if (!res.success) {
|
||||||
|
let errKey = "responses.playlist.saveFailed";
|
||||||
|
if (res.error === "LIMIT_REACHED") errKey = "responses.playlist.limitReached";
|
||||||
|
else if (res.error === "INVALID_NAME") errKey = "responses.playlist.invalidName";
|
||||||
|
|
||||||
|
const failEmbed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, errKey, { max: MAX_PLAYLISTS_PER_USER }));
|
||||||
|
if (statusMsg) return statusMsg.edit({ embeds: [failEmbed] });
|
||||||
|
return msg.reply({ embeds: [failEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const displaySource = formatSourceName(resolved.source);
|
||||||
|
const successEmbed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.savedFromSource", {
|
||||||
|
name: res.name,
|
||||||
|
count: res.count,
|
||||||
|
source: displaySource,
|
||||||
|
prefix,
|
||||||
|
}));
|
||||||
|
|
||||||
|
if (statusMsg) return statusMsg.edit({ embeds: [successEmbed] });
|
||||||
|
return msg.reply({ embeds: [successEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Case B: No URL — save tracks from the active queue */
|
||||||
|
if (!name && rawParts.length > 1) {
|
||||||
|
name = rawParts[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.saveUsage", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const p = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = p?.queue?.getCurrent();
|
||||||
|
const queued = p?.queue?.data || [];
|
||||||
|
|
||||||
|
const allTracks = [];
|
||||||
|
if (current) allTracks.push(current);
|
||||||
|
if (queued.length > 0) allTracks.push(...queued);
|
||||||
|
|
||||||
|
if (allTracks.length === 0) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.emptyQueue", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await pm.savePlaylist(userId, name, allTracks);
|
||||||
|
if (!res.success) {
|
||||||
|
if (res.error === "LIMIT_REACHED") {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.limitReached", { max: MAX_PLAYLISTS_PER_USER }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
if (res.error === "INVALID_NAME") {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.invalidName"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.saveFailed"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.saved", {
|
||||||
|
name: res.name,
|
||||||
|
count: res.count,
|
||||||
|
prefix,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: PLAY
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "play" || sub === "p" || sub === "load") {
|
||||||
|
let name = null;
|
||||||
|
if (rawParts.length > 1) {
|
||||||
|
name = rawParts[1];
|
||||||
|
} else if (rawParts.length === 1 && !["play", "list", "p", "load"].includes(firstToken)) {
|
||||||
|
name = rawParts[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.playUsage", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const playlist = await pm.getPlaylist(userId, name);
|
||||||
|
if (!playlist) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!playlist.tracks || playlist.tracks.length === 0) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.playlistEmpty", { name }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const p = await this.getPlayer(msg, true, true, true);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
const videos = playlist.tracks.map((t) => ({
|
||||||
|
videoId: "",
|
||||||
|
encoded: "",
|
||||||
|
sourceName: t.sourceName || "unknown",
|
||||||
|
isLive: false,
|
||||||
|
isStream: false,
|
||||||
|
title: t.title,
|
||||||
|
url: t.uri,
|
||||||
|
thumbnail: t.thumbnail || null,
|
||||||
|
spotifyUrl: null,
|
||||||
|
_durationMs: Number(t.durationMs) || 0,
|
||||||
|
duration: {
|
||||||
|
timestamp: Utils.prettifyMS(Number(t.durationMs) || 0),
|
||||||
|
seconds: Math.floor((Number(t.durationMs) || 0) / 1000),
|
||||||
|
},
|
||||||
|
author: {
|
||||||
|
name: t.author || "Unknown",
|
||||||
|
url: t.uri || null,
|
||||||
|
},
|
||||||
|
artists: null,
|
||||||
|
requester: userId,
|
||||||
|
requesterName: authorName,
|
||||||
|
}));
|
||||||
|
|
||||||
|
p.addManyToQueue(videos, false);
|
||||||
|
if (!p.queue.getCurrent()) {
|
||||||
|
p.playNext().catch((e) => logger.error("[playlist] playNext error:", e?.message));
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.queued", {
|
||||||
|
name: playlist.name,
|
||||||
|
count: videos.length,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: LIST
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "list" || sub === "all") {
|
||||||
|
const playlists = await pm.listPlaylists(userId);
|
||||||
|
if (playlists.length === 0) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.playlist.listTitle", { user: authorName }) })
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.noPlaylists", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(playlists.length / PAGE_SIZE));
|
||||||
|
let page = null;
|
||||||
|
if (rawParts.length > 1) {
|
||||||
|
const parsed = parseInt(rawParts[1], 10);
|
||||||
|
if (!isNaN(parsed)) page = parsed;
|
||||||
|
}
|
||||||
|
const safePage = Math.max(1, Math.min(parseInt(page, 10) || 1, totalPages));
|
||||||
|
const offset = (safePage - 1) * PAGE_SIZE;
|
||||||
|
|
||||||
|
const slice = playlists.slice(offset, offset + PAGE_SIZE);
|
||||||
|
|
||||||
|
let desc = "";
|
||||||
|
slice.forEach((pl, i) => {
|
||||||
|
const num = offset + i + 1;
|
||||||
|
desc += `\`${num}.\` **${pl.name}** — \`${pl.trackCount} tracks\`\n`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.playlist.listTitle", { user: authorName }) })
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({
|
||||||
|
text: this.t(msg, "responses.playlist.listFooter", {
|
||||||
|
page: safePage,
|
||||||
|
totalPages,
|
||||||
|
total: playlists.length,
|
||||||
|
max: MAX_PLAYLISTS_PER_USER,
|
||||||
|
prefix,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: SHOW / VIEW
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "show" || sub === "view" || sub === "info") {
|
||||||
|
let name = rawParts.length > 1 ? rawParts[1] : null;
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.showUsage", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const playlist = await pm.getPlaylist(userId, name);
|
||||||
|
if (!playlist) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const tracks = playlist.tracks || [];
|
||||||
|
if (tracks.length === 0) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.playlistEmpty", { name: playlist.name }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(tracks.length / PAGE_SIZE));
|
||||||
|
let page = null;
|
||||||
|
if (rawParts.length > 2) {
|
||||||
|
const parsed = parseInt(rawParts[2], 10);
|
||||||
|
if (!isNaN(parsed)) page = parsed;
|
||||||
|
}
|
||||||
|
const safePage = Math.max(1, Math.min(parseInt(page, 10) || 1, totalPages));
|
||||||
|
const offset = (safePage - 1) * PAGE_SIZE;
|
||||||
|
|
||||||
|
const slice = tracks.slice(offset, offset + PAGE_SIZE);
|
||||||
|
|
||||||
|
let desc = "";
|
||||||
|
slice.forEach((t, i) => {
|
||||||
|
const num = offset + i + 1;
|
||||||
|
const dur = Utils.prettifyMS(Number(t.durationMs) || 0);
|
||||||
|
const authorText = t.author ? ` • ${t.author}` : "";
|
||||||
|
desc += `\`${num}.\` **[${t.title}](${t.uri})**${authorText} \`[${dur}]\`\n`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.playlist.showTitle", { name: playlist.name }) })
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({
|
||||||
|
text: this.t(msg, "responses.playlist.showFooter", {
|
||||||
|
page: safePage,
|
||||||
|
totalPages,
|
||||||
|
total: tracks.length,
|
||||||
|
name: playlist.name,
|
||||||
|
prefix,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: ADD
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "add") {
|
||||||
|
let name = null;
|
||||||
|
let url = null;
|
||||||
|
|
||||||
|
/* Scan arguments for playlist name and optional URL */
|
||||||
|
for (let i = 1; i < rawParts.length; i++) {
|
||||||
|
const part = rawParts[i];
|
||||||
|
if (Utils.isValidUrl(part)) {
|
||||||
|
url = part;
|
||||||
|
} else if (!name) {
|
||||||
|
name = part;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.addUsage", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Case A: Adding from URL (Spotify, YouTube, SoundCloud, Apple Music) */
|
||||||
|
if (url) {
|
||||||
|
const resolved = await resolveExternalPlaylist(this, url);
|
||||||
|
if (resolved.tracks.length === 0) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.noTracksFromSource"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await pm.addTracksToPlaylist(userId, name, resolved.tracks);
|
||||||
|
if (!res.success) {
|
||||||
|
if (res.error === "NOT_FOUND") {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
if (res.error === "PLAYLIST_FULL") {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.playlistFull", { max: MAX_TRACKS_PER_PLAYLIST }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.addFailed"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.tracksAdded", {
|
||||||
|
name: res.name,
|
||||||
|
addedCount: res.addedCount,
|
||||||
|
count: res.count,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Case B: Adding currently playing track */
|
||||||
|
const p = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = p?.queue?.getCurrent();
|
||||||
|
|
||||||
|
if (!current) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.nothingPlaying"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await pm.addToPlaylist(userId, name, current);
|
||||||
|
if (!res.success) {
|
||||||
|
if (res.error === "NOT_FOUND") {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
if (res.error === "PLAYLIST_FULL") {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.playlistFull", { max: MAX_TRACKS_PER_PLAYLIST }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.addFailed"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.trackAdded", {
|
||||||
|
title: current.title,
|
||||||
|
name: res.name,
|
||||||
|
count: res.count,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: REMOVE
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "remove" || sub === "rm") {
|
||||||
|
let name = rawParts.length > 1 ? rawParts[1] : null;
|
||||||
|
let index = rawParts.length > 2 ? parseInt(rawParts[2], 10) : null;
|
||||||
|
|
||||||
|
if (!name || index == null || isNaN(index)) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.removeUsage", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await pm.removeFromPlaylist(userId, name, index);
|
||||||
|
if (!res.success) {
|
||||||
|
if (res.error === "NOT_FOUND") {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.invalidIndex"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.trackRemoved", {
|
||||||
|
title: res.removedTrack?.title || "Track",
|
||||||
|
name: res.name,
|
||||||
|
count: res.count,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -------------------------------------------------------------------------
|
||||||
|
SUBCOMMAND: DELETE
|
||||||
|
------------------------------------------------------------------------- */
|
||||||
|
if (sub === "delete" || sub === "del" || sub === "destroy") {
|
||||||
|
let name = rawParts.length > 1 ? rawParts[1] : null;
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.deleteUsage", { prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleted = await pm.deletePlaylist(userId, name);
|
||||||
|
if (!deleted) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_ERROR)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.notFound", { name, prefix }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(COLOR_SUCCESS)
|
||||||
|
.setDescription(this.t(msg, "responses.playlist.deleted", { name }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
}
|
||||||
+49
-2
@@ -8,6 +8,12 @@ import { CommandBuilder } from "../src/commands/index.mjs";
|
|||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs";
|
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||||
|
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||||
|
import {
|
||||||
|
getPlayableAttachment,
|
||||||
|
isFluxerAttachmentUrl,
|
||||||
|
extractMediaTitle,
|
||||||
|
} from "../src/utils/AttachmentUtils.mjs";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -27,7 +33,7 @@ export const command = new CommandBuilder()
|
|||||||
.addTextOption(option =>
|
.addTextOption(option =>
|
||||||
option.setName("query")
|
option.setName("query")
|
||||||
.setDescription("A search query, URL, or provider-prefixed query like `sp: song name`.", "options.playnext.query")
|
.setDescription("A search query, URL, or provider-prefixed query like `sp: song name`.", "options.playnext.query")
|
||||||
.setRequired(true)
|
.setRequired(false)
|
||||||
)
|
)
|
||||||
.addChoiceOption(o =>
|
.addChoiceOption(o =>
|
||||||
o.setName("provider")
|
o.setName("provider")
|
||||||
@@ -50,7 +56,48 @@ export async function run(message, data) {
|
|||||||
const p = await this.getPlayer(message, true, true, true);
|
const p = await this.getPlayer(message, true, true, true);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
|
|
||||||
const rawQuery = data.get("query").value;
|
const attachment = getPlayableAttachment(message);
|
||||||
|
const rawQuery = data.get("query")?.value?.trim() || "";
|
||||||
|
|
||||||
|
/* Handle case where neither a query nor an attachment was supplied */
|
||||||
|
if (!rawQuery && !attachment) {
|
||||||
|
const noQueryEmbed = new EmbedBuilder()
|
||||||
|
.setColor(ERROR_COLOR)
|
||||||
|
.setAuthor({ name: this.t(message, "responses.play.noQueryTitle") })
|
||||||
|
.setDescription(this.t(message, "responses.play.noQueryDesc"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.play.noQueryFooter") });
|
||||||
|
return message.reply({ embeds: [noQueryEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Handle direct Fluxer user attachment or fluxerusercontent.com URL */
|
||||||
|
const isAttachment = Boolean(attachment) || isFluxerAttachmentUrl(rawQuery);
|
||||||
|
if (isAttachment) {
|
||||||
|
const mediaUrl = attachment ? attachment.url : rawQuery;
|
||||||
|
const cleanTitle = attachment ? extractMediaTitle(attachment.filename) : extractMediaTitle(rawQuery);
|
||||||
|
|
||||||
|
const statusEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.playnext.playingNext") })
|
||||||
|
.setDescription(this.t(message, "responses.play.loadingAttachmentStream"));
|
||||||
|
let statusMsg = null;
|
||||||
|
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch (_) {}
|
||||||
|
|
||||||
|
const messages = p.playExternal(mediaUrl, cleanTitle, "Fluxer Attachment", true, "attachment");
|
||||||
|
messages.on("message", d => {
|
||||||
|
let embed;
|
||||||
|
if (d instanceof EmbedBuilder) {
|
||||||
|
embed = d;
|
||||||
|
} else if (d?.embeds?.[0]) {
|
||||||
|
embed = d.embeds[0];
|
||||||
|
} else {
|
||||||
|
embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(String(d));
|
||||||
|
}
|
||||||
|
embed.setAuthor({ name: this.t(message, "responses.playnext.playingNext") });
|
||||||
|
if (statusMsg) statusMsg.edit({ embeds: [embed] }).catch(() => {});
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const flagProvider = data.get("provider")?.value;
|
const flagProvider = data.get("provider")?.value;
|
||||||
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
|
const { provider: inlineProvider, query } = parseInlineProvider(rawQuery);
|
||||||
const provider = inlineProvider ?? flagProvider ?? "ytm";
|
const provider = inlineProvider ?? flagProvider ?? "ytm";
|
||||||
|
|||||||
@@ -12,9 +12,10 @@ import { logger } from "../src/core/Logger.mjs";
|
|||||||
/** @type {CommandBuilder} @description Command definition for the servers command (owner-only). */
|
/** @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 communities the bot is in")
|
||||||
.setRequirement(r => r.setOwnerOnly(true))
|
.setRequirement(r => r.setOwnerOnly(true))
|
||||||
.setCategory("util");
|
.setCategory("util")
|
||||||
|
.addAliases("communities");
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -9,7 +9,6 @@
|
|||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getMessageGuildId, getGlobalColor } from "../src/ui/index.mjs";
|
import { getMessageGuildId, getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { logger } from "../src/core/Logger.mjs";
|
|
||||||
import {
|
import {
|
||||||
SHORTCUTS, BOOL_SETTINGS, VALID_LOCALES, setValidLocales,
|
SHORTCUTS, BOOL_SETTINGS, VALID_LOCALES, setValidLocales,
|
||||||
VOLUME_MIN, VOLUME_MAX,
|
VOLUME_MIN, VOLUME_MAX,
|
||||||
@@ -201,9 +200,10 @@ export async function run(message, data) {
|
|||||||
const d = set.getAll();
|
const d = set.getAll();
|
||||||
const guildName = getGuildName(message);
|
const guildName = getGuildName(message);
|
||||||
const rawGuild = message.message?.guild;
|
const rawGuild = message.message?.guild;
|
||||||
const iconUrl = rawGuild?.icon
|
const iconUrl = rawGuild?.iconURL?.()
|
||||||
? "https://cdn.fluxer.app/icons/" + rawGuild.id + "/" + rawGuild.icon + ".webp"
|
?? (rawGuild?.icon
|
||||||
: null;
|
? "https://fluxerusercontent.com/icons/" + rawGuild.id + "/" + rawGuild.icon + ".webp"
|
||||||
|
: null);
|
||||||
|
|
||||||
const channels = get247Channels(set);
|
const channels = get247Channels(set);
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/statustest
|
||||||
|
* @description Owner-only diagnostic command to test the public status channel,
|
||||||
|
* force-refresh the live health card, and simulate subsystem incidents / resolutions.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
|
/** @type {CommandBuilder} @description Command definition for statustest (owner-only). */
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("statustest")
|
||||||
|
.setDescription("Test public status channel updates, live cards, and incidents.", "commands.statustest")
|
||||||
|
.setCategory("util")
|
||||||
|
.setRequirement(r => r.setOwnerOnly(true));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* Run handler for the statustest command.
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(msg) {
|
||||||
|
const statusMgr = this.statusChannel;
|
||||||
|
if (!statusMgr || !statusMgr.enabled || !statusMgr.channelId) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.statustest.disabledAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.statustest.disabledTitle"))
|
||||||
|
.setDescription(this.t(msg, "responses.statustest.disabledDesc"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const prefix = this.commands?.getPrefix?.(msg.message?.guildId) || "%";
|
||||||
|
const args = (msg.args || []).map(a => String(a).trim().toLowerCase());
|
||||||
|
const subCommand = args[0] || "help";
|
||||||
|
|
||||||
|
if (subCommand === "refresh") {
|
||||||
|
await statusMgr.updateLiveCard();
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0x2ecc71)
|
||||||
|
.setTitle(this.t(msg, "responses.statustest.refreshedTitle"))
|
||||||
|
.setDescription(this.t(msg, "responses.statustest.refreshedDesc", {
|
||||||
|
channelId: statusMgr.channelId,
|
||||||
|
messageId: statusMgr.liveMessageId || "New",
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (subCommand === "incident") {
|
||||||
|
const target = args[1] || "gateway";
|
||||||
|
const customReason = msg.args.slice(2).join(" ") || "Manual test incident triggered by bot owner.";
|
||||||
|
await statusMgr.triggerIncident(target, customReason);
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe74c3c)
|
||||||
|
.setTitle(this.t(msg, "responses.statustest.incidentTitle"))
|
||||||
|
.setDescription(this.t(msg, "responses.statustest.incidentDesc", {
|
||||||
|
target,
|
||||||
|
channelId: statusMgr.channelId,
|
||||||
|
prefix,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (subCommand === "resolve") {
|
||||||
|
const target = args[1] || "gateway";
|
||||||
|
const customNote = msg.args.slice(2).join(" ") || "Manual test resolution confirmed stable.";
|
||||||
|
await statusMgr.resolveIncident(target, customNote);
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0x2ecc71)
|
||||||
|
.setTitle(this.t(msg, "responses.statustest.resolvedTitle"))
|
||||||
|
.setDescription(this.t(msg, "responses.statustest.resolvedDesc", {
|
||||||
|
target,
|
||||||
|
channelId: statusMgr.channelId,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Default Help */
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.statustest.author") })
|
||||||
|
.setTitle(this.t(msg, "responses.statustest.helpTitle"))
|
||||||
|
.setDescription(this.t(msg, "responses.statustest.helpDesc", {
|
||||||
|
channelId: statusMgr.channelId,
|
||||||
|
cardId: statusMgr.liveMessageId || "Not yet created",
|
||||||
|
prefix,
|
||||||
|
}));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/top
|
||||||
|
* @description Display the most played tracks and top artists for the server or global network with pagination.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { GuildStats } from "../src/music/GuildStats.mjs";
|
||||||
|
import { cleanId, Utils } from "../src/utils/Utils.mjs";
|
||||||
|
import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs";
|
||||||
|
import { run as runMyWrapped } from "./mywrapped.mjs";
|
||||||
|
|
||||||
|
const PAGE_SIZE = 10;
|
||||||
|
const MAX_TRACKS = 50;
|
||||||
|
const SESSION_MS = 60 * 1000;
|
||||||
|
|
||||||
|
/** @type {CommandBuilder} */
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("top")
|
||||||
|
.setDescription("View the most played songs and top artists in this server.", "commands.top")
|
||||||
|
.addAliases("leaderboard", "chart", "toptracks")
|
||||||
|
.setCategory("music")
|
||||||
|
.addTextOption((o) =>
|
||||||
|
o
|
||||||
|
.setName("timeframe")
|
||||||
|
.setDescription("Filter timeframe: 24h, week, month, year, all, or global, or page number.", "options.top.timeframe")
|
||||||
|
.setRequired(false)
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run handler for the top command.
|
||||||
|
* @param {object} message
|
||||||
|
* @param {object} [data]
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message, data) {
|
||||||
|
const guildId = cleanId(getMessageGuildId(message));
|
||||||
|
const prefix = this.handler.getPrefix(guildId) || "%";
|
||||||
|
|
||||||
|
const rawArg = (
|
||||||
|
data?.get?.("timeframe")?.value ??
|
||||||
|
(message.message?.content || message.content || "")
|
||||||
|
.trim()
|
||||||
|
.split(/\s+/)
|
||||||
|
.slice(1)
|
||||||
|
.join(" ") ??
|
||||||
|
""
|
||||||
|
).trim().toLowerCase();
|
||||||
|
|
||||||
|
const tokens = rawArg.split(/\s+/).filter(Boolean);
|
||||||
|
|
||||||
|
if (tokens.includes("me") || tokens.includes("self") || tokens.includes("my")) {
|
||||||
|
return runMyWrapped.call(this, message, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
let isGlobal = false;
|
||||||
|
let timeframe = "month";
|
||||||
|
let explicitTimeframe = false;
|
||||||
|
let targetPage = 1;
|
||||||
|
|
||||||
|
for (const token of tokens) {
|
||||||
|
const num = parseInt(token, 10);
|
||||||
|
if (!isNaN(num) && num > 0) {
|
||||||
|
targetPage = num;
|
||||||
|
} else if (token === "global" || token === "network") {
|
||||||
|
isGlobal = true;
|
||||||
|
timeframe = "global";
|
||||||
|
explicitTimeframe = true;
|
||||||
|
} else if (token === "day" || token === "today" || token === "24h" || token === "d" || token === "1d") {
|
||||||
|
timeframe = "day";
|
||||||
|
explicitTimeframe = true;
|
||||||
|
} else if (token === "week" || token === "w" || token === "7d") {
|
||||||
|
timeframe = "week";
|
||||||
|
explicitTimeframe = true;
|
||||||
|
} else if (token === "month" || token === "m" || token === "30d") {
|
||||||
|
timeframe = "month";
|
||||||
|
explicitTimeframe = true;
|
||||||
|
} else if (token === "year" || token === "y" || token === "1y" || token === "365d") {
|
||||||
|
timeframe = "year";
|
||||||
|
explicitTimeframe = true;
|
||||||
|
} else if (token === "all" || token === "alltime" || token === "total") {
|
||||||
|
timeframe = "all";
|
||||||
|
explicitTimeframe = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let tracks = [];
|
||||||
|
let topArtist = null;
|
||||||
|
|
||||||
|
if (isGlobal) {
|
||||||
|
const res = await GuildStats.getGlobalTopTracks(MAX_TRACKS);
|
||||||
|
tracks = res.tracks || [];
|
||||||
|
topArtist = res.topArtist;
|
||||||
|
} else if (explicitTimeframe) {
|
||||||
|
const res = await GuildStats.getTopTracks(guildId, timeframe, MAX_TRACKS);
|
||||||
|
tracks = res.tracks || [];
|
||||||
|
topArtist = res.topArtist;
|
||||||
|
} else {
|
||||||
|
/* If no explicit timeframe passed, cascade: day -> week -> month -> year -> all */
|
||||||
|
const tfList = ["day", "week", "month", "year", "all"];
|
||||||
|
for (const tf of tfList) {
|
||||||
|
const res = await GuildStats.getTopTracks(guildId, tf, MAX_TRACKS);
|
||||||
|
if (res?.tracks && res.tracks.length > 0) {
|
||||||
|
tracks = res.tracks;
|
||||||
|
topArtist = res.topArtist;
|
||||||
|
timeframe = tf;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let fallbackGlobal = false;
|
||||||
|
if ((!tracks || tracks.length === 0) && !isGlobal && !explicitTimeframe) {
|
||||||
|
const globalRes = await GuildStats.getGlobalTopTracks(MAX_TRACKS);
|
||||||
|
if (globalRes?.tracks && globalRes.tracks.length > 0) {
|
||||||
|
tracks = globalRes.tracks;
|
||||||
|
topArtist = globalRes.topArtist;
|
||||||
|
fallbackGlobal = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const authorName = (isGlobal || fallbackGlobal)
|
||||||
|
? `🌐 ${this.t(message, "responses.top.globalAuthor")}`
|
||||||
|
: `🏆 ${this.t(message, "responses.top.topAuthor")}`;
|
||||||
|
|
||||||
|
const getTimeframeLabel = (tf) => {
|
||||||
|
if (isGlobal || fallbackGlobal) return "Global";
|
||||||
|
if (tf === "day") return this.t(message, "responses.top.timeframeDay");
|
||||||
|
if (tf === "week") return this.t(message, "responses.top.timeframeWeek");
|
||||||
|
if (tf === "month") return this.t(message, "responses.top.timeframeMonth");
|
||||||
|
if (tf === "year") return this.t(message, "responses.top.timeframeYear");
|
||||||
|
return this.t(message, "responses.top.timeframeAll");
|
||||||
|
};
|
||||||
|
|
||||||
|
const timeframeLabel = getTimeframeLabel(timeframe);
|
||||||
|
|
||||||
|
const titleName = (isGlobal || fallbackGlobal)
|
||||||
|
? this.t(message, "responses.top.globalTitle")
|
||||||
|
: this.t(message, "responses.top.topTitle", { timeframe: timeframeLabel });
|
||||||
|
|
||||||
|
const baseFooter = (isGlobal || fallbackGlobal)
|
||||||
|
? this.t(message, "responses.top.globalFooter", { prefix })
|
||||||
|
: this.t(message, "responses.top.topFooter", { prefix });
|
||||||
|
|
||||||
|
if (!tracks || tracks.length === 0) {
|
||||||
|
const emptyEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: authorName })
|
||||||
|
.setTitle(titleName)
|
||||||
|
.setDescription(this.t(message, "responses.top.noData", { prefix }))
|
||||||
|
.setFooter({ text: baseFooter });
|
||||||
|
return message.reply({ embeds: [emptyEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalPages = Math.max(1, Math.ceil(tracks.length / PAGE_SIZE));
|
||||||
|
let currentPage = Math.max(1, Math.min(targetPage, totalPages));
|
||||||
|
|
||||||
|
const medals = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"];
|
||||||
|
const playsLabel = this.t(message, "responses.top.plays");
|
||||||
|
|
||||||
|
const buildEmbed = (page, expired = false) => {
|
||||||
|
const safePage = Math.max(1, Math.min(page, totalPages));
|
||||||
|
const startIdx = (safePage - 1) * PAGE_SIZE;
|
||||||
|
const pageTracks = tracks.slice(startIdx, startIdx + PAGE_SIZE);
|
||||||
|
|
||||||
|
const lines = pageTracks.map((t, idx) => {
|
||||||
|
const rank = startIdx + idx + 1;
|
||||||
|
const rankBadge = rank <= 10 ? medals[rank - 1] : `\`#${rank}\``;
|
||||||
|
const cleanTitle = Utils.truncate(t.title, 40);
|
||||||
|
const cleanArtist = Utils.truncate(t.artist, 30);
|
||||||
|
return `${rankBadge} **${cleanTitle}**\n ↳ *${cleanArtist}* • \`${t.count} ${playsLabel}\``;
|
||||||
|
});
|
||||||
|
|
||||||
|
let desc = lines.join("\n\n");
|
||||||
|
if (fallbackGlobal && safePage === 1) {
|
||||||
|
const note = this.t(message, "responses.top.serverFallbackNote");
|
||||||
|
if (note) {
|
||||||
|
desc = `${note}\n\n${desc}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (topArtist && safePage === 1) {
|
||||||
|
desc += `\n\n⭐ **Top Artist:** **${topArtist.name}** (\`${topArtist.count} ${playsLabel}\`)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
let footerText = totalPages > 1
|
||||||
|
? `${this.t(message, "responses.top.pageFooter", { page: safePage, totalPages, timeframe: timeframeLabel })} • ${baseFooter}`
|
||||||
|
: baseFooter;
|
||||||
|
|
||||||
|
if (expired) {
|
||||||
|
const closedLabel = this.handler?.locale?.translate(guildId, "pagination.embed.sclosedTitle") || "Session Closed";
|
||||||
|
footerText += ` • ${closedLabel}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: authorName })
|
||||||
|
.setTitle(titleName)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: footerText });
|
||||||
|
};
|
||||||
|
|
||||||
|
const msg = await message.reply({ embeds: [buildEmbed(currentPage)] });
|
||||||
|
if (!msg || totalPages <= 1) return;
|
||||||
|
|
||||||
|
const rawMsg = msg.message ?? msg;
|
||||||
|
if (!rawMsg?.react) return;
|
||||||
|
|
||||||
|
const emojis = ["⬅️", "➡️"];
|
||||||
|
for (const emoji of emojis) {
|
||||||
|
await rawMsg.react(emoji).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearReactions = async () => {
|
||||||
|
try {
|
||||||
|
await rawMsg.removeAllReactions();
|
||||||
|
} catch {
|
||||||
|
for (const emoji of emojis) {
|
||||||
|
await rawMsg.removeReaction(emoji).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let timer = null;
|
||||||
|
const resetTimer = () => {
|
||||||
|
if (timer) clearTimeout(timer);
|
||||||
|
timer = setTimeout(async () => {
|
||||||
|
if (typeof unobserve === "function") unobserve();
|
||||||
|
await clearReactions().catch(() => {});
|
||||||
|
msg.edit({ embeds: [buildEmbed(currentPage, true)] }).catch(() => {});
|
||||||
|
}, SESSION_MS);
|
||||||
|
};
|
||||||
|
|
||||||
|
const unobserve = msg.onReaction(emojis, async (e) => {
|
||||||
|
resetTimer();
|
||||||
|
const emoji = e.emoji_id;
|
||||||
|
if (emoji === "⬅️") {
|
||||||
|
currentPage = currentPage <= 1 ? totalPages : currentPage - 1;
|
||||||
|
} else if (emoji === "➡️") {
|
||||||
|
currentPage = currentPage >= totalPages ? 1 : currentPage + 1;
|
||||||
|
}
|
||||||
|
msg.edit({ embeds: [buildEmbed(currentPage)] }).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
resetTimer();
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/wrapped
|
||||||
|
* @description Generate community music recap and statistics for the server or global network.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { GuildStats } from "../src/music/GuildStats.mjs";
|
||||||
|
import { cleanId, Utils } from "../src/utils/Utils.mjs";
|
||||||
|
import { getGlobalColor, getMessageGuildId } from "../src/ui/index.mjs";
|
||||||
|
import { run as runMyWrapped } from "./mywrapped.mjs";
|
||||||
|
|
||||||
|
/** @type {CommandBuilder} */
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("wrapped")
|
||||||
|
.setDescription("Generate a community music recap and listening statistics.", "commands.wrapped")
|
||||||
|
.addAliases("recap", "summary")
|
||||||
|
.setCategory("music")
|
||||||
|
.addTextOption((o) =>
|
||||||
|
o
|
||||||
|
.setName("scope")
|
||||||
|
.setDescription("Recap scope: server or global.", "options.wrapped.scope")
|
||||||
|
.setRequired(false)
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run handler for the wrapped command.
|
||||||
|
* @param {object} message
|
||||||
|
* @param {object} [data]
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message, data) {
|
||||||
|
const guildId = cleanId(getMessageGuildId(message));
|
||||||
|
const prefix = this.handler.getPrefix(guildId) || "%";
|
||||||
|
|
||||||
|
const rawArg = (
|
||||||
|
data?.get?.("scope")?.value ??
|
||||||
|
(message.message?.content || message.content || "").split(/\s+/)[1] ??
|
||||||
|
""
|
||||||
|
).trim().toLowerCase();
|
||||||
|
|
||||||
|
if (rawArg === "me" || rawArg === "self" || rawArg === "user") {
|
||||||
|
return runMyWrapped.call(this, message, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isGlobal = rawArg === "global" || rawArg === "all" || rawArg === "network";
|
||||||
|
|
||||||
|
if (isGlobal) {
|
||||||
|
const serverCount = this.client?.guilds?.size ?? 1300;
|
||||||
|
const stats = await GuildStats.getGlobalWrapped(serverCount);
|
||||||
|
|
||||||
|
if (!stats) {
|
||||||
|
const emptyEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: `🌐 ${this.t(message, "responses.wrapped.globalAuthor")}` })
|
||||||
|
.setTitle(this.t(message, "responses.wrapped.globalTitle"))
|
||||||
|
.setDescription(this.t(message, "responses.top.noData", { prefix }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.wrapped.globalFooter", { prefix }) });
|
||||||
|
return message.reply({ embeds: [emptyEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const playsLabel = this.t(message, "responses.top.plays");
|
||||||
|
const medals = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣"];
|
||||||
|
|
||||||
|
let topSongsText = "";
|
||||||
|
if (stats.topTracks && stats.topTracks.length > 0) {
|
||||||
|
topSongsText = stats.topTracks
|
||||||
|
.map((t, i) => `${medals[i] || "•"} **${Utils.truncate(t.title, 35)}** — *${Utils.truncate(t.artist, 25)}* (\`${t.count} ${playsLabel}\`)`)
|
||||||
|
.join("\n");
|
||||||
|
} else {
|
||||||
|
topSongsText = "_No track history recorded yet._";
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: `🌐 ${this.t(message, "responses.wrapped.globalAuthor")}` })
|
||||||
|
.setTitle(this.t(message, "responses.wrapped.globalTitle"))
|
||||||
|
.addFields(
|
||||||
|
{
|
||||||
|
name: `⏱️ ${this.t(message, "responses.wrapped.totalStreamed")}`,
|
||||||
|
value: `**${stats.totalHours}** hours`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `🎵 ${this.t(message, "responses.wrapped.tracksQueued")}`,
|
||||||
|
value: `**${stats.totalTracks.toLocaleString()}** tracks`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `⏰ ${this.t(message, "responses.wrapped.peakHour")}`,
|
||||||
|
value: `**${stats.peakHour}**`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `🌍 ${this.t(message, "responses.wrapped.activeServers")}`,
|
||||||
|
value: `**${stats.totalGuilds.toLocaleString()}** servers`,
|
||||||
|
inline: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `🏆 ${this.t(message, "responses.wrapped.topSongs")}`,
|
||||||
|
value: topSongsText,
|
||||||
|
inline: false,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.setFooter({ text: this.t(message, "responses.wrapped.globalFooter", { prefix }) });
|
||||||
|
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const stats = await GuildStats.getWrapped(guildId);
|
||||||
|
|
||||||
|
if (!stats) {
|
||||||
|
const emptyEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: `🎧 ${this.t(message, "responses.wrapped.wrappedAuthor")}` })
|
||||||
|
.setTitle(this.t(message, "responses.wrapped.wrappedTitle"))
|
||||||
|
.setDescription(this.t(message, "responses.top.noData", { prefix }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.wrapped.wrappedFooter", { prefix }) });
|
||||||
|
return message.reply({ embeds: [emptyEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const playsLabel = this.t(message, "responses.top.plays");
|
||||||
|
const medals = ["🥇", "🥈", "🥉", "4️⃣", "5️⃣"];
|
||||||
|
|
||||||
|
let topSongsText = "";
|
||||||
|
if (stats.topTracks && stats.topTracks.length > 0) {
|
||||||
|
topSongsText = stats.topTracks
|
||||||
|
.map((t, i) => `${medals[i] || "•"} **${Utils.truncate(t.title, 35)}** — *${Utils.truncate(t.artist, 25)}* (\`${t.count} ${playsLabel}\`)`)
|
||||||
|
.join("\n");
|
||||||
|
} else {
|
||||||
|
topSongsText = "_No track history recorded yet._";
|
||||||
|
}
|
||||||
|
|
||||||
|
const djMention = stats.topUserId ? `<@${stats.topUserId}> (\`${stats.topUserPlays} ${playsLabel}\`)` : "N/A";
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: `🎧 ${this.t(message, "responses.wrapped.wrappedAuthor")}` })
|
||||||
|
.setTitle(this.t(message, "responses.wrapped.wrappedTitle"))
|
||||||
|
.addFields(
|
||||||
|
{
|
||||||
|
name: `⏱️ ${this.t(message, "responses.wrapped.totalStreamed")}`,
|
||||||
|
value: `**${stats.totalHours}** hours`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `🎵 ${this.t(message, "responses.wrapped.tracksQueued")}`,
|
||||||
|
value: `**${stats.totalTracks.toLocaleString()}** tracks`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `⏰ ${this.t(message, "responses.wrapped.peakHour")}`,
|
||||||
|
value: `**${stats.peakHour}**`,
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `👑 ${this.t(message, "responses.wrapped.topDJ")}`,
|
||||||
|
value: djMention,
|
||||||
|
inline: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `🏆 ${this.t(message, "responses.wrapped.topSongs")}`,
|
||||||
|
value: topSongsText,
|
||||||
|
inline: false,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.setFooter({ text: this.t(message, "responses.wrapped.wrappedFooter", { prefix }) });
|
||||||
|
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
+18
-2
@@ -2,10 +2,10 @@
|
|||||||
"Comment": "Fluxer music bot configuration. Requires Node.js >= 22.13.0. 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",
|
||||||
"instanceUrl": null,
|
"instanceUrl": null,
|
||||||
"instanceUrl-Comment": "Optional base URL of a self-hosted Fluxer instance (e.g. 'https://chat.example.com'). Leave null or omit to connect to the official fluxer.app.",
|
"instanceUrl-Comment": "Optional base API URL of a self-hosted Fluxer instance (e.g. 'https://chat.example.com/api'). Include '/api' if your instance serves REST endpoints under /api. Leave null or omit to connect to official fluxer.com.",
|
||||||
"fluxer.js": {
|
"fluxer.js": {
|
||||||
"rest": {
|
"rest": {
|
||||||
"Comment": "REST client options. 'timeout' is ms before a request to api.fluxer.app is aborted (default: 15000). Raise if you see DOMException AbortError in logs.",
|
"Comment": "REST client options. 'timeout' is ms before a request to fluxer.com/api is aborted (default: 15000). Raise if you see DOMException AbortError in logs.",
|
||||||
"timeout": 30000,
|
"timeout": 30000,
|
||||||
"retries": 3
|
"retries": 3
|
||||||
}
|
}
|
||||||
@@ -20,6 +20,15 @@
|
|||||||
"maxQueue": 40,
|
"maxQueue": 40,
|
||||||
"Comment": "Forward error logs and crash reports to a Fluxer channel. Every logger.error line (and every logger.warn line when forwardWarn=true) is posted there: player failures, node disconnects, database errors, plus fatal crash reports (uncaughtException, unhandledRejection) with uptime and memory. startupMessage=true sends a one-time 'Log channel connected' confirmation at boot through the real send path — if it fails, the console shows the exact permission/ID problem. forwardInfo=true ALSO forwards logger.info lines (boot activity, joins, recoveries) — useful for full visibility but much noisier; keep false for errors-only. Identical messages are deduplicated for 60s, sends are spaced by minIntervalMs, and floods beyond maxQueue pending messages are dropped with a summary line instead of spamming. Test delivery any time with the owner-only 'logtest' command. channelId: enable Developer Mode in the Fluxer app, right-click the target channel and copy its ID — the bot must be able to send messages there. Fully disabled unless enabled=true AND channelId is set."
|
"Comment": "Forward error logs and crash reports to a Fluxer channel. Every logger.error line (and every logger.warn line when forwardWarn=true) is posted there: player failures, node disconnects, database errors, plus fatal crash reports (uncaughtException, unhandledRejection) with uptime and memory. startupMessage=true sends a one-time 'Log channel connected' confirmation at boot through the real send path — if it fails, the console shows the exact permission/ID problem. forwardInfo=true ALSO forwards logger.info lines (boot activity, joins, recoveries) — useful for full visibility but much noisier; keep false for errors-only. Identical messages are deduplicated for 60s, sends are spaced by minIntervalMs, and floods beyond maxQueue pending messages are dropped with a summary line instead of spamming. Test delivery any time with the owner-only 'logtest' command. channelId: enable Developer Mode in the Fluxer app, right-click the target channel and copy its ID — the bot must be able to send messages there. Fully disabled unless enabled=true AND channelId is set."
|
||||||
},
|
},
|
||||||
|
"statusChannel": {
|
||||||
|
"enabled": false,
|
||||||
|
"channelId": "paste the ID of the public channel for live bot status and incident alerts",
|
||||||
|
"mentionRoleId": "",
|
||||||
|
"liveMessageId": null,
|
||||||
|
"updateIntervalSeconds": 300,
|
||||||
|
"statusPageUrl": "https://status.remix.bot",
|
||||||
|
"Comment": "Public-facing system status & incident reporting. Maintains a self-updating live health card (RAM bar, CPU %, Uptime, Ping, active players and subsystem status) and sends dual-color incident lifecycle embeds (🔴 Outage with Investigating status / ✅ Resolved with exact downtime duration) when subsystems experience disruptions. channelId: target Fluxer channel ID. mentionRoleId: optional role snowflake to mention on outages (e.g. @Status). updateIntervalSeconds: frequency in seconds to edit the live status card (default: 300 / 5 minutes). liveMessageId: set automatically by the bot or paste an existing message ID. Test with the owner-only 'statustest' command."
|
||||||
|
},
|
||||||
"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.",
|
||||||
@@ -101,6 +110,13 @@
|
|||||||
"connectionLimit": 15,
|
"connectionLimit": 15,
|
||||||
"connectionLimit-Comment": "Maximum simultaneous MySQL connections shared across all bot services (default: 15). Prevents connection pool exhaustion in multi-shard deployments."
|
"connectionLimit-Comment": "Maximum simultaneous MySQL connections shared across all bot services (default: 15). Prevents connection pool exhaustion in multi-shard deployments."
|
||||||
},
|
},
|
||||||
|
"redis": {
|
||||||
|
"enabled": false,
|
||||||
|
"url": "redis://127.0.0.1:6379",
|
||||||
|
"password": null,
|
||||||
|
"searchTtlSeconds": 86400,
|
||||||
|
"Comment": "Centralized Redis service for ultra-fast track search caching (<1ms repeat lookups), 24/7 session restoration across bot reboots, and cross-shard atomic playback statistics. If disabled or omitted, searches fall back to direct Lavalink/NodeLink queries and sessions fall back to MySQL."
|
||||||
|
},
|
||||||
"dashboard": {
|
"dashboard": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"redis": {
|
"redis": {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"token": "YOUR_BOT_TOKEN_HERE",
|
"token": "YOUR_BOT_TOKEN_HERE",
|
||||||
|
"instanceUrl": null,
|
||||||
"prefix": "%",
|
"prefix": "%",
|
||||||
"embedColor": "0xe9196c",
|
"embedColor": "0xe9196c",
|
||||||
"owners": [],
|
"owners": [],
|
||||||
|
|||||||
@@ -62,7 +62,7 @@ services:
|
|||||||
- remix-net
|
- remix-net
|
||||||
|
|
||||||
nodelink:
|
nodelink:
|
||||||
image: ghcr.io/performanc/nodelink:latest
|
image: ghcr.io/performanc/nodelink:dev
|
||||||
container_name: remix-nodelink
|
container_name: remix-nodelink
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
|
|||||||
@@ -128,10 +128,16 @@ manager.on("error", (err) => {
|
|||||||
logger.error("[Sharding] Manager error:", err?.message ?? err);
|
logger.error("[Sharding] Manager error:", err?.message ?? err);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Event loop health heartbeat for Docker container healthcheck (Issue #12)
|
/* Event loop health heartbeat for Docker container healthcheck (Issue #12) */
|
||||||
const healthFile = path.join(os.tmpdir(), ".remix-health");
|
const healthFile = path.join(os.tmpdir(), ".remix-health");
|
||||||
const updateHealth = () => {
|
const updateHealth = () => {
|
||||||
try {
|
try {
|
||||||
|
/* Only touch healthFile during supervisor boot before child shards are spawned.
|
||||||
|
* Once child processes exist, Bot.mjs in the child controls the heartbeat based on gateway health. */
|
||||||
|
if (manager.shards && manager.shards.size > 0) {
|
||||||
|
const anyAlive = [...manager.shards.values()].some(s => s.process && !s.process.killed);
|
||||||
|
if (anyAlive) return;
|
||||||
|
}
|
||||||
fs.writeFile(healthFile, Date.now().toString(), () => {});
|
fs.writeFile(healthFile, Date.now().toString(), () => {});
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -143,7 +143,7 @@ export class CommandHandler extends EventEmitter {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
const guildId = msg.guildId ?? msg.guild?.id ?? msg.channel?.guildId ?? msg.channel?.channel?.guildId ?? msg.message?.guildId ?? null;
|
||||||
const prefix = this.getPrefix(guildId);
|
const prefix = this.getPrefix(guildId);
|
||||||
const ping = `<@${this.client.user?.id}>`;
|
const ping = `<@${this.client.user?.id}>`;
|
||||||
const pingBang = `<@!${this.client.user?.id}>`;
|
const pingBang = `<@!${this.client.user?.id}>`;
|
||||||
|
|||||||
@@ -49,15 +49,41 @@ export class CommandLoader {
|
|||||||
err?.code === "COMMUNICATION_DISABLED" ||
|
err?.code === "COMMUNICATION_DISABLED" ||
|
||||||
err?.statusCode === 403;
|
err?.statusCode === 403;
|
||||||
};
|
};
|
||||||
|
const isRateLimitError = (err) => {
|
||||||
|
if (!err) return false;
|
||||||
|
if (err.name === "RateLimitError" || Number(err.statusCode ?? err.status) === 429) return true;
|
||||||
|
const msg = String(err.message || "").toLowerCase();
|
||||||
|
return msg.includes("rate limit");
|
||||||
|
};
|
||||||
|
const isNetworkError = (err) => {
|
||||||
|
if (!err) return false;
|
||||||
|
const status = Number(err.statusCode ?? err.status);
|
||||||
|
if (status === 502 || status === 503 || status === 504 || status === 520 || status === 521 || status === 522 || status === 524) return true;
|
||||||
|
const code = err.code || err.cause?.code || err.cause?.cause?.code;
|
||||||
|
if (code === "UND_ERR_SOCKET" || code === "ECONNRESET" || code === "ETIMEDOUT") return true;
|
||||||
|
const str = `${err.message || ""} ${err.cause?.message || ""}`.toLowerCase();
|
||||||
|
return str.includes("other side closed") || str.includes("fetch failed");
|
||||||
|
};
|
||||||
const sendErrorReply = (id) => {
|
const sendErrorReply = (id) => {
|
||||||
Promise.resolve(data.message.reply("An error occurred. Error id: `#" + id + "`"))
|
Promise.resolve(data.message.reply("An error occurred. Error id: `#" + id + "`"))
|
||||||
.catch(err => logger.warn("[CommandHandler] Failed to send error-reply; error id #" + id + ":", err?.message));
|
.catch(err => {
|
||||||
|
if (isRateLimitError(err) || isPermError(err) || isNetworkError(err)) return;
|
||||||
|
logger.warn("[CommandHandler] Failed to send error-reply; error id #" + id + ":", err?.message || err?.code || err);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
const handleCmdError = (e) => {
|
const handleCmdError = (e) => {
|
||||||
if (isPermError(e)) {
|
if (isPermError(e)) {
|
||||||
logger.warn(`[CommandHandler] Missing permissions in channel ${data.message?.channelId ?? data.message?.channel?.id}: ${e.code ?? e.message}`);
|
logger.warn(`[CommandHandler] Missing permissions in channel ${data.message?.channelId ?? data.message?.channel?.id}: ${e.code ?? e.message}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (isRateLimitError(e)) {
|
||||||
|
logger.warn(`[CommandHandler] Command '${data.command?.name ?? "unknown"}' rate limited by Fluxer API: ${e.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (isNetworkError(e)) {
|
||||||
|
logger.warn(`[CommandHandler] Transient network or socket closure during command '${data.command?.name ?? "unknown"}': ${e.code ?? e.message}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const id = Utils.uid();
|
const id = Utils.uid();
|
||||||
logger.error("Error running command; error id #" + id, e);
|
logger.error("Error running command; error id #" + id, e);
|
||||||
sendErrorReply(id);
|
sendErrorReply(id);
|
||||||
|
|||||||
+165
-11
@@ -21,6 +21,7 @@ import { resolveIsBotUser } from "../voice/VoiceStateResolver.mjs";
|
|||||||
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
|
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
|
||||||
import { RemoteSettingsManager } from "../db/Settings.mjs";
|
import { RemoteSettingsManager } from "../db/Settings.mjs";
|
||||||
import { PlayerStateStore } from "../db/PlayerStateStore.mjs";
|
import { PlayerStateStore } from "../db/PlayerStateStore.mjs";
|
||||||
|
import { RedisManager } from "../db/RedisManager.mjs";
|
||||||
import { getSharedMysqlPool, getSharedPromisePool, closeSharedMysqlPool } from "../db/PoolManager.mjs";
|
import { getSharedMysqlPool, getSharedPromisePool, closeSharedMysqlPool } from "../db/PoolManager.mjs";
|
||||||
import { PlayerManager } from "../music/PlayerManager.mjs";
|
import { PlayerManager } from "../music/PlayerManager.mjs";
|
||||||
import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
||||||
@@ -30,7 +31,10 @@ import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
|
|||||||
import { LastFmManager } from "../services/lastfm/LastFmManager.mjs";
|
import { LastFmManager } from "../services/lastfm/LastFmManager.mjs";
|
||||||
import { FluxerListManager } from "../services/FluxerListManager.mjs";
|
import { FluxerListManager } from "../services/FluxerListManager.mjs";
|
||||||
import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs";
|
import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs";
|
||||||
|
import { PlaylistManager } from "../services/PlaylistManager.mjs";
|
||||||
|
import { StatusChannelManager } from "../services/StatusChannelManager.mjs";
|
||||||
import { TrackStats } from "../music/TrackStats.mjs";
|
import { TrackStats } from "../music/TrackStats.mjs";
|
||||||
|
import { GuildStats } from "../music/GuildStats.mjs";
|
||||||
import { configureBilibili } from "../music/bilibili/index.mjs";
|
import { configureBilibili } from "../music/bilibili/index.mjs";
|
||||||
import { configureAudio } from "../music/audio/AudioSettings.mjs";
|
import { configureAudio } from "../music/audio/AudioSettings.mjs";
|
||||||
import { applyMixins } from "../utils/mixins.mjs";
|
import { applyMixins } from "../utils/mixins.mjs";
|
||||||
@@ -142,14 +146,26 @@ class Remix {
|
|||||||
const sharedPromisePool = getSharedPromisePool(config.mysql);
|
const sharedPromisePool = getSharedPromisePool(config.mysql);
|
||||||
|
|
||||||
TrackStats.setPool(sharedPromisePool);
|
TrackStats.setPool(sharedPromisePool);
|
||||||
|
GuildStats.setPool(sharedPromisePool);
|
||||||
|
|
||||||
|
const redisConfig = config.redis ?? (config.dashboard?.enabled ? config.dashboard?.redis : null);
|
||||||
|
this.redis = new RedisManager(this, redisConfig);
|
||||||
|
if (this.redis.enabled) {
|
||||||
|
this.redis.connect().catch((err) => {
|
||||||
|
logger.warn("[Redis] Startup connection error:", err?.message);
|
||||||
|
});
|
||||||
|
TrackStats.setRedis(this.redis);
|
||||||
|
GuildStats.setRedis(this.redis);
|
||||||
|
}
|
||||||
|
|
||||||
this.dashboard = new Dashboard(this, {
|
this.dashboard = new Dashboard(this, {
|
||||||
enabled: config.dashboard?.enabled,
|
enabled: config.dashboard?.enabled,
|
||||||
redis: config.dashboard?.redis,
|
redis: config.dashboard?.redis ?? (this.redis.enabled ? this.redis.config : null),
|
||||||
mysql: sharedPromisePool,
|
mysql: sharedPromisePool,
|
||||||
});
|
});
|
||||||
if (this.dashboard?.redis) {
|
if (!this.redis.enabled && this.dashboard?.redis) {
|
||||||
TrackStats.setRedis(this.dashboard.redis);
|
TrackStats.setRedis(this.dashboard.redis);
|
||||||
|
GuildStats.setRedis(this.dashboard.redis);
|
||||||
}
|
}
|
||||||
|
|
||||||
const presenceContents = config.presenceContents ?? [];
|
const presenceContents = config.presenceContents ?? [];
|
||||||
@@ -208,6 +224,9 @@ class Remix {
|
|||||||
this.settingsMgr = settings;
|
this.settingsMgr = settings;
|
||||||
|
|
||||||
this.playerState = new PlayerStateStore(sharedPool);
|
this.playerState = new PlayerStateStore(sharedPool);
|
||||||
|
if (this.redis?.enabled) {
|
||||||
|
this.playerState.setRedis(this.redis);
|
||||||
|
}
|
||||||
|
|
||||||
const configPrefix = config.prefix ?? null;
|
const configPrefix = config.prefix ?? null;
|
||||||
if (configPrefix && settings.defaults) {
|
if (configPrefix && settings.defaults) {
|
||||||
@@ -230,13 +249,13 @@ class Remix {
|
|||||||
commands.onPing = (msg) => {
|
commands.onPing = (msg) => {
|
||||||
msg.replyEmbed(
|
msg.replyEmbed(
|
||||||
this.handler.format(
|
this.handler.format(
|
||||||
"My prefix in this server is `$prefix`\n\nRun `$prefix$helpCmd` to get started!",
|
"My prefix in this community is `$prefix`\n\nRun `$prefix$helpCmd` to get started!",
|
||||||
msg.message.guildId
|
msg.message.guildId
|
||||||
),
|
),
|
||||||
false,
|
false,
|
||||||
{
|
{
|
||||||
icon_url: (msg.channel?.channel?.guild?.icon || msg.server?.icon)
|
icon_url: (msg.channel?.channel?.guild?.icon || msg.server?.icon)
|
||||||
? `https://cdn.fluxer.app/icons/${msg.channel?.channel?.guild?.id ?? msg.server?.id}/${msg.channel?.channel?.guild?.icon ?? msg.server?.icon}.webp`
|
? `https://fluxerusercontent.com/icons/${msg.channel?.channel?.guild?.id ?? msg.server?.id}/${msg.channel?.channel?.guild?.icon ?? msg.server?.icon}.webp`
|
||||||
: null,
|
: null,
|
||||||
title: msg.channel?.channel?.guild?.name ?? msg.server?.name ?? null,
|
title: msg.channel?.channel?.guild?.name ?? msg.server?.name ?? null,
|
||||||
}
|
}
|
||||||
@@ -270,18 +289,71 @@ class Remix {
|
|||||||
this.lastfm = new LastFmManager(config.lastfm, sharedPromisePool);
|
this.lastfm = new LastFmManager(config.lastfm, sharedPromisePool);
|
||||||
this.fluxerlist = new FluxerListManager(config.fluxerlist);
|
this.fluxerlist = new FluxerListManager(config.fluxerlist);
|
||||||
this.trackOptions = new TrackOptionsManager(sharedPool);
|
this.trackOptions = new TrackOptionsManager(sharedPool);
|
||||||
|
this.playlists = new PlaylistManager(sharedPromisePool);
|
||||||
|
this.statusChannel = new StatusChannelManager(this, config.statusChannel);
|
||||||
|
|
||||||
// Event loop health heartbeat for Docker container healthcheck (Issue #12)
|
/* Gateway activity timestamps and status tracking */
|
||||||
|
this._lastGatewayHeartbeat = Date.now();
|
||||||
|
this._lastGatewayDisconnect = 0;
|
||||||
|
this._gatewayConnected = false;
|
||||||
|
|
||||||
|
/* Event loop health heartbeat for Docker container healthcheck (Issue #12) */
|
||||||
const healthFile = path.join(os.tmpdir(), ".remix-health");
|
const healthFile = path.join(os.tmpdir(), ".remix-health");
|
||||||
const updateHealth = () => {
|
const updateHealth = () => {
|
||||||
try {
|
try {
|
||||||
fs.writeFile(healthFile, Date.now().toString(), () => {});
|
/* Only touch health file if gateway is healthy or still in initial boot */
|
||||||
|
const now = Date.now();
|
||||||
|
const silenceMs = this._hasBooted ? now - (this._lastGatewayHeartbeat || 0) : 0;
|
||||||
|
const disconnectedMs = (!this._gatewayConnected && this._hasBooted) ? (now - (this._lastGatewayDisconnect || now)) : 0;
|
||||||
|
if (silenceMs < 60_000 && disconnectedMs < 45_000) {
|
||||||
|
fs.writeFile(healthFile, now.toString(), () => {});
|
||||||
|
}
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
};
|
};
|
||||||
updateHealth();
|
updateHealth();
|
||||||
this._healthInterval = setInterval(updateHealth, 10_000);
|
this._healthInterval = setInterval(updateHealth, 10_000);
|
||||||
this._healthInterval.unref?.();
|
this._healthInterval.unref?.();
|
||||||
|
|
||||||
|
/* Active gateway self-healing watchdog */
|
||||||
|
this._gatewayWatchdogInterval = setInterval(async () => {
|
||||||
|
if (!this._hasBooted) return;
|
||||||
|
const now = Date.now();
|
||||||
|
const silenceMs = now - (this._lastGatewayHeartbeat || 0);
|
||||||
|
const disconnectedMs = !this._gatewayConnected ? (now - (this._lastGatewayDisconnect || now)) : 0;
|
||||||
|
|
||||||
|
/* After 25s of silence or disconnection, actively trigger reconnect attempts on local shards */
|
||||||
|
if (!this._gatewayConnected || silenceMs >= 25_000) {
|
||||||
|
const shards = ShardingUtils.getLocalShards(this.client);
|
||||||
|
for (const [id, shard] of shards) {
|
||||||
|
try {
|
||||||
|
if (typeof shard.connect === "function") shard.connect();
|
||||||
|
else if (typeof shard.reconnect === "function") shard.reconnect();
|
||||||
|
else if (typeof shard.ws?.connect === "function") shard.ws.connect();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* After 60s of total gateway silence or 45s of persistent disconnection, restart to auto-recover */
|
||||||
|
if (silenceMs >= 60_000 || disconnectedMs >= 45_000) {
|
||||||
|
logger.error(`[GatewayWatchdog] Gateway unresponsive (silence=${Math.round(silenceMs / 1000)}s, disconnected=${Math.round(disconnectedMs / 1000)}s) — performing graceful restart to restore service.`);
|
||||||
|
|
||||||
|
/* Hard kill timer in case gracefulShutdown hangs on network or database locks */
|
||||||
|
const hardKillTimer = setTimeout(() => {
|
||||||
|
process.exit(1);
|
||||||
|
}, 5_000);
|
||||||
|
hardKillTimer.unref?.();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await Promise.race([
|
||||||
|
this.gracefulShutdown(),
|
||||||
|
new Promise((_, reject) => setTimeout(() => reject(new Error("gracefulShutdown timed out")), 4_000))
|
||||||
|
]);
|
||||||
|
} catch (_) {}
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}, 10_000);
|
||||||
|
this._gatewayWatchdogInterval.unref?.();
|
||||||
|
|
||||||
// Direct process signal fallback handlers
|
// Direct process signal fallback handlers
|
||||||
process.once("SIGINT", () => {
|
process.once("SIGINT", () => {
|
||||||
this.gracefulShutdown().then(() => process.exit(0)).catch(() => process.exit(1));
|
this.gracefulShutdown().then(() => process.exit(0)).catch(() => process.exit(1));
|
||||||
@@ -295,6 +367,9 @@ class Remix {
|
|||||||
client.on(Events.Ready, async () => {
|
client.on(Events.Ready, async () => {
|
||||||
try {
|
try {
|
||||||
logger.player("Logged in as " + (client.user?.username ?? "bot"));
|
logger.player("Logged in as " + (client.user?.username ?? "bot"));
|
||||||
|
this._lastGatewayHeartbeat = Date.now();
|
||||||
|
this._gatewayConnected = true;
|
||||||
|
this._lastGatewayDisconnect = 0;
|
||||||
|
|
||||||
this._attachWsErrorHandlers();
|
this._attachWsErrorHandlers();
|
||||||
|
|
||||||
@@ -317,23 +392,62 @@ class Remix {
|
|||||||
if (!lavalinkInitialised) {
|
if (!lavalinkInitialised) {
|
||||||
lavalinkInitialised = true;
|
lavalinkInitialised = true;
|
||||||
this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" });
|
this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" });
|
||||||
|
this.lavalink.remix = this;
|
||||||
this.lavalink.on("ready", () => {
|
this.lavalink.on("ready", () => {
|
||||||
logger.lavalink("[Lavalink] Session ready");
|
logger.lavalink("[Lavalink] Session ready");
|
||||||
|
this.statusChannel?.resolveIncident("audioNode");
|
||||||
|
if (this._hasBooted) {
|
||||||
|
this.players?.resumeAllOnNodeReconnect?.();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.lavalink.on("nodeConnect", (node) => {
|
||||||
|
logger.lavalink("[Lavalink] Node connected: " + (node?.id ?? "main"));
|
||||||
|
this.statusChannel?.resolveIncident("audioNode");
|
||||||
if (this._hasBooted) {
|
if (this._hasBooted) {
|
||||||
this.players?.resumeAllOnNodeReconnect?.();
|
this.players?.resumeAllOnNodeReconnect?.();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
this.lavalink.on("nodeReconnect", () => {
|
this.lavalink.on("nodeReconnect", () => {
|
||||||
|
this.statusChannel?.resolveIncident("audioNode");
|
||||||
if (this._hasBooted) {
|
if (this._hasBooted) {
|
||||||
this.players?.resumeAllOnNodeReconnect?.();
|
this.players?.resumeAllOnNodeReconnect?.();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
this.lavalink.on("nodeDisconnect", (node, reason) => {
|
||||||
|
let reasonStr = "Connection dropped";
|
||||||
|
if (typeof reason === "string" && reason.trim()) {
|
||||||
|
reasonStr = reason.trim();
|
||||||
|
} else if (typeof reason === "object" && reason !== null) {
|
||||||
|
const text = reason.reason || reason.message;
|
||||||
|
const code = reason.code ? ` (code ${reason.code})` : "";
|
||||||
|
if (text) {
|
||||||
|
reasonStr = `${text}${code}`;
|
||||||
|
} else if (reason.code) {
|
||||||
|
reasonStr = `Socket closed (code ${reason.code})`;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
reasonStr = JSON.stringify(reason);
|
||||||
|
} catch (_) {
|
||||||
|
reasonStr = "Connection dropped";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.statusChannel?.triggerIncident("audioNode", `Audio engine disconnected: ${reasonStr}`);
|
||||||
|
});
|
||||||
|
this.lavalink.on("nodeError", (node, err) => {
|
||||||
|
this.statusChannel?.triggerIncident("audioNode", `Audio engine error: ${err?.message || "Unreachable"}`);
|
||||||
|
});
|
||||||
await this.lavalink.init();
|
await this.lavalink.init();
|
||||||
this.playerContext.lavalink = this.lavalink;
|
this.playerContext.lavalink = this.lavalink;
|
||||||
|
if (this.lavalink?._nodeConnected || Boolean(this.lavalink?.getNode?.())) {
|
||||||
|
this.statusChannel?.resolveIncident("audioNode");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.gatewayHandler.onReady();
|
this.gatewayHandler.onReady();
|
||||||
this._hasBooted = true;
|
this._hasBooted = true;
|
||||||
|
this.statusChannel?.start();
|
||||||
|
this.statusChannel?.resolveIncident("gateway");
|
||||||
|
|
||||||
this.fluxerlist?.startAutoStats?.(client);
|
this.fluxerlist?.startAutoStats?.(client);
|
||||||
|
|
||||||
@@ -365,6 +479,7 @@ class Remix {
|
|||||||
config,
|
config,
|
||||||
player: this.playerContext,
|
player: this.playerContext,
|
||||||
dashboard: this.dashboard,
|
dashboard: this.dashboard,
|
||||||
|
redis: this.redis,
|
||||||
locale: this.locale,
|
locale: this.locale,
|
||||||
timers: this.T,
|
timers: this.T,
|
||||||
trackOptions: this.trackOptions,
|
trackOptions: this.trackOptions,
|
||||||
@@ -589,7 +704,7 @@ class Remix {
|
|||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
|
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
|
||||||
_wsErrorCooldown.lastLogged = now;
|
_wsErrorCooldown.lastLogged = now;
|
||||||
logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`);
|
logger.player(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
const attachToSocket = (wsObj, label) => {
|
const attachToSocket = (wsObj, label) => {
|
||||||
@@ -616,9 +731,43 @@ class Remix {
|
|||||||
shard._fluxerErrorHandled = true;
|
shard._fluxerErrorHandled = true;
|
||||||
attachedNew = true;
|
attachedNew = true;
|
||||||
shard.on("error", (err) => logWsError(`Shard ${id}`, err));
|
shard.on("error", (err) => logWsError(`Shard ${id}`, err));
|
||||||
|
if (typeof shard.on === "function") {
|
||||||
|
shard.on("disconnect", () => {
|
||||||
|
this._gatewayConnected = false;
|
||||||
|
if (!this._lastGatewayDisconnect) this._lastGatewayDisconnect = Date.now();
|
||||||
|
});
|
||||||
|
shard.on("resume", () => {
|
||||||
|
this._gatewayConnected = true;
|
||||||
|
this._lastGatewayHeartbeat = Date.now();
|
||||||
|
this._lastGatewayDisconnect = 0;
|
||||||
|
});
|
||||||
|
shard.on("ready", () => {
|
||||||
|
this._gatewayConnected = true;
|
||||||
|
this._lastGatewayHeartbeat = Date.now();
|
||||||
|
this._lastGatewayDisconnect = 0;
|
||||||
|
});
|
||||||
|
}
|
||||||
if (shard.ws) attachToSocket(shard.ws, `Shard ${id} socket`);
|
if (shard.ws) attachToSocket(shard.ws, `Shard ${id} socket`);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (typeof this.client?.on === "function" && !this.client._fluxerShardEventsBound) {
|
||||||
|
this.client._fluxerShardEventsBound = true;
|
||||||
|
this.client.on("shardDisconnect", () => {
|
||||||
|
this._gatewayConnected = false;
|
||||||
|
if (!this._lastGatewayDisconnect) this._lastGatewayDisconnect = Date.now();
|
||||||
|
});
|
||||||
|
this.client.on("shardResume", () => {
|
||||||
|
this._gatewayConnected = true;
|
||||||
|
this._lastGatewayHeartbeat = Date.now();
|
||||||
|
this._lastGatewayDisconnect = 0;
|
||||||
|
});
|
||||||
|
this.client.on("shardReady", () => {
|
||||||
|
this._gatewayConnected = true;
|
||||||
|
this._lastGatewayHeartbeat = Date.now();
|
||||||
|
this._lastGatewayDisconnect = 0;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
for (const [id, shard] of ShardingUtils.getLocalShards(this.client)) {
|
for (const [id, shard] of ShardingUtils.getLocalShards(this.client)) {
|
||||||
attachToShard(shard, id);
|
attachToShard(shard, id);
|
||||||
}
|
}
|
||||||
@@ -694,11 +843,14 @@ class Remix {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
TrackStats.save();
|
TrackStats.save();
|
||||||
|
GuildStats.flushAll();
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
|
|
||||||
// 4. Close Redis if dashboard enabled
|
/* 4. Close Redis */
|
||||||
try {
|
try {
|
||||||
if (this.dashboard?.redis?.destroy) {
|
if (this.redis?.destroy) {
|
||||||
|
await this.redis.destroy();
|
||||||
|
} else if (this.dashboard?.redis?.destroy) {
|
||||||
await this.dashboard.redis.destroy();
|
await this.dashboard.redis.destroy();
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -714,8 +866,9 @@ class Remix {
|
|||||||
logger.error("[Shutdown] Failed to close Dashboard DB:", e.message);
|
logger.error("[Shutdown] Failed to close Dashboard DB:", e.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Stop 24/7 watchdog
|
/* 6. Stop 24/7 watchdog and status channel */
|
||||||
try {
|
try {
|
||||||
|
this.statusChannel?.destroy?.();
|
||||||
this.gatewayHandler?.stop247Watchdog?.();
|
this.gatewayHandler?.stop247Watchdog?.();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[Shutdown] Watchdog stop error:", e?.message);
|
logger.warn("[Shutdown] Watchdog stop error:", e?.message);
|
||||||
@@ -737,8 +890,9 @@ class Remix {
|
|||||||
logger.warn("[Shutdown] MySQL pool close failed:", e?.message);
|
logger.warn("[Shutdown] MySQL pool close failed:", e?.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 9. Clean up event-loop health heartbeat
|
/* 9. Clean up event-loop health heartbeat and gateway watchdog */
|
||||||
try {
|
try {
|
||||||
|
if (this._gatewayWatchdogInterval) clearInterval(this._gatewayWatchdogInterval);
|
||||||
if (this._healthInterval) clearInterval(this._healthInterval);
|
if (this._healthInterval) clearInterval(this._healthInterval);
|
||||||
const healthFile = path.join(os.tmpdir(), ".remix-health");
|
const healthFile = path.join(os.tmpdir(), ".remix-health");
|
||||||
fs.unlink(healthFile, () => {});
|
fs.unlink(healthFile, () => {});
|
||||||
|
|||||||
@@ -189,7 +189,7 @@ const BotVoiceMixin = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const guild = this.client?.guilds?.get?.(cleanG);
|
const guild = this.client?.guilds?.get?.(cleanG);
|
||||||
if (!guild) {
|
if (!guild && this.client?.guilds?.size > 0 && typeof this.client?.guilds?.fetch !== "function") {
|
||||||
logger.voice247(`[247] Bot is not currently in guild ${cleanG} — skipping rejoin for ${cleanCh} (setting kept intact)`);
|
logger.voice247(`[247] Bot is not currently in guild ${cleanG} — skipping rejoin for ${cleanCh} (setting kept intact)`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -203,7 +203,9 @@ const BotVoiceMixin = {
|
|||||||
if (!this._247RejoinTimers) this._247RejoinTimers = new Map();
|
if (!this._247RejoinTimers) this._247RejoinTimers = new Map();
|
||||||
if (this._247RejoinTimers.has(cleanCh)) return;
|
if (this._247RejoinTimers.has(cleanCh)) return;
|
||||||
|
|
||||||
const delay = delayMs ?? this.config?.timers?.rejoin247Delay ?? 3_000;
|
/* Stagger multiple simultaneous rejoins to avoid overwhelming the gateway and LiveKit */
|
||||||
|
const stagger = (this._247RejoinTimers.size) * 2_500;
|
||||||
|
const delay = delayMs ?? ((this.config?.timers?.rejoin247Delay ?? 3_000) + stagger);
|
||||||
logger.voice247(`[247] Arming bot-level rejoin for ${cleanCh} (guild ${cleanG}) in ${delay / 1000}s`);
|
logger.voice247(`[247] Arming bot-level rejoin for ${cleanCh} (guild ${cleanG}) in ${delay / 1000}s`);
|
||||||
|
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
@@ -212,13 +214,19 @@ const BotVoiceMixin = {
|
|||||||
logger.voice247(`[247] Rejoin for ${cleanCh} cancelled — intentional leave registered`);
|
logger.voice247(`[247] Rejoin for ${cleanCh} cancelled — intentional leave registered`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
/* Defer if gateway is reconnecting or down — voice join requires an active gateway connection */
|
||||||
|
if (this._gatewayConnected === false) {
|
||||||
|
logger.voice247(`[247] Gateway not connected yet — deferring rejoin for ${cleanCh} by 5s`);
|
||||||
|
this.schedule247Rejoin(cleanCh, cleanG, 5_000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const p = this.gatewayHandler?._rejoinChannel?.(cleanG, cleanCh);
|
const p = this.gatewayHandler?._rejoinChannel?.(cleanG, cleanCh);
|
||||||
if (p && typeof p.catch === "function") {
|
if (p && typeof p.catch === "function") {
|
||||||
p.catch(err => logger.warn(`[247] Rejoin failed for channel ${cleanCh}:`, err?.message ?? err));
|
p.catch(err => logger.voice247(`[247] Rejoin failed for channel ${cleanCh}:`, err?.message ?? err));
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.warn(`[247] Rejoin failed for channel ${cleanCh}:`, err?.message ?? err);
|
logger.voice247(`[247] Rejoin failed for channel ${cleanCh}:`, err?.message ?? err);
|
||||||
}
|
}
|
||||||
}, delay);
|
}, delay);
|
||||||
|
|
||||||
@@ -438,6 +446,22 @@ const BotVoiceMixin = {
|
|||||||
player.queue.loop = !!snap.loop;
|
player.queue.loop = !!snap.loop;
|
||||||
player.queue.songLoop = !!snap.songLoop;
|
player.queue.songLoop = !!snap.songLoop;
|
||||||
|
|
||||||
|
if (snap.autoplay) {
|
||||||
|
player._autoplay = true;
|
||||||
|
if (Array.isArray(snap.autoplayHistory)) {
|
||||||
|
player._autoplayHistory = [...snap.autoplayHistory];
|
||||||
|
}
|
||||||
|
if (snap.lastTrack && !player._lastPlayedTrack) {
|
||||||
|
player._lastPlayedTrack = snap.lastTrack;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { attachAutoplay } = await import("../../commands/autoplay.mjs");
|
||||||
|
attachAutoplay(player, this);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn(`[Restore] Autoplay re-attach failed for guild ${player._guildId}:`, e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const restoredQueue = (Array.isArray(snap.queue) ? snap.queue : [])
|
const restoredQueue = (Array.isArray(snap.queue) ? snap.queue : [])
|
||||||
.filter((t) => t && (t.url || t.encoded));
|
.filter((t) => t && (t.url || t.encoded));
|
||||||
|
|
||||||
@@ -449,12 +473,22 @@ const BotVoiceMixin = {
|
|||||||
else current = null;
|
else current = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (current && !player._lastPlayedTrack) {
|
||||||
|
player._lastPlayedTrack = current;
|
||||||
|
}
|
||||||
|
|
||||||
player.queue.data = [];
|
player.queue.data = [];
|
||||||
if (current) player.queue.data.push(current);
|
if (current) player.queue.data.push(current);
|
||||||
for (const t of restoredQueue) player.queue.data.push(t);
|
for (const t of restoredQueue) player.queue.data.push(t);
|
||||||
|
|
||||||
const count = player.queue.data.length;
|
const count = player.queue.data.length;
|
||||||
if (!count) return { count: 0, pos };
|
if (!count) {
|
||||||
|
if (snap.autoplay && player._autoplayHandler && player._lastPlayedTrack) {
|
||||||
|
player._autoplayHandler().catch((e) => logger.warn(`[Restore] Autoplay pick failed for guild ${player._guildId}:`, e?.message));
|
||||||
|
return { count: 1, pos: 0 };
|
||||||
|
}
|
||||||
|
return { count: 0, pos };
|
||||||
|
}
|
||||||
|
|
||||||
if (announce) {
|
if (announce) {
|
||||||
const restoreEmbed = new EmbedBuilder()
|
const restoreEmbed = new EmbedBuilder()
|
||||||
@@ -705,7 +739,7 @@ const BotVoiceMixin = {
|
|||||||
name: guild.name,
|
name: guild.name,
|
||||||
id: guild.id,
|
id: guild.id,
|
||||||
icon: guild.icon
|
icon: guild.icon
|
||||||
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
|
? `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`
|
||||||
: null,
|
: null,
|
||||||
description: guild.description ?? null,
|
description: guild.description ?? null,
|
||||||
ownerId: guild.ownerId ?? null,
|
ownerId: guild.ownerId ?? null,
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ import util from "node:util";
|
|||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { logger } from "./Logger.mjs";
|
import { logger } from "./Logger.mjs";
|
||||||
|
|
||||||
const DEFAULT_API_BASE = "https://api.fluxer.app/v1";
|
const DEFAULT_API_BASE = "https://fluxer.com/api/v1";
|
||||||
const SEND_TIMEOUT_MS = 5_000;
|
const SEND_TIMEOUT_MS = 5_000;
|
||||||
const CRASH_SEND_BUDGET_MS = 3_500;
|
const CRASH_SEND_BUDGET_MS = 3_500;
|
||||||
const FORWARD_DEDUP_MS = 60_000;
|
const FORWARD_DEDUP_MS = 60_000;
|
||||||
@@ -288,6 +288,16 @@ function _forward(level, tag, args) {
|
|||||||
if (typeof tag !== "string") return;
|
if (typeof tag !== "string") return;
|
||||||
if (tag.startsWith("[ErrorChannel]") || tag.startsWith("[Error_Handling]")) return;
|
if (tag.startsWith("[ErrorChannel]") || tag.startsWith("[Error_Handling]")) return;
|
||||||
const body = _formatArgs(args);
|
const body = _formatArgs(args);
|
||||||
|
/* Suppress expected external not-found lookups from generating alarmist telemetry warnings */
|
||||||
|
if (tag.includes("[LastFm]") && (/not found|error 6:/i.test(body) || /Track not found/i.test(body))) return;
|
||||||
|
/* Suppress status card incident publications and transient socket drops from creating telemetry warnings */
|
||||||
|
if (tag.includes("[StatusChannel]") && (/Incident published for/i.test(tag) || /Incident published for/i.test(body) || /other side closed/i.test(body) || /fetch failed/i.test(body))) return;
|
||||||
|
/* Suppress benign search fallback and candidate exploration warnings */
|
||||||
|
if (tag.includes("[Player]") && (/Free text search candidate/i.test(tag) || /search candidate.*failed/i.test(tag))) return;
|
||||||
|
/* Suppress transient node reconnect retry connection refused errors while audio engine boots */
|
||||||
|
if (tag.includes("[Lavalink]") && /ECONNREFUSED/i.test(body)) return;
|
||||||
|
/* Suppress routine boot recovery deferred resolution warnings */
|
||||||
|
if (tag.includes("[BootRecovery]") && /keeping the 24\/7 setting/i.test(body)) return;
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const key = `${level}|${tag}|${(body || tag).slice(0, 200)}`;
|
const key = `${level}|${tag}|${(body || tag).slice(0, 200)}`;
|
||||||
const last = _forwardDedup.get(key);
|
const last = _forwardDedup.get(key);
|
||||||
@@ -326,7 +336,14 @@ function _forward(level, tag, args) {
|
|||||||
/** @private Format values the same way console would. */
|
/** @private Format values the same way console would. */
|
||||||
function _formatArgs(args) {
|
function _formatArgs(args) {
|
||||||
try {
|
try {
|
||||||
return util.format(...args).trim();
|
let text = util.format(...args).trim();
|
||||||
|
if (/<!doctype|<html/i.test(text)) {
|
||||||
|
/* Sanitize upstream Cloudflare/Fluxer raw HTML error pages to clean summary */
|
||||||
|
const match = text.match(/HTTP\s*(\d{3})/i) || text.match(/<title>([^<]+)<\/title>/i);
|
||||||
|
const hint = match ? match[1] : "503";
|
||||||
|
text = text.replace(/<!doctype[\s\S]*$/i, `[HTTP ${hint}: Fluxer API temporarily unavailable — see fluxerstatus.com]`);
|
||||||
|
}
|
||||||
|
return text;
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ import { DatabaseManager } from "../db/DatabaseManager.mjs";
|
|||||||
import { RedisHandler } from "./RedisHandler.mjs";
|
import { RedisHandler } from "./RedisHandler.mjs";
|
||||||
import { logger } from "../core/Logger.mjs";
|
import { logger } from "../core/Logger.mjs";
|
||||||
import { applyMixins } from "../utils/mixins.mjs";
|
import { applyMixins } from "../utils/mixins.mjs";
|
||||||
|
import { PermissionFlags } from "@fluxerjs/core";
|
||||||
|
import { Utils } from "../utils/Utils.mjs";
|
||||||
import RpcHandlersMixin from "./RpcHandlersMixin.mjs";
|
import RpcHandlersMixin from "./RpcHandlersMixin.mjs";
|
||||||
import Serializers from "./Serializers.mjs";
|
import Serializers from "./Serializers.mjs";
|
||||||
|
|
||||||
|
|||||||
@@ -107,7 +107,7 @@ export class RedisHandler {
|
|||||||
.then(() => {
|
.then(() => {
|
||||||
if (this._destroyed) return;
|
if (this._destroyed) return;
|
||||||
logger.redis("[Redis/Main] Connected");
|
logger.redis("[Redis/Main] Connected");
|
||||||
this.readyMessage();
|
this.readyMessage(true);
|
||||||
})
|
})
|
||||||
.catch((e) => {
|
.catch((e) => {
|
||||||
logger.error("[Redis/Main] Initial connection failed:", e.message);
|
logger.error("[Redis/Main] Initial connection failed:", e.message);
|
||||||
@@ -117,6 +117,8 @@ export class RedisHandler {
|
|||||||
.then(() => {
|
.then(() => {
|
||||||
if (this._destroyed) return;
|
if (this._destroyed) return;
|
||||||
logger.redis("[Redis/Subscriber] Connected");
|
logger.redis("[Redis/Subscriber] Connected");
|
||||||
|
this.readyMessage(true);
|
||||||
|
this.send(this.platform + ":ping", "" + Date.now());
|
||||||
|
|
||||||
this.subscriber.subscribe("request", async (m) => {
|
this.subscriber.subscribe("request", async (m) => {
|
||||||
if (this._destroyed) return;
|
if (this._destroyed) return;
|
||||||
@@ -155,20 +157,34 @@ export class RedisHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Send a "connected" info message to the dashboard after a 5-second debounce.
|
* Send a "connected" info message to the dashboard.
|
||||||
|
* @param {boolean} [immediate=false]
|
||||||
* @returns {void}
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
readyMessage() {
|
readyMessage(immediate = false) {
|
||||||
if (this._destroyed) return;
|
if (this._destroyed) return;
|
||||||
if (this._readyTimer) clearTimeout(this._readyTimer);
|
if (this._readyTimer) clearTimeout(this._readyTimer);
|
||||||
this._readyTimer = setTimeout(() => {
|
const announce = () => {
|
||||||
this._readyTimer = null;
|
this._readyTimer = null;
|
||||||
if (this._destroyed) return;
|
if (this._destroyed) return;
|
||||||
this.send("info", JSON.stringify({
|
this.send("info", JSON.stringify({
|
||||||
platform: this.platform,
|
platform: this.platform,
|
||||||
type: "connected",
|
type: "connected",
|
||||||
}));
|
}));
|
||||||
}, 5000);
|
};
|
||||||
|
if (immediate) {
|
||||||
|
announce();
|
||||||
|
} else {
|
||||||
|
this._readyTimer = setTimeout(announce, 1500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether Redis clients are connected and ready.
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
isReady() {
|
||||||
|
return Boolean(!this._destroyed && this.client?.isReady);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -58,8 +58,7 @@ const Serializers = {
|
|||||||
if (!vid) return null;
|
if (!vid) return null;
|
||||||
const durationMs =
|
const durationMs =
|
||||||
typeof vid.duration === "number" ? vid.duration :
|
typeof vid.duration === "number" ? vid.duration :
|
||||||
typeof vid.duration === "object" && vid.duration?.seconds !== null ? vid.duration.seconds * 1000 :
|
(vid.duration?.seconds != null ? vid.duration.seconds * 1000 : 0);
|
||||||
0;
|
|
||||||
return {
|
return {
|
||||||
title: vid.title,
|
title: vid.title,
|
||||||
url: vid.type === "radio" ? vid.author?.url : vid.url,
|
url: vid.type === "radio" ? vid.author?.url : vid.url,
|
||||||
|
|||||||
@@ -75,6 +75,9 @@ export class PlayerStateStore {
|
|||||||
/** @private @type {Promise<void>|null} Memoized CREATE TABLE promise. */
|
/** @private @type {Promise<void>|null} Memoized CREATE TABLE promise. */
|
||||||
_tableReady = null;
|
_tableReady = null;
|
||||||
|
|
||||||
|
/** @private @type {object|null} Optional Redis manager for caching player sessions. */
|
||||||
|
redis = null;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {object|null} pool - mysql2 callback pool (RemoteSettingsManager.db).
|
* @param {object|null} pool - mysql2 callback pool (RemoteSettingsManager.db).
|
||||||
*/
|
*/
|
||||||
@@ -82,6 +85,14 @@ export class PlayerStateStore {
|
|||||||
this.db = pool ?? null;
|
this.db = pool ?? null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attach the Redis manager for ultra-fast session cache and recovery.
|
||||||
|
* @param {object|null} redisManager - RedisManager instance.
|
||||||
|
*/
|
||||||
|
setRedis(redisManager) {
|
||||||
|
this.redis = redisManager ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the bot id (called once the gateway client is ready).
|
* Set the bot id (called once the gateway client is ready).
|
||||||
* @param {string} id - Bot user id.
|
* @param {string} id - Bot user id.
|
||||||
@@ -142,7 +153,7 @@ export class PlayerStateStore {
|
|||||||
|
|
||||||
const current = player.queue?.getCurrent?.() ?? null;
|
const current = player.queue?.getCurrent?.() ?? null;
|
||||||
const queued = Array.isArray(player.queue?.data) ? player.queue.data : [];
|
const queued = Array.isArray(player.queue?.data) ? player.queue.data : [];
|
||||||
if (!current && queued.length === 0) {
|
if (!current && queued.length === 0 && !player._autoplay) {
|
||||||
return this.clearSnapshot(guildId);
|
return this.clearSnapshot(guildId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,6 +172,9 @@ export class PlayerStateStore {
|
|||||||
volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume : null,
|
volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume : null,
|
||||||
loop: !!player.queue?.loop,
|
loop: !!player.queue?.loop,
|
||||||
songLoop: !!player.queue?.songLoop,
|
songLoop: !!player.queue?.songLoop,
|
||||||
|
autoplay: !!player._autoplay,
|
||||||
|
autoplayHistory: Array.isArray(player._autoplayHistory) ? player._autoplayHistory.slice(-20) : [],
|
||||||
|
lastTrack: slimTrack(player._lastPlayedTrack),
|
||||||
current: slimTrack(current),
|
current: slimTrack(current),
|
||||||
positionMs,
|
positionMs,
|
||||||
queue: queued.slice(0, MAX_PERSISTED_TRACKS).map(slimTrack).filter(Boolean),
|
queue: queued.slice(0, MAX_PERSISTED_TRACKS).map(slimTrack).filter(Boolean),
|
||||||
@@ -173,6 +187,10 @@ export class PlayerStateStore {
|
|||||||
ON DUPLICATE KEY UPDATE data = VALUES(data), position_ms = VALUES(position_ms)`,
|
ON DUPLICATE KEY UPDATE data = VALUES(data), position_ms = VALUES(position_ms)`,
|
||||||
[this.botId, guildId, JSON.stringify(payload), positionMs]
|
[this.botId, guildId, JSON.stringify(payload), positionMs]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (this.redis?.isReady()) {
|
||||||
|
this.redis.savePlayerSession(guildId, payload).catch(() => {});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -198,7 +216,11 @@ export class PlayerStateStore {
|
|||||||
*/
|
*/
|
||||||
async clearSnapshot(guildId) {
|
async clearSnapshot(guildId) {
|
||||||
const gId = cleanId(guildId);
|
const gId = cleanId(guildId);
|
||||||
if (!gId || !this.db) return;
|
if (!gId) return;
|
||||||
|
if (this.redis?.isReady()) {
|
||||||
|
this.redis.deletePlayerSession(gId).catch(() => {});
|
||||||
|
}
|
||||||
|
if (!this.db) return;
|
||||||
try {
|
try {
|
||||||
await this.init();
|
await this.init();
|
||||||
await this._exec(`DELETE FROM player_state WHERE bot_id = ? AND guild_id = ?`, [this.botId, gId]);
|
await this._exec(`DELETE FROM player_state WHERE bot_id = ? AND guild_id = ?`, [this.botId, gId]);
|
||||||
@@ -210,6 +232,16 @@ export class PlayerStateStore {
|
|||||||
async load(guildId) {
|
async load(guildId) {
|
||||||
const gId = cleanId(guildId);
|
const gId = cleanId(guildId);
|
||||||
if (!gId) return null;
|
if (!gId) return null;
|
||||||
|
|
||||||
|
if (this.redis?.isReady()) {
|
||||||
|
try {
|
||||||
|
const cached = await this.redis.getPlayerSession(gId);
|
||||||
|
if (cached && cached.channelId) {
|
||||||
|
return { guildId: gId, data: cached, positionMs: Number(cached.positionMs) || 0 };
|
||||||
|
}
|
||||||
|
} catch (_) { /* fallback to database lookup */ }
|
||||||
|
}
|
||||||
|
|
||||||
await this.init();
|
await this.init();
|
||||||
const rows = await this._exec(
|
const rows = await this._exec(
|
||||||
`SELECT guild_id, data, position_ms FROM player_state WHERE bot_id = ? AND guild_id = ?`,
|
`SELECT guild_id, data, position_ms FROM player_state WHERE bot_id = ? AND guild_id = ?`,
|
||||||
|
|||||||
@@ -0,0 +1,223 @@
|
|||||||
|
/**
|
||||||
|
* @module src/db/RedisManager
|
||||||
|
* @description Centralized Redis service for caching, atomic counters,
|
||||||
|
* track search optimization, and 24/7 session restoration.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { createClient } from "redis";
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default linear-ramp reconnection strategy.
|
||||||
|
* @param {number} retries - Number of reconnection attempts made so far.
|
||||||
|
* @returns {number} Delay in milliseconds before next attempt.
|
||||||
|
*/
|
||||||
|
const DEFAULT_RETRY_STRATEGY = (retries) => {
|
||||||
|
if (!Number.isFinite(retries)) return 15_000;
|
||||||
|
return retries < 10 ? Math.min(retries * 500, 5_000) : 15_000;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class RedisManager
|
||||||
|
* @description Oversees Redis connection lifecycle, search caching, and player session checkpoints.
|
||||||
|
*/
|
||||||
|
export class RedisManager {
|
||||||
|
/**
|
||||||
|
* @param {object} remix - The main Bot instance.
|
||||||
|
* @param {object} [config] - Redis configuration object.
|
||||||
|
*/
|
||||||
|
constructor(remix, config = {}) {
|
||||||
|
this.remix = remix;
|
||||||
|
this.config = config || {};
|
||||||
|
this.enabled = this.config.enabled === true;
|
||||||
|
this.platform = "fluxer";
|
||||||
|
|
||||||
|
this.client = null;
|
||||||
|
this._isReady = false;
|
||||||
|
this._destroyed = false;
|
||||||
|
this.searchTtlSeconds = Number(this.config.searchTtlSeconds ?? 86400);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Connect to the Redis server if enabled.
|
||||||
|
* @returns {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
async connect() {
|
||||||
|
if (!this.enabled || !this.config.url) {
|
||||||
|
logger.redis("[Redis] Disabled or missing URL in configuration.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const clientOpts = {
|
||||||
|
url: this.config.url,
|
||||||
|
socket: {
|
||||||
|
connectTimeout: 5_000,
|
||||||
|
reconnectStrategy: DEFAULT_RETRY_STRATEGY,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
if (this.config.password) {
|
||||||
|
clientOpts.password = this.config.password;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.client = createClient(clientOpts);
|
||||||
|
|
||||||
|
this.client.on("error", (err) => {
|
||||||
|
logger.warn("[Redis] Client error:", err.message);
|
||||||
|
});
|
||||||
|
|
||||||
|
this.client.on("ready", () => {
|
||||||
|
this._isReady = true;
|
||||||
|
logger.redis("[Redis] Connected and operational.");
|
||||||
|
});
|
||||||
|
|
||||||
|
this.client.on("reconnecting", () => {
|
||||||
|
this._isReady = false;
|
||||||
|
logger.redis("[Redis] Reconnecting to server...");
|
||||||
|
});
|
||||||
|
|
||||||
|
this.client.on("end", () => {
|
||||||
|
this._isReady = false;
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.client.connect();
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[Redis] Initial connection attempt failed:", err.message);
|
||||||
|
this._isReady = false;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if the Redis client is connected and ready for commands.
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
isReady() {
|
||||||
|
return this._isReady && Boolean(this.client?.isOpen);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a cached track search result.
|
||||||
|
* @param {string} query - The search query or URL.
|
||||||
|
* @param {string} [source=""] - The Lavalink source prefix (e.g. ytmsearch).
|
||||||
|
* @returns {Promise<object|null>}
|
||||||
|
*/
|
||||||
|
async getCachedSearch(query, source = "") {
|
||||||
|
if (!this.isReady() || !query) return null;
|
||||||
|
try {
|
||||||
|
const key = this.getSearchCacheKey(query, source);
|
||||||
|
const data = await this.client.get(key);
|
||||||
|
if (!data) return null;
|
||||||
|
return JSON.parse(data);
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[Redis] Error reading search cache:", err?.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cache a track search result in Redis.
|
||||||
|
* @param {string} query - The search query or URL.
|
||||||
|
* @param {string} source - The Lavalink source prefix.
|
||||||
|
* @param {object} result - The search result object.
|
||||||
|
* @param {number} [ttlSeconds] - Custom TTL in seconds.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async cacheSearch(query, source, result, ttlSeconds = this.searchTtlSeconds) {
|
||||||
|
if (!this.isReady() || !query || !result) return;
|
||||||
|
try {
|
||||||
|
const key = this.getSearchCacheKey(query, source);
|
||||||
|
await this.client.set(key, JSON.stringify(result), {
|
||||||
|
EX: ttlSeconds,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[Redis] Error storing search cache:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a standardized cache key for audio searches.
|
||||||
|
* @param {string} query - The search query or URL.
|
||||||
|
* @param {string} [source=""] - The source prefix.
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
getSearchCacheKey(query, source = "") {
|
||||||
|
const cleanQuery = String(query).trim().toLowerCase().replace(/\s+/g, " ");
|
||||||
|
const cleanSource = String(source).trim().toLowerCase();
|
||||||
|
return `${this.platform}:cache:search:${cleanSource}:${cleanQuery}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save a player session snapshot for 24/7 recovery across bot restarts.
|
||||||
|
* @param {string} guildId - The guild snowflake ID.
|
||||||
|
* @param {object} sessionData - Session payload (queue, currentTrack, volume, mode).
|
||||||
|
* @param {number} [ttlSeconds=604800] - 7 days default retention.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async savePlayerSession(guildId, sessionData, ttlSeconds = 604800) {
|
||||||
|
if (!this.isReady() || !guildId || !sessionData) return;
|
||||||
|
try {
|
||||||
|
const key = `${this.platform}:player:session:${guildId}`;
|
||||||
|
await this.client.set(key, JSON.stringify(sessionData), {
|
||||||
|
EX: ttlSeconds,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn(`[Redis] Failed to save player session for guild ${guildId}:`, err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve a saved player session snapshot.
|
||||||
|
* @param {string} guildId - The guild snowflake ID.
|
||||||
|
* @returns {Promise<object|null>}
|
||||||
|
*/
|
||||||
|
async getPlayerSession(guildId) {
|
||||||
|
if (!this.isReady() || !guildId) return null;
|
||||||
|
try {
|
||||||
|
const key = `${this.platform}:player:session:${guildId}`;
|
||||||
|
const data = await this.client.get(key);
|
||||||
|
if (!data) return null;
|
||||||
|
return JSON.parse(data);
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn(`[Redis] Failed to load player session for guild ${guildId}:`, err?.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a saved player session snapshot.
|
||||||
|
* @param {string} guildId - The guild snowflake ID.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async deletePlayerSession(guildId) {
|
||||||
|
if (!this.isReady() || !guildId) return;
|
||||||
|
try {
|
||||||
|
const key = `${this.platform}:player:session:${guildId}`;
|
||||||
|
await this.client.del(key);
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn(`[Redis] Failed to delete player session for guild ${guildId}:`, err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gracefully close Redis connection.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async destroy() {
|
||||||
|
if (this._destroyed) return;
|
||||||
|
this._destroyed = true;
|
||||||
|
this._isReady = false;
|
||||||
|
try {
|
||||||
|
if (this.client?.isOpen) {
|
||||||
|
await this.client.quit();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Redis] Quit error:", e?.message);
|
||||||
|
}
|
||||||
|
logger.redis("[Redis] Connection closed gracefully.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default RedisManager;
|
||||||
@@ -179,6 +179,9 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
/** @private @type {boolean} True after shutdown() is called. */
|
/** @private @type {boolean} True after shutdown() is called. */
|
||||||
_shuttingDown = false;
|
_shuttingDown = false;
|
||||||
|
|
||||||
|
/** @private @type {boolean} Whether the settings table has been verified/created. */
|
||||||
|
_tableChecked = false;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a new RemoteSettingsManager backed by a MySQL pool.
|
* Create a new RemoteSettingsManager backed by a MySQL pool.
|
||||||
* @param {object} config - mysql2 pool or configuration (host, user, password, database).
|
* @param {object} config - mysql2 pool or configuration (host, user, password, database).
|
||||||
@@ -243,6 +246,25 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure the settings table exists in MySQL.
|
||||||
|
* Auto-creates the table on fresh databases.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async _ensureTable() {
|
||||||
|
if (this._tableChecked) return;
|
||||||
|
await this.query(`
|
||||||
|
CREATE TABLE IF NOT EXISTS \`settings\` (
|
||||||
|
\`id\` VARCHAR(32) NOT NULL,
|
||||||
|
\`data\` JSON NOT NULL,
|
||||||
|
\`bot_id\` VARCHAR(32) NOT NULL DEFAULT '',
|
||||||
|
PRIMARY KEY (\`id\`, \`bot_id\`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
`);
|
||||||
|
this._tableChecked = true;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ensure the `bot_id` column exists in the settings table and is part of the primary key.
|
* 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.
|
* Auto-migrates legacy tables that lack the column.
|
||||||
@@ -251,6 +273,7 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
*/
|
*/
|
||||||
async _ensureBotIdColumn() {
|
async _ensureBotIdColumn() {
|
||||||
if (this._hasBotIdColumn) return;
|
if (this._hasBotIdColumn) return;
|
||||||
|
await this._ensureTable();
|
||||||
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'`
|
||||||
@@ -351,6 +374,7 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
* @returns {Promise<{error: Error|null, results: any[], fields: any}>}
|
* @returns {Promise<{error: Error|null, results: any[], fields: any}>}
|
||||||
*/
|
*/
|
||||||
async selectGuild(guildId) {
|
async selectGuild(guildId) {
|
||||||
|
await this._ensureTable();
|
||||||
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()}`);
|
||||||
}
|
}
|
||||||
@@ -361,6 +385,7 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
async load() {
|
async load() {
|
||||||
|
await this._ensureTable();
|
||||||
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++;
|
||||||
@@ -461,6 +486,7 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
*/
|
*/
|
||||||
async create(id, server) {
|
async create(id, server) {
|
||||||
if (this._shuttingDown) return;
|
if (this._shuttingDown) return;
|
||||||
|
await this._ensureTable();
|
||||||
const escapedId = mysql.escape(id);
|
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();
|
||||||
|
|||||||
@@ -0,0 +1,876 @@
|
|||||||
|
/**
|
||||||
|
* @module src/music/GuildStats
|
||||||
|
* @description Persistent per-guild and global music analytics engine.
|
||||||
|
* Backed by MySQL relational tables and Redis atomic counters/sorted sets.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
|
const REDIS_GUILD_PREFIX = "fluxer:stats:guild:";
|
||||||
|
const REDIS_GLOBAL_PLAYS = "fluxer:stats:global:plays";
|
||||||
|
const REDIS_GLOBAL_SONGS = "fluxer:stats:global:songs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format 24-hour index into standard 12-hour display.
|
||||||
|
* @param {number} hour
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function formatHour(hour) {
|
||||||
|
const h = Number(hour) % 24;
|
||||||
|
const period = h >= 12 ? "PM" : "AM";
|
||||||
|
const display = h % 12 === 0 ? 12 : h % 12;
|
||||||
|
return `${display}:00 ${period}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
class GuildStatsManager {
|
||||||
|
constructor() {
|
||||||
|
/** @type {Map<string, object>} */
|
||||||
|
this._cache = new Map();
|
||||||
|
this._pool = null;
|
||||||
|
this._redis = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set centralized MySQL connection pool and initialize tables.
|
||||||
|
* @param {object} pool
|
||||||
|
*/
|
||||||
|
setPool(pool) {
|
||||||
|
this._pool = pool;
|
||||||
|
this._initDatabase().catch((e) => {
|
||||||
|
logger.warn("[GuildStats] Database init error:", e?.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set Redis manager instance for fast caching and atomic score increments.
|
||||||
|
* @param {object} redisHandler
|
||||||
|
*/
|
||||||
|
setRedis(redisHandler) {
|
||||||
|
this._redis = redisHandler;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize MySQL schema for guild track records and aggregated song counters.
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async _initDatabase() {
|
||||||
|
if (!this._pool) return;
|
||||||
|
try {
|
||||||
|
await this._pool.execute(`
|
||||||
|
CREATE TABLE IF NOT EXISTS \`guild_track_stats\` (
|
||||||
|
\`id\` BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
\`guild_id\` VARCHAR(32) NOT NULL,
|
||||||
|
\`title\` VARCHAR(255) NOT NULL,
|
||||||
|
\`artist\` VARCHAR(255) NOT NULL,
|
||||||
|
\`duration_ms\` BIGINT NOT NULL DEFAULT 0,
|
||||||
|
\`user_id\` VARCHAR(32) NULL,
|
||||||
|
\`hour_played\` TINYINT NOT NULL DEFAULT 0,
|
||||||
|
\`played_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
INDEX \`idx_guild_time\` (\`guild_id\`, \`played_at\`),
|
||||||
|
INDEX \`idx_global_time\` (\`played_at\`),
|
||||||
|
INDEX \`idx_guild_user\` (\`guild_id\`, \`user_id\`),
|
||||||
|
INDEX \`idx_user_time\` (\`user_id\`, \`played_at\`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
`);
|
||||||
|
|
||||||
|
await this._pool.execute(`
|
||||||
|
CREATE TABLE IF NOT EXISTS \`guild_song_counts\` (
|
||||||
|
\`guild_id\` VARCHAR(32) NOT NULL,
|
||||||
|
\`song_key\` VARCHAR(255) NOT NULL,
|
||||||
|
\`title\` VARCHAR(255) NOT NULL,
|
||||||
|
\`artist\` VARCHAR(255) NOT NULL,
|
||||||
|
\`play_count\` BIGINT NOT NULL DEFAULT 1,
|
||||||
|
\`duration_ms\` BIGINT NOT NULL DEFAULT 0,
|
||||||
|
\`last_played\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
PRIMARY KEY (\`guild_id\`, \`song_key\`),
|
||||||
|
INDEX \`idx_guild_plays\` (\`guild_id\`, \`play_count\` DESC)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
`);
|
||||||
|
|
||||||
|
/* Add supplementary indexes if tables already exist */
|
||||||
|
try {
|
||||||
|
await this._pool.execute("CREATE INDEX `idx_guild_user` ON `guild_track_stats` (`guild_id`, `user_id`);");
|
||||||
|
} catch (_) {}
|
||||||
|
try {
|
||||||
|
await this._pool.execute("CREATE INDEX `idx_user_time` ON `guild_track_stats` (`user_id`, `played_at`);");
|
||||||
|
} catch (_) {}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[GuildStats] Failed to initialize MySQL tables:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get or load in-memory guild stats object.
|
||||||
|
* @param {string} guildId
|
||||||
|
* @returns {object}
|
||||||
|
*/
|
||||||
|
_getGuildData(guildId) {
|
||||||
|
if (!guildId) return null;
|
||||||
|
if (this._cache.has(guildId)) {
|
||||||
|
return this._cache.get(guildId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
guildId,
|
||||||
|
totalPlays: 0,
|
||||||
|
totalDurationMs: 0,
|
||||||
|
hourly: new Array(24).fill(0),
|
||||||
|
users: {},
|
||||||
|
songs: {},
|
||||||
|
recent: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
this._cache.set(guildId, data);
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Record a track playback event for a specific guild into SQL, Redis, and file cache.
|
||||||
|
* @param {object} param0
|
||||||
|
* @param {string} param0.guildId
|
||||||
|
* @param {object} param0.track
|
||||||
|
* @param {string|null} [param0.userId]
|
||||||
|
*/
|
||||||
|
recordPlay({ guildId, track, userId = null }) {
|
||||||
|
if (!guildId || !track) return;
|
||||||
|
const data = this._getGuildData(guildId);
|
||||||
|
if (!data) return;
|
||||||
|
|
||||||
|
const title = track.title || "Unknown Track";
|
||||||
|
const artist = track.artist || (typeof track.author === "object" ? track.author?.name : track.author) || "Unknown Artist";
|
||||||
|
const durationMs = (() => {
|
||||||
|
const d = track.duration;
|
||||||
|
if (!d) return 0;
|
||||||
|
if (typeof d === "object" && d?.seconds) return d.seconds * 1000;
|
||||||
|
if (typeof d === "number") return d;
|
||||||
|
return 0;
|
||||||
|
})();
|
||||||
|
|
||||||
|
data.totalPlays += 1;
|
||||||
|
data.totalDurationMs += durationMs;
|
||||||
|
|
||||||
|
const currentHour = new Date().getHours();
|
||||||
|
data.hourly[currentHour] = (data.hourly[currentHour] || 0) + 1;
|
||||||
|
|
||||||
|
if (userId && typeof userId === "string" && userId !== "system") {
|
||||||
|
data.users[userId] = (data.users[userId] || 0) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const songKey = `${title}:::${artist}`;
|
||||||
|
if (!data.songs[songKey]) {
|
||||||
|
data.songs[songKey] = { title, artist, count: 0, durationMs };
|
||||||
|
}
|
||||||
|
data.songs[songKey].count += 1;
|
||||||
|
|
||||||
|
data.recent.unshift({
|
||||||
|
title,
|
||||||
|
artist,
|
||||||
|
durationMs,
|
||||||
|
userId: userId || null,
|
||||||
|
ts: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (data.recent.length > 1000) {
|
||||||
|
data.recent.length = 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (guildId !== "global") {
|
||||||
|
const globalData = this._getGuildData("global");
|
||||||
|
if (globalData) {
|
||||||
|
globalData.totalPlays += 1;
|
||||||
|
globalData.totalDurationMs += durationMs;
|
||||||
|
globalData.hourly[currentHour] = (globalData.hourly[currentHour] || 0) + 1;
|
||||||
|
if (!globalData.guilds) globalData.guilds = {};
|
||||||
|
globalData.guilds[guildId] = (globalData.guilds[guildId] || 0) + 1;
|
||||||
|
if (userId && typeof userId === "string" && userId !== "system") {
|
||||||
|
if (!globalData.users) globalData.users = {};
|
||||||
|
globalData.users[userId] = (globalData.users[userId] || 0) + 1;
|
||||||
|
}
|
||||||
|
if (!globalData.songs[songKey]) {
|
||||||
|
globalData.songs[songKey] = { title, artist, count: 0, durationMs };
|
||||||
|
}
|
||||||
|
globalData.songs[songKey].count += 1;
|
||||||
|
globalData.recent.unshift({
|
||||||
|
title,
|
||||||
|
artist,
|
||||||
|
durationMs,
|
||||||
|
userId: userId || null,
|
||||||
|
guildId,
|
||||||
|
ts: Date.now(),
|
||||||
|
});
|
||||||
|
if (globalData.recent.length > 2000) {
|
||||||
|
globalData.recent.length = 2000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Asynchronous MySQL persistence */
|
||||||
|
if (this._pool) {
|
||||||
|
this._pool.execute(`
|
||||||
|
INSERT INTO \`guild_track_stats\` (\`guild_id\`, \`title\`, \`artist\`, \`duration_ms\`, \`user_id\`, \`hour_played\`, \`played_at\`)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP);
|
||||||
|
`, [guildId, title.slice(0, 255), artist.slice(0, 255), durationMs, userId || null, currentHour]).catch((err) => {
|
||||||
|
logger.warn("[GuildStats] MySQL insert error:", err?.message);
|
||||||
|
});
|
||||||
|
|
||||||
|
this._pool.execute(`
|
||||||
|
INSERT INTO \`guild_song_counts\` (\`guild_id\`, \`song_key\`, \`title\`, \`artist\`, \`play_count\`, \`duration_ms\`, \`last_played\`)
|
||||||
|
VALUES (?, ?, ?, ?, 1, ?, CURRENT_TIMESTAMP)
|
||||||
|
ON DUPLICATE KEY UPDATE \`play_count\` = \`play_count\` + 1, \`last_played\` = CURRENT_TIMESTAMP;
|
||||||
|
`, [guildId, songKey.slice(0, 255), title.slice(0, 255), artist.slice(0, 255), durationMs]).catch(() => {});
|
||||||
|
|
||||||
|
if (guildId !== "global") {
|
||||||
|
this._pool.execute(`
|
||||||
|
INSERT INTO \`guild_track_stats\` (\`guild_id\`, \`title\`, \`artist\`, \`duration_ms\`, \`user_id\`, \`hour_played\`, \`played_at\`)
|
||||||
|
VALUES ('global', ?, ?, ?, ?, ?, CURRENT_TIMESTAMP);
|
||||||
|
`, [title.slice(0, 255), artist.slice(0, 255), durationMs, userId || null, currentHour]).catch(() => {});
|
||||||
|
|
||||||
|
this._pool.execute(`
|
||||||
|
INSERT INTO \`guild_song_counts\` (\`guild_id\`, \`song_key\`, \`title\`, \`artist\`, \`play_count\`, \`duration_ms\`, \`last_played\`)
|
||||||
|
VALUES ('global', ?, ?, ?, 1, ?, CURRENT_TIMESTAMP)
|
||||||
|
ON DUPLICATE KEY UPDATE \`play_count\` = \`play_count\` + 1, \`last_played\` = CURRENT_TIMESTAMP;
|
||||||
|
`, [songKey.slice(0, 255), title.slice(0, 255), artist.slice(0, 255), durationMs]).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Asynchronous Redis atomic increments */
|
||||||
|
const client = this._redis?.client;
|
||||||
|
if (client && client.isOpen) {
|
||||||
|
client.incrBy(`${REDIS_GUILD_PREFIX}${guildId}:plays`, 1).catch(() => {});
|
||||||
|
client.incrBy(REDIS_GLOBAL_PLAYS, 1).catch(() => {});
|
||||||
|
client.zIncrBy(`${REDIS_GUILD_PREFIX}${guildId}:songs`, 1, songKey).catch(() => {});
|
||||||
|
client.zIncrBy(REDIS_GLOBAL_SONGS, 1, songKey).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get top tracks for a guild with timeframe filtering.
|
||||||
|
* @param {string} guildId
|
||||||
|
* @param {string} [timeframe="month"] - "week" | "month" | "all"
|
||||||
|
* @param {number} [limit=10]
|
||||||
|
* @returns {Promise<{tracks: Array, topArtist: {name: string, count: number}|null}>}
|
||||||
|
*/
|
||||||
|
async getTopTracks(guildId, timeframe = "month", limit = 10) {
|
||||||
|
const lim = Math.max(1, Math.min(100, Number(limit) || 10));
|
||||||
|
|
||||||
|
if (this._pool) {
|
||||||
|
try {
|
||||||
|
let sql = "";
|
||||||
|
let params = [];
|
||||||
|
if (timeframe === "day") {
|
||||||
|
sql = `
|
||||||
|
SELECT \`title\`, \`artist\`, COUNT(*) as count, MAX(\`duration_ms\`) as durationMs
|
||||||
|
FROM \`guild_track_stats\`
|
||||||
|
WHERE \`guild_id\` = ? AND \`played_at\` >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
|
||||||
|
GROUP BY \`title\`, \`artist\`
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT ?;
|
||||||
|
`;
|
||||||
|
params = [guildId, lim];
|
||||||
|
} else if (timeframe === "week") {
|
||||||
|
sql = `
|
||||||
|
SELECT \`title\`, \`artist\`, COUNT(*) as count, MAX(\`duration_ms\`) as durationMs
|
||||||
|
FROM \`guild_track_stats\`
|
||||||
|
WHERE \`guild_id\` = ? AND \`played_at\` >= DATE_SUB(NOW(), INTERVAL 7 DAY)
|
||||||
|
GROUP BY \`title\`, \`artist\`
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT ?;
|
||||||
|
`;
|
||||||
|
params = [guildId, lim];
|
||||||
|
} else if (timeframe === "month") {
|
||||||
|
sql = `
|
||||||
|
SELECT \`title\`, \`artist\`, COUNT(*) as count, MAX(\`duration_ms\`) as durationMs
|
||||||
|
FROM \`guild_track_stats\`
|
||||||
|
WHERE \`guild_id\` = ? AND \`played_at\` >= DATE_SUB(NOW(), INTERVAL 30 DAY)
|
||||||
|
GROUP BY \`title\`, \`artist\`
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT ?;
|
||||||
|
`;
|
||||||
|
params = [guildId, lim];
|
||||||
|
} else if (timeframe === "year") {
|
||||||
|
sql = `
|
||||||
|
SELECT \`title\`, \`artist\`, COUNT(*) as count, MAX(\`duration_ms\`) as durationMs
|
||||||
|
FROM \`guild_track_stats\`
|
||||||
|
WHERE \`guild_id\` = ? AND \`played_at\` >= DATE_SUB(NOW(), INTERVAL 365 DAY)
|
||||||
|
GROUP BY \`title\`, \`artist\`
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT ?;
|
||||||
|
`;
|
||||||
|
params = [guildId, lim];
|
||||||
|
} else {
|
||||||
|
sql = `
|
||||||
|
SELECT \`title\`, \`artist\`, \`play_count\` as count, \`duration_ms\` as durationMs
|
||||||
|
FROM \`guild_song_counts\`
|
||||||
|
WHERE \`guild_id\` = ?
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT ?;
|
||||||
|
`;
|
||||||
|
params = [guildId, lim];
|
||||||
|
}
|
||||||
|
|
||||||
|
let [rows] = await this._pool.execute(sql, params);
|
||||||
|
if (rows && rows.length > 0) {
|
||||||
|
const artistMap = {};
|
||||||
|
const tracks = rows.map((r) => {
|
||||||
|
const c = Number(r.count) || 0;
|
||||||
|
if (r.artist && r.artist !== "Unknown Artist") {
|
||||||
|
artistMap[r.artist] = (artistMap[r.artist] || 0) + c;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
title: r.title,
|
||||||
|
artist: r.artist,
|
||||||
|
count: c,
|
||||||
|
durationMs: Number(r.durationMs) || 0,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const sortedArtists = Object.entries(artistMap).sort((a, b) => b[1] - a[1]);
|
||||||
|
const topArtist = sortedArtists.length > 0 ? { name: sortedArtists[0][0], count: sortedArtists[0][1] } : null;
|
||||||
|
|
||||||
|
return { tracks, topArtist };
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[GuildStats] MySQL getTopTracks error:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fallback to local memory/file cache */
|
||||||
|
const data = this._getGuildData(guildId);
|
||||||
|
if (!data || data.totalPlays === 0) {
|
||||||
|
return { tracks: [], topArtist: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
let trackMap = {};
|
||||||
|
const artistMap = {};
|
||||||
|
|
||||||
|
if (timeframe === "all") {
|
||||||
|
trackMap = data.songs;
|
||||||
|
for (const item of Object.values(trackMap)) {
|
||||||
|
artistMap[item.artist] = (artistMap[item.artist] || 0) + item.count;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const now = Date.now();
|
||||||
|
let cutoff = now - 30 * 86_400_000;
|
||||||
|
if (timeframe === "day") {
|
||||||
|
cutoff = now - 86_400_000;
|
||||||
|
} else if (timeframe === "week") {
|
||||||
|
cutoff = now - 7 * 86_400_000;
|
||||||
|
} else if (timeframe === "year") {
|
||||||
|
cutoff = now - 365 * 86_400_000;
|
||||||
|
}
|
||||||
|
for (const p of data.recent) {
|
||||||
|
if (p.ts >= cutoff) {
|
||||||
|
const k = `${p.title}:::${p.artist}`;
|
||||||
|
if (!trackMap[k]) {
|
||||||
|
trackMap[k] = { title: p.title, artist: p.artist, count: 0, durationMs: p.durationMs };
|
||||||
|
}
|
||||||
|
trackMap[k].count += 1;
|
||||||
|
artistMap[p.artist] = (artistMap[p.artist] || 0) + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let tracks = Object.values(trackMap)
|
||||||
|
.sort((a, b) => b.count - a.count)
|
||||||
|
.slice(0, lim);
|
||||||
|
|
||||||
|
if (tracks.length === 0 && Object.keys(data.songs || {}).length > 0) {
|
||||||
|
trackMap = data.songs;
|
||||||
|
for (const item of Object.values(trackMap)) {
|
||||||
|
artistMap[item.artist] = (artistMap[item.artist] || 0) + item.count;
|
||||||
|
}
|
||||||
|
tracks = Object.values(trackMap)
|
||||||
|
.sort((a, b) => b.count - a.count)
|
||||||
|
.slice(0, lim);
|
||||||
|
}
|
||||||
|
|
||||||
|
let topArtist = null;
|
||||||
|
const sortedArtists = Object.entries(artistMap).sort((a, b) => b[1] - a[1]);
|
||||||
|
if (sortedArtists.length > 0 && sortedArtists[0][0] !== "Unknown Artist") {
|
||||||
|
topArtist = { name: sortedArtists[0][0], count: sortedArtists[0][1] };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { tracks, topArtist };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get global top tracks across all servers.
|
||||||
|
* @param {number} [limit=10]
|
||||||
|
* @returns {Promise<{tracks: Array, topArtist: {name: string, count: number}|null}>}
|
||||||
|
*/
|
||||||
|
async getGlobalTopTracks(limit = 10) {
|
||||||
|
const lim = Math.max(1, Math.min(100, Number(limit) || 10));
|
||||||
|
|
||||||
|
if (this._pool) {
|
||||||
|
try {
|
||||||
|
let [rows] = await this._pool.execute(`
|
||||||
|
SELECT \`title\`, \`artist\`, \`play_count\` as count, \`duration_ms\` as durationMs
|
||||||
|
FROM \`guild_song_counts\`
|
||||||
|
WHERE \`guild_id\` = 'global'
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT ?;
|
||||||
|
`, [lim]);
|
||||||
|
|
||||||
|
if (!rows || rows.length === 0) {
|
||||||
|
const [aggRows] = await this._pool.execute(`
|
||||||
|
SELECT \`title\`, \`artist\`, SUM(\`play_count\`) as count, MAX(\`duration_ms\`) as durationMs
|
||||||
|
FROM \`guild_song_counts\`
|
||||||
|
WHERE \`guild_id\` != 'global'
|
||||||
|
GROUP BY \`title\`, \`artist\`
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT ?;
|
||||||
|
`, [lim]);
|
||||||
|
if (aggRows && aggRows.length > 0) {
|
||||||
|
rows = aggRows;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rows && rows.length > 0) {
|
||||||
|
const artistMap = {};
|
||||||
|
const tracks = rows.map((r) => {
|
||||||
|
const c = Number(r.count) || 0;
|
||||||
|
if (r.artist && r.artist !== "Unknown Artist") {
|
||||||
|
artistMap[r.artist] = (artistMap[r.artist] || 0) + c;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
title: r.title,
|
||||||
|
artist: r.artist,
|
||||||
|
count: c,
|
||||||
|
durationMs: Number(r.durationMs) || 0,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
const sortedArtists = Object.entries(artistMap).sort((a, b) => b[1] - a[1]);
|
||||||
|
const topArtist = sortedArtists.length > 0 ? { name: sortedArtists[0][0], count: sortedArtists[0][1] } : null;
|
||||||
|
|
||||||
|
return { tracks, topArtist };
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[GuildStats] MySQL getGlobalTopTracks error:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fallback to local global cache */
|
||||||
|
const globalData = this._getGuildData("global");
|
||||||
|
if (!globalData || globalData.totalPlays === 0) {
|
||||||
|
return { tracks: [], topArtist: null };
|
||||||
|
}
|
||||||
|
const tracks = Object.values(globalData.songs || {})
|
||||||
|
.sort((a, b) => b.count - a.count)
|
||||||
|
.slice(0, lim);
|
||||||
|
|
||||||
|
const artistMap = {};
|
||||||
|
for (const item of Object.values(globalData.songs || {})) {
|
||||||
|
if (item.artist && item.artist !== "Unknown Artist") {
|
||||||
|
artistMap[item.artist] = (artistMap[item.artist] || 0) + item.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const sortedArtists = Object.entries(artistMap).sort((a, b) => b[1] - a[1]);
|
||||||
|
const topArtist = sortedArtists.length > 0 ? { name: sortedArtists[0][0], count: sortedArtists[0][1] } : null;
|
||||||
|
|
||||||
|
return { tracks, topArtist };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get community monthly wrapped summary statistics.
|
||||||
|
* @param {string} guildId
|
||||||
|
* @returns {Promise<object|null>}
|
||||||
|
*/
|
||||||
|
async getWrapped(guildId) {
|
||||||
|
if (this._pool) {
|
||||||
|
try {
|
||||||
|
const [sumRows] = await this._pool.execute(`
|
||||||
|
SELECT COUNT(*) as totalTracks, COALESCE(SUM(\`duration_ms\`), 0) as totalDurationMs
|
||||||
|
FROM \`guild_track_stats\`
|
||||||
|
WHERE \`guild_id\` = ?;
|
||||||
|
`, [guildId]);
|
||||||
|
|
||||||
|
const totalTracks = Number(sumRows?.[0]?.totalTracks) || 0;
|
||||||
|
if (totalTracks > 0) {
|
||||||
|
const totalDurationMs = Number(sumRows?.[0]?.totalDurationMs) || 0;
|
||||||
|
const totalHours = Math.round((totalDurationMs / 3_600_000) * 10) / 10;
|
||||||
|
|
||||||
|
const [hourRows] = await this._pool.execute(`
|
||||||
|
SELECT \`hour_played\`, COUNT(*) as count
|
||||||
|
FROM \`guild_track_stats\`
|
||||||
|
WHERE \`guild_id\` = ?
|
||||||
|
GROUP BY \`hour_played\`
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT 1;
|
||||||
|
`, [guildId]);
|
||||||
|
const peakHour = hourRows?.[0] ? formatHour(hourRows[0].hour_played) : "12:00 PM";
|
||||||
|
|
||||||
|
const [userRows] = await this._pool.execute(`
|
||||||
|
SELECT \`user_id\`, COUNT(*) as count
|
||||||
|
FROM \`guild_track_stats\`
|
||||||
|
WHERE \`guild_id\` = ? AND \`user_id\` IS NOT NULL AND \`user_id\` != 'system'
|
||||||
|
GROUP BY \`user_id\`
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT 1;
|
||||||
|
`, [guildId]);
|
||||||
|
const topUserId = userRows?.[0]?.user_id || null;
|
||||||
|
const topUserPlays = Number(userRows?.[0]?.count) || 0;
|
||||||
|
|
||||||
|
const [trackRows] = await this._pool.execute(`
|
||||||
|
SELECT \`title\`, \`artist\`, \`play_count\` as count, \`duration_ms\` as durationMs
|
||||||
|
FROM \`guild_song_counts\`
|
||||||
|
WHERE \`guild_id\` = ?
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT 5;
|
||||||
|
`, [guildId]);
|
||||||
|
|
||||||
|
const topTracks = (trackRows || []).map((r) => ({
|
||||||
|
title: r.title,
|
||||||
|
artist: r.artist,
|
||||||
|
count: Number(r.count) || 0,
|
||||||
|
durationMs: Number(r.durationMs) || 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalHours,
|
||||||
|
totalTracks,
|
||||||
|
peakHour,
|
||||||
|
topUserId,
|
||||||
|
topUserPlays,
|
||||||
|
topTracks,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[GuildStats] MySQL getWrapped error:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fallback to local memory/file cache */
|
||||||
|
const data = this._getGuildData(guildId);
|
||||||
|
if (!data || data.totalPlays === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalHours = Math.round((data.totalDurationMs / 3_600_000) * 10) / 10;
|
||||||
|
|
||||||
|
let peakHourIndex = 0;
|
||||||
|
let peakHourCount = 0;
|
||||||
|
for (let i = 0; i < 24; i++) {
|
||||||
|
if ((data.hourly[i] || 0) > peakHourCount) {
|
||||||
|
peakHourCount = data.hourly[i];
|
||||||
|
peakHourIndex = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let topUserId = null;
|
||||||
|
let topUserPlays = 0;
|
||||||
|
for (const [uid, count] of Object.entries(data.users || {})) {
|
||||||
|
if (count > topUserPlays) {
|
||||||
|
topUserPlays = count;
|
||||||
|
topUserId = uid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const topTracks = Object.values(data.songs || {})
|
||||||
|
.sort((a, b) => b.count - a.count)
|
||||||
|
.slice(0, 5);
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalHours,
|
||||||
|
totalTracks: data.totalPlays,
|
||||||
|
peakHour: formatHour(peakHourIndex),
|
||||||
|
topUserId,
|
||||||
|
topUserPlays,
|
||||||
|
topTracks,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get global wrapped recap across all servers.
|
||||||
|
* @param {number} [fallbackServerCount=0]
|
||||||
|
* @returns {Promise<object|null>}
|
||||||
|
*/
|
||||||
|
async getGlobalWrapped(fallbackServerCount = 0) {
|
||||||
|
if (this._pool) {
|
||||||
|
try {
|
||||||
|
const [sumRows] = await this._pool.execute(`
|
||||||
|
SELECT COUNT(*) as totalTracks, COALESCE(SUM(\`duration_ms\`), 0) as totalDurationMs, COUNT(DISTINCT \`guild_id\`) as totalGuilds
|
||||||
|
FROM \`guild_track_stats\`
|
||||||
|
WHERE \`guild_id\` != 'global';
|
||||||
|
`);
|
||||||
|
|
||||||
|
const totalTracks = Number(sumRows?.[0]?.totalTracks) || 0;
|
||||||
|
if (totalTracks > 0) {
|
||||||
|
const totalDurationMs = Number(sumRows?.[0]?.totalDurationMs) || 0;
|
||||||
|
const totalHours = Math.round((totalDurationMs / 3_600_000) * 10) / 10;
|
||||||
|
const totalGuilds = Math.max(fallbackServerCount, Number(sumRows?.[0]?.totalGuilds) || 1);
|
||||||
|
|
||||||
|
const [hourRows] = await this._pool.execute(`
|
||||||
|
SELECT \`hour_played\`, COUNT(*) as count
|
||||||
|
FROM \`guild_track_stats\`
|
||||||
|
GROUP BY \`hour_played\`
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT 1;
|
||||||
|
`);
|
||||||
|
const peakHour = hourRows?.[0] ? formatHour(hourRows[0].hour_played) : "12:00 PM";
|
||||||
|
|
||||||
|
let [trackRows] = await this._pool.execute(`
|
||||||
|
SELECT \`title\`, \`artist\`, \`play_count\` as count, \`duration_ms\` as durationMs
|
||||||
|
FROM \`guild_song_counts\`
|
||||||
|
WHERE \`guild_id\` = 'global'
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT 5;
|
||||||
|
`);
|
||||||
|
if (!trackRows || trackRows.length === 0) {
|
||||||
|
const [aggRows] = await this._pool.execute(`
|
||||||
|
SELECT \`title\`, \`artist\`, SUM(\`play_count\`) as count, MAX(\`duration_ms\`) as durationMs
|
||||||
|
FROM \`guild_song_counts\`
|
||||||
|
WHERE \`guild_id\` != 'global'
|
||||||
|
GROUP BY \`title\`, \`artist\`
|
||||||
|
ORDER BY count DESC
|
||||||
|
LIMIT 5;
|
||||||
|
`);
|
||||||
|
if (aggRows && aggRows.length > 0) {
|
||||||
|
trackRows = aggRows;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const topTracks = (trackRows || []).map((r) => ({
|
||||||
|
title: r.title,
|
||||||
|
artist: r.artist,
|
||||||
|
count: Number(r.count) || 0,
|
||||||
|
durationMs: Number(r.durationMs) || 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalHours,
|
||||||
|
totalTracks,
|
||||||
|
peakHour,
|
||||||
|
totalGuilds,
|
||||||
|
topTracks,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[GuildStats] MySQL getGlobalWrapped error:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fallback to local memory/file cache */
|
||||||
|
const globalData = this._getGuildData("global");
|
||||||
|
if (!globalData || globalData.totalPlays === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalHours = Math.round((globalData.totalDurationMs / 3_600_000) * 10) / 10;
|
||||||
|
|
||||||
|
let peakHourIndex = 0;
|
||||||
|
let peakHourCount = 0;
|
||||||
|
for (let i = 0; i < 24; i++) {
|
||||||
|
if ((globalData.hourly[i] || 0) > peakHourCount) {
|
||||||
|
peakHourCount = globalData.hourly[i];
|
||||||
|
peakHourIndex = i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalGuilds = Math.max(
|
||||||
|
fallbackServerCount,
|
||||||
|
Object.keys(globalData.guilds || {}).length,
|
||||||
|
1
|
||||||
|
);
|
||||||
|
|
||||||
|
const topTracks = Object.values(globalData.songs || {})
|
||||||
|
.sort((a, b) => b.count - a.count)
|
||||||
|
.slice(0, 5);
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalHours,
|
||||||
|
totalTracks: globalData.totalPlays,
|
||||||
|
peakHour: formatHour(peakHourIndex),
|
||||||
|
totalGuilds,
|
||||||
|
topTracks,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get personal listening statistics for a specific user in a guild (or global network).
|
||||||
|
* @param {string} guildId
|
||||||
|
* @param {string} userId
|
||||||
|
* @returns {Promise<object|null>}
|
||||||
|
*/
|
||||||
|
async getUserStats(guildId, userId) {
|
||||||
|
if (!userId) return null;
|
||||||
|
|
||||||
|
if (this._pool) {
|
||||||
|
try {
|
||||||
|
const isGlobalScope = guildId === "global";
|
||||||
|
const sumSql = isGlobalScope
|
||||||
|
? "SELECT COUNT(*) as totalTracks, COALESCE(SUM(`duration_ms`), 0) as totalDurationMs FROM `guild_track_stats` WHERE `user_id` = ?;"
|
||||||
|
: "SELECT COUNT(*) as totalTracks, COALESCE(SUM(`duration_ms`), 0) as totalDurationMs FROM `guild_track_stats` WHERE `guild_id` = ? AND `user_id` = ?;";
|
||||||
|
const sumParams = isGlobalScope ? [userId] : [guildId, userId];
|
||||||
|
|
||||||
|
let [sumRows] = await this._pool.execute(sumSql, sumParams);
|
||||||
|
let totalTracks = Number(sumRows?.[0]?.totalTracks) || 0;
|
||||||
|
let isGlobalFallback = false;
|
||||||
|
|
||||||
|
if (totalTracks === 0 && !isGlobalScope) {
|
||||||
|
const [globalSumRows] = await this._pool.execute(
|
||||||
|
"SELECT COUNT(*) as totalTracks, COALESCE(SUM(`duration_ms`), 0) as totalDurationMs FROM `guild_track_stats` WHERE `user_id` = ?;",
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
if (Number(globalSumRows?.[0]?.totalTracks) > 0) {
|
||||||
|
sumRows = globalSumRows;
|
||||||
|
totalTracks = Number(globalSumRows[0].totalTracks);
|
||||||
|
isGlobalFallback = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (totalTracks > 0) {
|
||||||
|
const totalDurationMs = Number(sumRows?.[0]?.totalDurationMs) || 0;
|
||||||
|
const totalHours = Math.round((totalDurationMs / 3_600_000) * 10) / 10;
|
||||||
|
const effectiveGlobal = isGlobalScope || isGlobalFallback;
|
||||||
|
|
||||||
|
const hourSql = effectiveGlobal
|
||||||
|
? "SELECT `hour_played`, COUNT(*) as count FROM `guild_track_stats` WHERE `user_id` = ? GROUP BY `hour_played` ORDER BY count DESC LIMIT 1;"
|
||||||
|
: "SELECT `hour_played`, COUNT(*) as count FROM `guild_track_stats` WHERE `guild_id` = ? AND `user_id` = ? GROUP BY `hour_played` ORDER BY count DESC LIMIT 1;";
|
||||||
|
const hourParams = effectiveGlobal ? [userId] : [guildId, userId];
|
||||||
|
|
||||||
|
const [hourRows] = await this._pool.execute(hourSql, hourParams);
|
||||||
|
const peakHour = hourRows?.[0] ? formatHour(hourRows[0].hour_played) : "12:00 PM";
|
||||||
|
|
||||||
|
const trackSql = effectiveGlobal
|
||||||
|
? "SELECT `title`, `artist`, COUNT(*) as count, MAX(`duration_ms`) as durationMs FROM `guild_track_stats` WHERE `user_id` = ? GROUP BY `title`, `artist` ORDER BY count DESC LIMIT 5;"
|
||||||
|
: "SELECT `title`, `artist`, COUNT(*) as count, MAX(`duration_ms`) as durationMs FROM `guild_track_stats` WHERE `guild_id` = ? AND `user_id` = ? GROUP BY `title`, `artist` ORDER BY count DESC LIMIT 5;";
|
||||||
|
const trackParams = effectiveGlobal ? [userId] : [guildId, userId];
|
||||||
|
|
||||||
|
const [trackRows] = await this._pool.execute(trackSql, trackParams);
|
||||||
|
const topTracks = (trackRows || []).map((r) => ({
|
||||||
|
title: r.title,
|
||||||
|
artist: r.artist,
|
||||||
|
count: Number(r.count) || 0,
|
||||||
|
durationMs: Number(r.durationMs) || 0,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const artistMap = {};
|
||||||
|
for (const t of topTracks) {
|
||||||
|
if (t.artist && t.artist !== "Unknown Artist") {
|
||||||
|
artistMap[t.artist] = (artistMap[t.artist] || 0) + t.count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const sortedArtists = Object.entries(artistMap).sort((a, b) => b[1] - a[1]);
|
||||||
|
const topArtist = sortedArtists.length > 0 ? { name: sortedArtists[0][0], count: sortedArtists[0][1] } : null;
|
||||||
|
|
||||||
|
const lbSql = effectiveGlobal
|
||||||
|
? "SELECT `user_id`, COUNT(*) as plays FROM `guild_track_stats` WHERE `user_id` IS NOT NULL AND `user_id` != 'system' GROUP BY `user_id` ORDER BY plays DESC;"
|
||||||
|
: "SELECT `user_id`, COUNT(*) as plays FROM `guild_track_stats` WHERE `guild_id` = ? AND `user_id` IS NOT NULL AND `user_id` != 'system' GROUP BY `user_id` ORDER BY plays DESC;";
|
||||||
|
const lbParams = effectiveGlobal ? [] : [guildId];
|
||||||
|
|
||||||
|
const [leaderboardRows] = await this._pool.execute(lbSql, lbParams);
|
||||||
|
let djRank = 1;
|
||||||
|
let totalDjs = 1;
|
||||||
|
if (leaderboardRows && leaderboardRows.length > 0) {
|
||||||
|
totalDjs = leaderboardRows.length;
|
||||||
|
const idx = leaderboardRows.findIndex((r) => String(r.user_id) === String(userId));
|
||||||
|
if (idx !== -1) {
|
||||||
|
djRank = idx + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalTracks,
|
||||||
|
totalHours,
|
||||||
|
peakHour,
|
||||||
|
topTracks,
|
||||||
|
topArtist,
|
||||||
|
djRank,
|
||||||
|
totalDjs,
|
||||||
|
isGlobalFallback,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[GuildStats] MySQL getUserStats error:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Fallback to local memory/file cache */
|
||||||
|
let data = this._getGuildData(guildId);
|
||||||
|
let totalTracks = Number(data?.users?.[userId]) || 0;
|
||||||
|
let isGlobalFallback = false;
|
||||||
|
|
||||||
|
if (totalTracks === 0 && guildId !== "global") {
|
||||||
|
const globalData = this._getGuildData("global");
|
||||||
|
if (Number(globalData?.users?.[userId]) > 0) {
|
||||||
|
data = globalData;
|
||||||
|
totalTracks = Number(globalData.users[userId]);
|
||||||
|
isGlobalFallback = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!data || totalTracks === 0) return null;
|
||||||
|
|
||||||
|
const userTracks = (data.recent || []).filter((r) => String(r.userId) === String(userId));
|
||||||
|
let totalDurationMs = 0;
|
||||||
|
const songMap = {};
|
||||||
|
const artistMap = {};
|
||||||
|
const hourMap = {};
|
||||||
|
|
||||||
|
for (const item of userTracks) {
|
||||||
|
totalDurationMs += Number(item.durationMs) || 0;
|
||||||
|
const k = `${item.title}:::${item.artist}`;
|
||||||
|
if (!songMap[k]) {
|
||||||
|
songMap[k] = { title: item.title, artist: item.artist, count: 0 };
|
||||||
|
}
|
||||||
|
songMap[k].count += 1;
|
||||||
|
if (item.artist && item.artist !== "Unknown Artist") {
|
||||||
|
artistMap[item.artist] = (artistMap[item.artist] || 0) + 1;
|
||||||
|
}
|
||||||
|
const hr = new Date(item.ts || Date.now()).getHours();
|
||||||
|
hourMap[hr] = (hourMap[hr] || 0) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalHours = Math.round((totalDurationMs / 3_600_000) * 10) / 10;
|
||||||
|
const topTracks = Object.values(songMap)
|
||||||
|
.sort((a, b) => b.count - a.count)
|
||||||
|
.slice(0, 5);
|
||||||
|
|
||||||
|
const sortedArtists = Object.entries(artistMap).sort((a, b) => b[1] - a[1]);
|
||||||
|
const topArtist = sortedArtists.length > 0 ? { name: sortedArtists[0][0], count: sortedArtists[0][1] } : null;
|
||||||
|
|
||||||
|
let peakHourIndex = 12;
|
||||||
|
let peakHourCount = 0;
|
||||||
|
for (const [hr, cnt] of Object.entries(hourMap)) {
|
||||||
|
if (cnt > peakHourCount) {
|
||||||
|
peakHourCount = cnt;
|
||||||
|
peakHourIndex = Number(hr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const peakHour = formatHour(peakHourIndex);
|
||||||
|
|
||||||
|
const sortedUsers = Object.entries(data.users || {}).sort((a, b) => b[1] - a[1]);
|
||||||
|
const totalDjs = Math.max(1, sortedUsers.length);
|
||||||
|
const userIndex = sortedUsers.findIndex((u) => String(u[0]) === String(userId));
|
||||||
|
const djRank = userIndex !== -1 ? userIndex + 1 : 1;
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalTracks,
|
||||||
|
totalHours,
|
||||||
|
peakHour,
|
||||||
|
topTracks,
|
||||||
|
topArtist,
|
||||||
|
djRank,
|
||||||
|
totalDjs,
|
||||||
|
isGlobalFallback,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flush guild data (no-op: data is stored in MySQL).
|
||||||
|
* @param {string} [guildId]
|
||||||
|
*/
|
||||||
|
save(guildId) {
|
||||||
|
/* No-op: Data is stored permanently in MySQL relational tables */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Flush all active guild caches (no-op: data is stored in MySQL).
|
||||||
|
*/
|
||||||
|
flushAll() {
|
||||||
|
/* No-op: Data is stored permanently in MySQL relational tables */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GuildStats = new GuildStatsManager();
|
||||||
@@ -41,6 +41,7 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
authorization:nodeCfg.password ?? "youshallnotpass",
|
authorization:nodeCfg.password ?? "youshallnotpass",
|
||||||
secure: nodeCfg.secure ?? false,
|
secure: nodeCfg.secure ?? false,
|
||||||
nodeType: NodeType.NodeLink,
|
nodeType: NodeType.NodeLink,
|
||||||
|
heartBeatInterval: Number(nodeCfg.heartBeatInterval ?? 60_000),
|
||||||
requestSignalTimeoutMS: Number.isFinite(requestSignalTimeoutMS) ? requestSignalTimeoutMS : 60_000,
|
requestSignalTimeoutMS: Number.isFinite(requestSignalTimeoutMS) ? requestSignalTimeoutMS : 60_000,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -68,7 +69,12 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
if (nodeMgr) {
|
if (nodeMgr) {
|
||||||
try {
|
try {
|
||||||
nodeMgr.on("error", (node, err) => {
|
nodeMgr.on("error", (node, err) => {
|
||||||
logger.error("[Lavalink] NodeManager error:", node?.id, err?.message ?? err);
|
const msg = err?.message ?? String(err ?? "");
|
||||||
|
if (!this._nodeConnected && /ECONNREFUSED|ETIMEDOUT|ENOTFOUND/i.test(msg)) {
|
||||||
|
logger.lavalink("[Lavalink] Node reconnect attempt:", node?.id, msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logger.error("[Lavalink] NodeManager error:", node?.id, msg);
|
||||||
});
|
});
|
||||||
nodeMgr.on("connect", (node) => {
|
nodeMgr.on("connect", (node) => {
|
||||||
this._nodeConnected = true;
|
this._nodeConnected = true;
|
||||||
@@ -111,7 +117,12 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.lavalink.on("nodeError", (node, err) => {
|
this.lavalink.on("nodeError", (node, err) => {
|
||||||
logger.error("[Lavalink] Node error (manager):", node.id, err?.message ?? err);
|
const msg = err?.message ?? String(err ?? "");
|
||||||
|
if (!this._nodeConnected && /ECONNREFUSED|ETIMEDOUT|ENOTFOUND/i.test(msg)) {
|
||||||
|
logger.lavalink("[Lavalink] Node reconnect attempt (manager):", node?.id ?? node, msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logger.error("[Lavalink] Node error (manager):", node?.id ?? node, msg);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
@@ -451,43 +462,59 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
/** @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 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 = {}) {
|
async search(query, options = {}) {
|
||||||
try {
|
const redis = this.remix?.redis;
|
||||||
const players = this.lavalink?.players;
|
if (redis?.isReady() && typeof query === "string") {
|
||||||
if (players?.size > 0) {
|
const cached = await redis.getCachedSearch(query, options?.source);
|
||||||
const firstPlayer = players.values?.().next?.().value;
|
if (cached && (cached.tracks?.length > 0 || cached.loadType === "track" || cached.loadType === "playlist" || cached.loadType === "search")) {
|
||||||
if (firstPlayer?.node) {
|
return cached;
|
||||||
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 executeSearch = async () => {
|
||||||
const nodes = this.lavalink?.nodes;
|
try {
|
||||||
const nodeId = this._nodeCfg?.id ?? "main";
|
const players = this.lavalink?.players;
|
||||||
const node = nodes?.get?.(nodeId) ?? nodes?.cache?.get?.(nodeId);
|
if (players?.size > 0) {
|
||||||
if (node) {
|
const firstPlayer = players.values?.().next?.().value;
|
||||||
logger.lavalink("[Lavalink] search via fallback node.get()");
|
if (firstPlayer?.node) {
|
||||||
if (options.source) {
|
logger.lavalink("[Lavalink] search via player.node for guild " + firstPlayer.guildId);
|
||||||
return node.search({ query, source: options.source });
|
if (options.source) {
|
||||||
|
return await firstPlayer.node.search({ query, source: options.source });
|
||||||
|
}
|
||||||
|
return await firstPlayer.node.search(query);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return node.search(query);
|
} catch (_) { /* fall through to node-based search */ }
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
|
|
||||||
throw new Error("No connected Lavalink node available for search");
|
const node = this._getConnectedNode();
|
||||||
|
if (node) {
|
||||||
|
logger.lavalink("[Lavalink] search via _getConnectedNode()");
|
||||||
|
if (options.source) {
|
||||||
|
return await node.search({ query, source: options.source });
|
||||||
|
}
|
||||||
|
return await node.search(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const nodes = this.lavalink?.nodes;
|
||||||
|
const nodeId = this._nodeCfg?.id ?? "main";
|
||||||
|
const fallbackNode = nodes?.get?.(nodeId) ?? nodes?.cache?.get?.(nodeId);
|
||||||
|
if (fallbackNode) {
|
||||||
|
logger.lavalink("[Lavalink] search via fallback node.get()");
|
||||||
|
if (options.source) {
|
||||||
|
return await fallbackNode.search({ query, source: options.source });
|
||||||
|
}
|
||||||
|
return await fallbackNode.search(query);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
throw new Error("No connected Lavalink node available for search");
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await executeSearch();
|
||||||
|
if (redis?.isReady() && result && (result.tracks?.length > 0 || result.loadType === "track" || result.loadType === "playlist")) {
|
||||||
|
redis.cacheSearch(query, options?.source, result).catch(() => {});
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Get the Lavalink player for a guild. @param {string} guildId - The guild ID. @returns {object|null} The Lavalink player, or null if not found. */
|
/** Get the Lavalink player for a guild. @param {string} guildId - The guild ID. @returns {object|null} The Lavalink player, or null if not found. */
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { cleanId } from "../utils/Utils.mjs";
|
|||||||
import { getMessageGuildId } from "../ui/index.mjs";
|
import { getMessageGuildId } from "../ui/index.mjs";
|
||||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||||
import { TrackStats } from "./TrackStats.mjs";
|
import { TrackStats } from "./TrackStats.mjs";
|
||||||
|
import { GuildStats } from "./GuildStats.mjs";
|
||||||
|
|
||||||
/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */
|
/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */
|
||||||
function getPlayerGuildId(player, fallbackChannel = null) {
|
function getPlayerGuildId(player, fallbackChannel = null) {
|
||||||
@@ -97,12 +98,41 @@ const PlayerEventsMixin = {
|
|||||||
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
||||||
|
|
||||||
if (!player._radioReconnects) {
|
if (!player._radioReconnects) {
|
||||||
let userId = song?.requester ?? null;
|
let userId = null;
|
||||||
|
if (typeof song?.requester === "string") {
|
||||||
|
userId = cleanId(song.requester);
|
||||||
|
} else if (song?.requester && typeof song.requester === "object") {
|
||||||
|
userId = cleanId(song.requester.id ?? song.requester.requester ?? song.requester.userId ?? "");
|
||||||
|
} else if (song?.userId) {
|
||||||
|
userId = cleanId(song.userId);
|
||||||
|
}
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
const humans = player._getHumanParticipantIdentities?.() ?? [];
|
const humans = player._getHumanParticipantIdentities?.() ?? [];
|
||||||
if (humans.length === 1) userId = humans[0];
|
if (humans.length === 1) userId = cleanId(humans[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
TrackStats.increment(userId || null);
|
||||||
|
|
||||||
|
const resolvedGuildId = cleanId(
|
||||||
|
player._resolveGuildId?.() ??
|
||||||
|
player._guildId ??
|
||||||
|
context.guildId ??
|
||||||
|
getMessageGuildId({ channel: player.channel }) ??
|
||||||
|
getMessageGuildId({ channel: player.textChannel }) ??
|
||||||
|
player.channel?.guildId ??
|
||||||
|
player.channel?.guild?.id ??
|
||||||
|
player.channel?.serverId ??
|
||||||
|
player.channel?.server_id ??
|
||||||
|
""
|
||||||
|
);
|
||||||
|
|
||||||
|
if (resolvedGuildId && song) {
|
||||||
|
GuildStats.recordPlay({
|
||||||
|
guildId: resolvedGuildId,
|
||||||
|
track: song,
|
||||||
|
userId: userId || null,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
TrackStats.increment(userId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this._lastfm?.enabled && song) {
|
if (this._lastfm?.enabled && song) {
|
||||||
@@ -268,7 +298,7 @@ const PlayerEventsMixin = {
|
|||||||
const durationMs = (() => {
|
const durationMs = (() => {
|
||||||
const d = song.duration;
|
const d = song.duration;
|
||||||
if (!d) return null;
|
if (!d) return null;
|
||||||
if (typeof d === "object" && d.seconds) return d.seconds * 1000;
|
if (typeof d === "object" && d?.seconds) return d.seconds * 1000;
|
||||||
if (typeof d === "number") return d;
|
if (typeof d === "number") return d;
|
||||||
return null;
|
return null;
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -410,7 +410,41 @@ const PlayerLifecycleMixin = {
|
|||||||
}
|
}
|
||||||
this.setupEvents(player, {
|
this.setupEvents(player, {
|
||||||
channelId: cleanChannelId,
|
channelId: cleanChannelId,
|
||||||
guildId: cleanId(channel.guildId ?? getMessageGuildId(message)),
|
guildId: cleanId(channel.guildId ?? channel.guild?.id ?? channel.serverId ?? channel.server_id ?? getMessageGuildId(message)),
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("inactivityWarning", ({ timeoutMs }) => {
|
||||||
|
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
|
||||||
|
const ch = player.textChannel;
|
||||||
|
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
|
||||||
|
const prefix = this.commands.getPrefix(guildId);
|
||||||
|
const minutes = Math.max(1, Math.round((timeoutMs || 180000) / 60000));
|
||||||
|
const autoleaveChMgr = this.commands?.client?.channels ?? null;
|
||||||
|
let targetCh = (ch && typeof ch === "object" && typeof ch.send !== "function" && ch.id &&
|
||||||
|
autoleaveChMgr && typeof autoleaveChMgr.send === "function")
|
||||||
|
? (() => { const t = { id: ch.id, type: ch.type }; t.send = (o) => autoleaveChMgr.send(ch.id, o); return t; })()
|
||||||
|
: ch;
|
||||||
|
if (typeof targetCh?.send === "function") {
|
||||||
|
const title = this.locale?.translate(guildId, "responses.join.inactivityWarningTitle") ?? "Leaving Voice Soon";
|
||||||
|
const desc = this.locale?.translate(guildId, "responses.join.inactivityWarningDesc", {
|
||||||
|
channel: activeChannelId,
|
||||||
|
minutes,
|
||||||
|
prefix,
|
||||||
|
}) ?? `Voice session is currently inactive. Disconnecting from <#${activeChannelId}> in **${minutes} minute(s)**.\n\nUse \`${prefix}247\` to keep me in voice 24/7!`;
|
||||||
|
const footer = this.locale?.translate(guildId, "responses.join.inactivityWarningFooter", { prefix }) ?? `Play a song with ${prefix}play to resume`;
|
||||||
|
|
||||||
|
const warnEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.locale?.translate(guildId, "responses.join.autoLeaveAuthor") ?? "⏱️ Voice Watchdog • Session Inactive" })
|
||||||
|
.setTitle(title)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: footer });
|
||||||
|
targetCh.send({ embeds: [warnEmbed], allowedMentions: { parse: [] } }).catch(err => {
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[PlayerManager] Cannot send inactivity warning message in channel ${targetCh.id} — missing permissions`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
player.on("autoleave", () => {
|
player.on("autoleave", () => {
|
||||||
@@ -574,6 +608,13 @@ const PlayerLifecycleMixin = {
|
|||||||
player.textChannel = null;
|
player.textChannel = null;
|
||||||
logger.warn(`[PlayerManager] Cannot send player message in channel ${ch.id} — missing permissions`);
|
logger.warn(`[PlayerManager] Cannot send player message in channel ${ch.id} — missing permissions`);
|
||||||
} else {
|
} else {
|
||||||
|
const status = err?.status ?? err?.statusCode;
|
||||||
|
const is5xx = status >= 500 && status < 600;
|
||||||
|
const isHtml = typeof err?.message === "string" && /<!doctype|<html/i.test(err.message);
|
||||||
|
if (is5xx || isHtml) {
|
||||||
|
logger.player(`[PlayerManager] Could not send player message in channel ${ch.id} (Fluxer API HTTP ${status || 503} unavailable)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
logger.warn(`[PlayerManager] Failed to send player message in channel ${ch.id}:`, err?.message ?? err);
|
logger.warn(`[PlayerManager] Failed to send player message in channel ${ch.id}:`, err?.message ?? err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ const TRACK_KIND_AUDIO = 1;
|
|||||||
const pendingUnpublishSids = new WeakMap();
|
const pendingUnpublishSids = new WeakMap();
|
||||||
|
|
||||||
/** @type {number} @description Max time to wait for a stale-track unpublish to settle before publishing anyway (defensive — an unpublish should resolve almost instantly; this only guards against a hung/never-resolving LiveKit promise blocking playback indefinitely). */
|
/** @type {number} @description Max time to wait for a stale-track unpublish to settle before publishing anyway (defensive — an unpublish should resolve almost instantly; this only guards against a hung/never-resolving LiveKit promise blocking playback indefinitely). */
|
||||||
const UNPUBLISH_WAIT_TIMEOUT_MS = 1200;
|
const UNPUBLISH_WAIT_TIMEOUT_MS = 2500;
|
||||||
|
|
||||||
/** @extends {EventEmitter} */
|
/** @extends {EventEmitter} */
|
||||||
export class FluxerAudioBridge extends EventEmitter {
|
export class FluxerAudioBridge extends EventEmitter {
|
||||||
@@ -35,6 +35,7 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
_endResolve = null;
|
_endResolve = null;
|
||||||
_endReject = null;
|
_endReject = null;
|
||||||
_usedTrackstream = false;
|
_usedTrackstream = false;
|
||||||
|
_ffmpegProc = null;
|
||||||
|
|
||||||
/** @type {boolean} @description Whether audio is currently playing. */
|
/** @type {boolean} @description Whether audio is currently playing. */
|
||||||
get playing() { return this._playing; }
|
get playing() { return this._playing; }
|
||||||
@@ -114,10 +115,33 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
durationMs = options.durationMs || 0; // reset in case trackstream consumed it
|
durationMs = options.durationMs || 0; // reset in case trackstream consumed it
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Route B: /v4/loadstream — opt-in legacy route (server-side seek,
|
/* ── Route B: /v4/loadstream — opt-in legacy route (server-side seek,
|
||||||
// filters and MP3/AAC/PCM decoding). Unchanged behavior when enabled.
|
filters and MP3/AAC/PCM decoding). Falls back gracefully on node timeout. */
|
||||||
if (loadstreamEnabled && trackInfo.encoded && this._lavalink) {
|
if (loadstreamEnabled && trackInfo.encoded && this._lavalink) {
|
||||||
const loaded = await this._streamFromLoadstream(trackInfo, seekMs, filterPayload);
|
let loaded = null;
|
||||||
|
try {
|
||||||
|
loaded = await this._streamFromLoadstream(trackInfo, seekMs, filterPayload);
|
||||||
|
} catch (loadErr) {
|
||||||
|
logger.warn(`[AudioBridge] loadstream failed (${loadErr.message}) — attempting fallback...`);
|
||||||
|
/* If trackstream was skipped due to filters or seek, try trackstream without server-side filter */
|
||||||
|
if (!trackstreamGate) {
|
||||||
|
logger.player("[AudioBridge] Falling back to trackstream route (without server-side filters)...");
|
||||||
|
const trackstreamFallback = await this._playViaTrackstream(conn, trackInfo, { seekMs, durationMs, generation });
|
||||||
|
if (trackstreamFallback !== null) return trackstreamFallback;
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
}
|
||||||
|
/* If trackInfo has a playable URL, fall back to in-process ffmpeg decoding */
|
||||||
|
if (trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||||
|
try {
|
||||||
|
logger.player("[AudioBridge] Falling back to in-process ffmpeg decode for: " + trackInfo.url.substring(0, 80));
|
||||||
|
return await this._playViaFfmpeg(conn, trackInfo.url, durationMs, generation);
|
||||||
|
} catch (ffErr) {
|
||||||
|
logger.warn(`[AudioBridge] FFmpeg fallback also failed: ${ffErr?.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw loadErr;
|
||||||
|
}
|
||||||
|
|
||||||
if (generation !== this._playGeneration) {
|
if (generation !== this._playGeneration) {
|
||||||
loaded.stream.destroy();
|
loaded.stream.destroy();
|
||||||
return "stopped";
|
return "stopped";
|
||||||
@@ -158,25 +182,36 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
return "stopped";
|
return "stopped";
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Route C: direct URL — only for tracks WITHOUT an encoded payload
|
/* ── Route C: direct URL — only for tracks WITHOUT an encoded payload
|
||||||
// (Bilibili proxy, radio, direct links). Encoded tracks that reached
|
(Bilibili proxy, radio, direct links). Encoded tracks that reached
|
||||||
// this point get the explicit error below instead of fetching their
|
this point get the explicit error below instead of fetching their
|
||||||
// source page.
|
source page. */
|
||||||
if (!trackInfo.encoded && trackInfo.url && trackInfo.url.startsWith("http")) {
|
if (!trackInfo.encoded && trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||||
logger.player("[AudioBridge] Route 3: Fetching directly via SafeHttp: " + trackInfo.url.substring(0, 80) + "...");
|
logger.player("[AudioBridge] Route 3: Fetching directly via SafeHttp: " + trackInfo.url.substring(0, 80) + "...");
|
||||||
const { openPublicStream } = await import("./SafeHttp.mjs");
|
let stream = null;
|
||||||
const { stream, req } = await openPublicStream(trackInfo.url, {
|
let routed = null;
|
||||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
|
try {
|
||||||
});
|
const { openPublicStream } = await import("./SafeHttp.mjs");
|
||||||
this._sourceStream = stream;
|
const opened = await openPublicStream(trackInfo.url, {
|
||||||
this._sourceReq = req || null;
|
headers: {
|
||||||
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||||
|
"Accept": "*/*",
|
||||||
|
"Icy-MetaData": "0",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
stream = opened.stream;
|
||||||
|
this._sourceStream = stream;
|
||||||
|
this._sourceReq = opened.req || null;
|
||||||
|
routed = await this._routeByMagic(stream);
|
||||||
|
} catch (openErr) {
|
||||||
|
logger.warn("[AudioBridge] Route 3 SafeHttp probe failed (" + openErr.message + "), falling back to in-process ffmpeg...");
|
||||||
|
}
|
||||||
|
|
||||||
const routed = await this._routeByMagic(stream);
|
if (routed?.kind === "webm") {
|
||||||
if (routed.kind === "webm") {
|
|
||||||
logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown"));
|
logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown"));
|
||||||
this._stream = routed.stream;
|
this._stream = routed.stream;
|
||||||
await conn.play(routed.stream);
|
await conn.play(routed.stream);
|
||||||
} else if (routed.kind === "ogg") {
|
} else if (routed?.kind === "ogg") {
|
||||||
logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown"));
|
logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown"));
|
||||||
const oggResult = await this._remuxOggToWebM(routed.stream);
|
const oggResult = await this._remuxOggToWebM(routed.stream);
|
||||||
this._stream = oggResult;
|
this._stream = oggResult;
|
||||||
@@ -206,9 +241,12 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
}
|
}
|
||||||
return "stopped";
|
return "stopped";
|
||||||
} else {
|
} else {
|
||||||
stream.destroy();
|
if (stream) {
|
||||||
this._sourceStream = null;
|
try { stream.destroy(); } catch (_) {}
|
||||||
logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink...");
|
this._sourceStream = null;
|
||||||
|
}
|
||||||
|
const streamKind = routed?.kind || "pcm";
|
||||||
|
logger.player("[AudioBridge] Route 3c: Direct stream is " + streamKind + " (MP3/AAC?) — resolving through Lavalink...");
|
||||||
|
|
||||||
const encoded = this._lavalink
|
const encoded = this._lavalink
|
||||||
? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId)
|
? await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId)
|
||||||
@@ -219,50 +257,70 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
const result3c = await this._playViaTrackstream(conn, trackInfo, { seekMs, durationMs, generation });
|
const result3c = await this._playViaTrackstream(conn, trackInfo, { seekMs, durationMs, generation });
|
||||||
if (result3c !== null) return result3c;
|
if (result3c !== null) return result3c;
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
// Trackstream could not serve the resolved track either — fall
|
/* Trackstream could not serve the resolved track either — fall
|
||||||
// through to loadstream when allowed, else the explicit error.
|
through to loadstream when allowed, else the explicit error. */
|
||||||
if (loadstreamEnabled) {
|
if (loadstreamEnabled) {
|
||||||
const loaded3c = await this._streamFromLoadstream(trackInfo, seekMs, null);
|
try {
|
||||||
if (generation !== this._playGeneration) {
|
const loaded3c = await this._streamFromLoadstream(trackInfo, seekMs, null);
|
||||||
loaded3c.stream.destroy();
|
if (generation !== this._playGeneration) {
|
||||||
|
loaded3c.stream.destroy();
|
||||||
|
return "stopped";
|
||||||
|
}
|
||||||
|
const routed3c = await this._routeByMagic(loaded3c.stream);
|
||||||
|
this._sourceStream = loaded3c.stream;
|
||||||
|
this._sourceReq = loaded3c.req || null;
|
||||||
|
if (routed3c.kind === "webm") {
|
||||||
|
logger.player("[AudioBridge] Route 3c (loadstream): webm/opus passthrough");
|
||||||
|
this._stream = routed3c.stream;
|
||||||
|
await conn.play(routed3c.stream);
|
||||||
|
} else if (routed3c.kind === "ogg") {
|
||||||
|
logger.player("[AudioBridge] Route 3c (loadstream): ogg/opus remux to webm");
|
||||||
|
const oggResult3c = await this._remuxOggToWebM(routed3c.stream);
|
||||||
|
this._stream = oggResult3c;
|
||||||
|
if (durationMs <= 0) durationMs = oggResult3c.getDurationMs();
|
||||||
|
await conn.play(this._stream);
|
||||||
|
} else {
|
||||||
|
logger.player("[AudioBridge] Route 3c (loadstream): PCM -> Opus -> WebM");
|
||||||
|
this._stream = this._buildPcmPipeline(routed3c.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 (Route 3c Lavalink resolve)");
|
||||||
|
return "finished";
|
||||||
|
}
|
||||||
return "stopped";
|
return "stopped";
|
||||||
|
} catch (loadErr3c) {
|
||||||
|
logger.warn("[AudioBridge] Route 3c loadstream failed (" + loadErr3c.message + "), falling back to in-process ffmpeg...");
|
||||||
}
|
}
|
||||||
const routed3c = await this._routeByMagic(loaded3c.stream);
|
|
||||||
this._sourceStream = loaded3c.stream;
|
|
||||||
this._sourceReq = loaded3c.req || null;
|
|
||||||
if (routed3c.kind === "webm") {
|
|
||||||
logger.player("[AudioBridge] Route 3c (loadstream): webm/opus passthrough");
|
|
||||||
this._stream = routed3c.stream;
|
|
||||||
await conn.play(routed3c.stream);
|
|
||||||
} else if (routed3c.kind === "ogg") {
|
|
||||||
logger.player("[AudioBridge] Route 3c (loadstream): ogg/opus remux to webm");
|
|
||||||
const oggResult3c = await this._remuxOggToWebM(routed3c.stream);
|
|
||||||
this._stream = oggResult3c;
|
|
||||||
if (durationMs <= 0) durationMs = oggResult3c.getDurationMs();
|
|
||||||
await conn.play(this._stream);
|
|
||||||
} else {
|
|
||||||
logger.player("[AudioBridge] Route 3c (loadstream): PCM -> Opus -> WebM");
|
|
||||||
this._stream = this._buildPcmPipeline(routed3c.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 (Route 3c Lavalink resolve)");
|
|
||||||
return "finished";
|
|
||||||
}
|
|
||||||
return "stopped";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Route 3d: In-process FFmpeg decode fallback for MP4, AAC, MP3, WAV, and direct media */
|
||||||
|
let ffmpegFailReason = null;
|
||||||
|
try {
|
||||||
|
return await this._playViaFfmpeg(conn, trackInfo.url, durationMs, generation);
|
||||||
|
} catch (ffmpegErr) {
|
||||||
|
ffmpegFailReason = ffmpegErr?.message || "FFmpeg process error";
|
||||||
|
logger.warn("[AudioBridge] Route 3d ffmpeg playback failed: " + ffmpegFailReason);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loadstreamEnabled) {
|
||||||
|
throw new Error(
|
||||||
|
"[AudioBridge] Direct stream is " + streamKind + " (MP3/AAC/PCM?) — NodeLink could not resolve an encoded track " +
|
||||||
|
"and in-process FFmpeg failed" + (ffmpegFailReason ? ": " + ffmpegFailReason : ". Ensure ffmpeg is installed in PATH.")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"[AudioBridge] Direct stream is " + routed.kind + " (MP3/AAC/PCM?) — this format needs server-side decoding. " +
|
"[AudioBridge] Direct stream is " + streamKind + " (MP3/AAC/PCM?) — this format needs server-side decoding or ffmpeg. " +
|
||||||
"Set audio.allowLoadstream to true in config.json (requires a NodeLink exposing /v4/loadstream), " +
|
"Set audio.allowLoadstream to true in config.json (requires a NodeLink exposing /v4/loadstream), " +
|
||||||
"or play a WebM/Opus source."
|
"or ensure ffmpeg is installed in PATH."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
@@ -379,7 +437,13 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
|
|
||||||
let direct;
|
let direct;
|
||||||
try {
|
try {
|
||||||
direct = await this._getTrackstreamUrl(trackInfo);
|
if (trackInfo._prefetchedDirect && (Date.now() - (trackInfo._prefetchedDirect.cachedAt || 0) < 60_000)) {
|
||||||
|
direct = trackInfo._prefetchedDirect;
|
||||||
|
trackInfo._prefetchedDirect = null;
|
||||||
|
logger.player("[AudioBridge] Using pre-fetched trackstream direct URL: " + (trackInfo.title || "unknown"));
|
||||||
|
} else {
|
||||||
|
direct = await this._getTrackstreamUrl(trackInfo);
|
||||||
|
}
|
||||||
if (!direct?.url) throw new Error("trackstream returned no URL");
|
if (!direct?.url) throw new Error("trackstream returned no URL");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (stale()) return "stopped";
|
if (stale()) return "stopped";
|
||||||
@@ -425,8 +489,34 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!/webm|opus/i.test(String(direct.format || ""))) {
|
if (!/webm|opus/i.test(String(direct.format || ""))) {
|
||||||
// Last chance: sniff the direct URL's actual bytes — format strings
|
/* If format is HLS / m3u8 (YouTube Live, SoundCloud live), directly decode via in-process ffmpeg */
|
||||||
// can lie (e.g. "mp4" that is really a WebM/Opus stream).
|
if (/hls|m3u8/i.test(String(direct.format || "")) || (direct.url && direct.url.includes(".m3u8"))) {
|
||||||
|
logger.player("[AudioBridge] trackstream direct URL is HLS (" + (direct.format || "m3u8") + ") — playing via in-process ffmpeg: " + direct.url.substring(0, 80));
|
||||||
|
this._usedTrackstream = true;
|
||||||
|
try {
|
||||||
|
return await this._playViaFfmpeg(conn, direct.url, durationMs, generation);
|
||||||
|
} catch (ffErr) {
|
||||||
|
if (stale()) return "stopped";
|
||||||
|
logger.warn("[AudioBridge] trackstream HLS ffmpeg playback failed: " + ffErr.message);
|
||||||
|
/* If media URL expired (403 Forbidden), try one fresh resolve from Lavalink */
|
||||||
|
if (ffErr.message.includes("403") && trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||||
|
logger.player("[AudioBridge] Stream URL expired (HTTP 403) — refreshing track via Lavalink...");
|
||||||
|
const freshEncoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId).catch(() => null);
|
||||||
|
if (freshEncoded && !stale()) {
|
||||||
|
trackInfo.encoded = freshEncoded;
|
||||||
|
try {
|
||||||
|
const freshDirect = await this._getTrackstreamUrl(trackInfo);
|
||||||
|
if (freshDirect?.url) {
|
||||||
|
return await this._playViaFfmpeg(conn, freshDirect.url, durationMs, generation);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Try in-process byte positioning for WebM/Ogg streams (e.g. if format string lied) */
|
||||||
try {
|
try {
|
||||||
const opened = await this._openPositionedStream(direct.url, seekMs);
|
const opened = await this._openPositionedStream(direct.url, seekMs);
|
||||||
if (stale()) return "stopped";
|
if (stale()) return "stopped";
|
||||||
@@ -436,8 +526,16 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
return result;
|
return result;
|
||||||
} catch (e3) {
|
} catch (e3) {
|
||||||
if (stale()) return "stopped";
|
if (stale()) return "stopped";
|
||||||
logger.player("[AudioBridge] trackstream direct URL not playable in-process (" + e3.message + ")");
|
/* Non-WebM direct stream (AAC, MP4, HLS fallback): play via in-process FFmpeg */
|
||||||
return null;
|
logger.player("[AudioBridge] trackstream direct URL is non-webm (" + (direct.format || e3.message) + ") — playing via in-process ffmpeg: " + direct.url.substring(0, 80));
|
||||||
|
this._usedTrackstream = true;
|
||||||
|
try {
|
||||||
|
return await this._playViaFfmpeg(conn, direct.url, durationMs, generation);
|
||||||
|
} catch (ffErr) {
|
||||||
|
if (stale()) return "stopped";
|
||||||
|
logger.warn("[AudioBridge] trackstream ffmpeg fallback failed: " + ffErr.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -449,9 +547,14 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
(trackInfo.title || "unknown"));
|
(trackInfo.title || "unknown"));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (seekMs > 0 || durationMs <= 0) {
|
if (durationMs <= 0) {
|
||||||
// Streamed route: byte-positioned for seeks; also gives an
|
/* Live stream: decode via in-process FFmpeg to seek to the live edge */
|
||||||
// end-of-stream handle when the duration is unknown.
|
logger.player("[AudioBridge] Live stream (duration <= 0) — playing via in-process ffmpeg: " + direct.url.substring(0, 80));
|
||||||
|
return await this._playViaFfmpeg(conn, direct.url, durationMs, generation);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (seekMs > 0) {
|
||||||
|
/* Streamed route: byte-positioned for seeks */
|
||||||
const opened = await this._openPositionedStream(direct.url, seekMs);
|
const opened = await this._openPositionedStream(direct.url, seekMs);
|
||||||
if (stale()) {
|
if (stale()) {
|
||||||
opened.stream.destroy();
|
opened.stream.destroy();
|
||||||
@@ -637,6 +740,10 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
if (this._sourceReq) {
|
if (this._sourceReq) {
|
||||||
try { this._sourceReq.destroy(); } catch (_) {}
|
try { this._sourceReq.destroy(); } catch (_) {}
|
||||||
}
|
}
|
||||||
|
if (this._ffmpegProc) {
|
||||||
|
try { this._ffmpegProc.kill("SIGKILL"); } catch (_) {}
|
||||||
|
this._ffmpegProc = null;
|
||||||
|
}
|
||||||
this._stream = null;
|
this._stream = null;
|
||||||
this._encoder = null;
|
this._encoder = null;
|
||||||
this._sourceStream = null;
|
this._sourceStream = null;
|
||||||
@@ -644,6 +751,128 @@ export class FluxerAudioBridge extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Stop playback, release the voice connection, and remove all listeners. */
|
/** Stop playback, release the voice connection, and remove all listeners. */
|
||||||
|
/**
|
||||||
|
* Decode and play direct audio/video via in-process ffmpeg into the PCM-Opus pipeline.
|
||||||
|
* @param {object} conn - Fluxer voice connection
|
||||||
|
* @param {string} url - Direct media stream URL
|
||||||
|
* @param {number} durationMs - Duration in ms (0 for continuous stream)
|
||||||
|
* @param {number} generation - Play generation counter
|
||||||
|
* @returns {Promise<"finished"|"stopped">}
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
async _playViaFfmpeg(conn, url, durationMs, generation) {
|
||||||
|
logger.player("[AudioBridge] Decoding media via in-process ffmpeg: " + url.substring(0, 80));
|
||||||
|
const { spawn } = await import("node:child_process");
|
||||||
|
let headers = "";
|
||||||
|
if (url.includes("soundcloud.cloud") || url.includes("sndcdn.com")) {
|
||||||
|
headers = "Origin: https://soundcloud.com\r\nReferer: https://soundcloud.com/\r\n";
|
||||||
|
} else if (url.includes("googlevideo.com") || url.includes("youtube.com") || url.includes("youtu.be")) {
|
||||||
|
headers = "Origin: https://www.youtube.com\r\nReferer: https://www.youtube.com/\r\n";
|
||||||
|
}
|
||||||
|
const ffmpegArgs = [
|
||||||
|
"-re",
|
||||||
|
];
|
||||||
|
if (headers) {
|
||||||
|
ffmpegArgs.push("-headers", headers);
|
||||||
|
}
|
||||||
|
ffmpegArgs.push(
|
||||||
|
"-user_agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||||
|
"-reconnect", "1",
|
||||||
|
"-reconnect_streamed", "1",
|
||||||
|
"-reconnect_delay_max", "5",
|
||||||
|
);
|
||||||
|
ffmpegArgs.push(
|
||||||
|
"-i", url,
|
||||||
|
"-vn",
|
||||||
|
"-filter:a", "volume=1.0",
|
||||||
|
"-f", "s16le",
|
||||||
|
"-ar", "48000",
|
||||||
|
"-ac", "2",
|
||||||
|
"pipe:1"
|
||||||
|
);
|
||||||
|
const proc = spawn("ffmpeg", ffmpegArgs, { stdio: ["ignore", "pipe", "pipe"] });
|
||||||
|
this._ffmpegProc = proc;
|
||||||
|
|
||||||
|
let hasOutput = false;
|
||||||
|
let stderrBuf = "";
|
||||||
|
let chunkCount = 0;
|
||||||
|
let spawnError = null;
|
||||||
|
|
||||||
|
proc.stdout.on("data", (chunk) => {
|
||||||
|
chunkCount++;
|
||||||
|
if (chunkCount === 1) {
|
||||||
|
hasOutput = true;
|
||||||
|
logger.player("[AudioBridge] FFmpeg output stream started (" + chunk.length + " bytes)");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
proc.on("error", (err) => {
|
||||||
|
spawnError = err;
|
||||||
|
logger.warn("[AudioBridge] FFmpeg process error: " + err.message);
|
||||||
|
});
|
||||||
|
proc.stderr.on("data", (chunk) => {
|
||||||
|
/* Buffer trailing stderr for error reporting on non-zero exit; avoid logging in-flight progress lines */
|
||||||
|
stderrBuf = (stderrBuf + chunk.toString()).slice(-600);
|
||||||
|
});
|
||||||
|
|
||||||
|
this._stream = this._buildPcmPipeline(proc.stdout);
|
||||||
|
await conn.play(this._stream);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
let settled = false;
|
||||||
|
const doReject = (err) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
reject(err);
|
||||||
|
};
|
||||||
|
const doResolve = () => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
resolve();
|
||||||
|
};
|
||||||
|
|
||||||
|
if (spawnError && !hasOutput) {
|
||||||
|
doReject(spawnError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
proc.once("error", (err) => {
|
||||||
|
if (!hasOutput) {
|
||||||
|
doReject(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
proc.once("close", (code, signal) => {
|
||||||
|
if (!hasOutput && code !== 0 && !this._stopped) {
|
||||||
|
const errLine = stderrBuf.split("\n").filter(Boolean).pop() || "Process exited with code " + code;
|
||||||
|
logger.warn("[AudioBridge] FFmpeg non-zero close (code=" + code + "): " + errLine);
|
||||||
|
doReject(new Error("[FFmpeg] " + errLine));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
logger.player("[AudioBridge] FFmpeg process closed cleanly (code=" + code + ")");
|
||||||
|
doResolve();
|
||||||
|
});
|
||||||
|
|
||||||
|
this._awaitEnd(durationMs).then(() => {
|
||||||
|
if (!hasOutput && !this._stopped) {
|
||||||
|
/* Zero output: wait for proc.close to reject with the actual error */
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
doResolve();
|
||||||
|
}, doReject);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
if (this._playing && !this._stopped) {
|
||||||
|
this._playing = false;
|
||||||
|
logger.player("[AudioBridge] Track finished naturally (in-process ffmpeg)");
|
||||||
|
return "finished";
|
||||||
|
}
|
||||||
|
return "stopped";
|
||||||
|
}
|
||||||
|
|
||||||
destroy() {
|
destroy() {
|
||||||
this.stop();
|
this.stop();
|
||||||
this._conn = null;
|
this._conn = null;
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ const MAX_REDIRECTS = 5;
|
|||||||
/** @type {number} @description Timeout (ms) for HTTP requests to Lavalink REST endpoints (trackstream, loadtracks JSON). */
|
/** @type {number} @description Timeout (ms) for HTTP requests to Lavalink REST endpoints (trackstream, loadtracks JSON). */
|
||||||
const REST_REQUEST_TIMEOUT_MS = 15_000;
|
const REST_REQUEST_TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
/** @type {number} @description Timeout (ms) to wait for the first byte from loadstream (Lavalink may need time to resolve HLS/external streams). */
|
/** @type {number} @description Timeout (ms) to wait for the first byte from loadstream (reduced from 60s to 12s so dead node connections fail fast and fall back). */
|
||||||
const LOADSTREAM_CONNECT_TIMEOUT_MS = 60_000;
|
const LOADSTREAM_CONNECT_TIMEOUT_MS = 12_000;
|
||||||
|
|
||||||
/** @type {number} @description Idle timeout (ms) once loadstream data is flowing — if no data arrives for this long, abort. */
|
/** @type {number} @description Idle timeout (ms) once loadstream data is flowing — if no data arrives for this long, abort. */
|
||||||
const LOADSTREAM_IDLE_TIMEOUT_MS = 30_000;
|
const LOADSTREAM_IDLE_TIMEOUT_MS = 30_000;
|
||||||
@@ -51,7 +51,7 @@ const HttpStreams = {
|
|||||||
port: urlObj.port,
|
port: urlObj.port,
|
||||||
path: urlObj.pathname + urlObj.search,
|
path: urlObj.pathname + urlObj.search,
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
|
headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", ...headers },
|
||||||
}, (res) => {
|
}, (res) => {
|
||||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||||
res.resume();
|
res.resume();
|
||||||
@@ -80,7 +80,10 @@ const HttpStreams = {
|
|||||||
});
|
});
|
||||||
|
|
||||||
req.on("socket", (socket) => {
|
req.on("socket", (socket) => {
|
||||||
socket.on("error", () => {});
|
if (!socket._hasRemixErrorHandler) {
|
||||||
|
socket._hasRemixErrorHandler = true;
|
||||||
|
socket.on("error", () => {});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
req.on("error", reject);
|
req.on("error", reject);
|
||||||
req.setTimeout(timeoutMs, () => {
|
req.setTimeout(timeoutMs, () => {
|
||||||
@@ -125,7 +128,7 @@ const HttpStreams = {
|
|||||||
port: urlObj.port,
|
port: urlObj.port,
|
||||||
path: urlObj.pathname + urlObj.search,
|
path: urlObj.pathname + urlObj.search,
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
|
headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", ...headers },
|
||||||
}, (res) => {
|
}, (res) => {
|
||||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
||||||
@@ -170,7 +173,10 @@ const HttpStreams = {
|
|||||||
});
|
});
|
||||||
|
|
||||||
req.on("socket", (socket) => {
|
req.on("socket", (socket) => {
|
||||||
socket.on("error", () => {});
|
if (!socket._hasRemixErrorHandler) {
|
||||||
|
socket._hasRemixErrorHandler = true;
|
||||||
|
socket.on("error", () => {});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
req.on("error", (err) => {
|
req.on("error", (err) => {
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
/**
|
||||||
|
* @module src/music/audio/RadioMetadata
|
||||||
|
* @description Out-of-band Shoutcast and Icecast metadata extractor.
|
||||||
|
* Polls stream headers and interleaved ICY metadata frames or Icecast status
|
||||||
|
* JSON out-of-band without corrupting or interfering with audio streaming.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import http from "node:http";
|
||||||
|
import https from "node:https";
|
||||||
|
import { URL } from "node:url";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract live song title from Shoutcast/Icecast ICY metadata frames out-of-band.
|
||||||
|
* @param {string} url - Stream URL to probe.
|
||||||
|
* @param {number} [timeoutMs=6000] - Socket timeout in milliseconds.
|
||||||
|
* @returns {Promise<string|null>}
|
||||||
|
*/
|
||||||
|
export function fetchIcyStreamTitle(url, timeoutMs = 6000) {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
try {
|
||||||
|
const parsed = new URL(url);
|
||||||
|
const client = parsed.protocol === "https:" ? https : http;
|
||||||
|
const req = client.get(parsed, {
|
||||||
|
headers: {
|
||||||
|
"Icy-MetaData": "1",
|
||||||
|
"User-Agent": "FluxerBot/1.0 (Radio Title Poller)",
|
||||||
|
},
|
||||||
|
}, (res) => {
|
||||||
|
const metaint = parseInt(res.headers["icy-metaint"], 10);
|
||||||
|
if (!metaint || isNaN(metaint)) {
|
||||||
|
req.destroy();
|
||||||
|
return resolve(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
let totalBytes = 0;
|
||||||
|
let metaLen = 0;
|
||||||
|
let metaBuffer = null;
|
||||||
|
let metaBytesRead = 0;
|
||||||
|
let state = 0;
|
||||||
|
|
||||||
|
res.on("data", (chunk) => {
|
||||||
|
let pos = 0;
|
||||||
|
while (pos < chunk.length) {
|
||||||
|
if (state === 0) {
|
||||||
|
const needed = metaint - totalBytes;
|
||||||
|
const available = chunk.length - pos;
|
||||||
|
if (available < needed) {
|
||||||
|
totalBytes += available;
|
||||||
|
pos = chunk.length;
|
||||||
|
} else {
|
||||||
|
pos += needed;
|
||||||
|
totalBytes = 0;
|
||||||
|
state = 1;
|
||||||
|
}
|
||||||
|
} else if (state === 1) {
|
||||||
|
metaLen = chunk[pos] * 16;
|
||||||
|
pos += 1;
|
||||||
|
if (metaLen === 0) {
|
||||||
|
state = 0;
|
||||||
|
} else {
|
||||||
|
metaBuffer = Buffer.alloc(metaLen);
|
||||||
|
metaBytesRead = 0;
|
||||||
|
state = 2;
|
||||||
|
}
|
||||||
|
} else if (state === 2) {
|
||||||
|
const needed = metaLen - metaBytesRead;
|
||||||
|
const available = chunk.length - pos;
|
||||||
|
const toCopy = Math.min(needed, available);
|
||||||
|
chunk.copy(metaBuffer, metaBytesRead, pos, pos + toCopy);
|
||||||
|
metaBytesRead += toCopy;
|
||||||
|
pos += toCopy;
|
||||||
|
if (metaBytesRead >= metaLen) {
|
||||||
|
const metaStr = metaBuffer.toString("utf8");
|
||||||
|
const match = metaStr.match(/StreamTitle='([^']*)'/i);
|
||||||
|
req.destroy();
|
||||||
|
return resolve(match && match[1] ? match[1].trim() : null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
res.on("error", () => {
|
||||||
|
try { req.destroy(); } catch (_) {}
|
||||||
|
resolve(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
req.on("error", () => resolve(null));
|
||||||
|
req.setTimeout(timeoutMs, () => {
|
||||||
|
try { req.destroy(); } catch (_) {}
|
||||||
|
resolve(null);
|
||||||
|
});
|
||||||
|
} catch (_) {
|
||||||
|
resolve(null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch current track title from Icecast status-json.xsl endpoint.
|
||||||
|
* @param {string} streamUrl - Stream URL.
|
||||||
|
* @param {number} [timeoutMs=3000] - Request timeout.
|
||||||
|
* @returns {Promise<string|null>}
|
||||||
|
*/
|
||||||
|
export async function fetchIcecastJsonTitle(streamUrl, timeoutMs = 3000) {
|
||||||
|
try {
|
||||||
|
const parsed = new URL(streamUrl);
|
||||||
|
const jsonUrl = `${parsed.protocol}//${parsed.host}/status-json.xsl`;
|
||||||
|
const res = await fetch(jsonUrl, {
|
||||||
|
signal: AbortSignal.timeout(timeoutMs),
|
||||||
|
headers: { "User-Agent": "FluxerBot/1.0" },
|
||||||
|
});
|
||||||
|
if (!res.ok) return null;
|
||||||
|
const data = await res.json();
|
||||||
|
const sources = Array.isArray(data?.icestats?.source)
|
||||||
|
? data.icestats.source
|
||||||
|
: [data?.icestats?.source].filter(Boolean);
|
||||||
|
const mount = parsed.pathname;
|
||||||
|
const match = sources.find((s) => s.listenurl?.endsWith(mount) || s.server_name);
|
||||||
|
const raw = match?.title || match?.yp_currently_playing;
|
||||||
|
return raw && typeof raw === "string" ? raw.trim() : null;
|
||||||
|
} catch (_) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve radio stream title using out-of-band ICY frames with status-json fallback.
|
||||||
|
* @param {string} url - Stream URL.
|
||||||
|
* @param {number} [timeoutMs=6000] - Timeout.
|
||||||
|
* @returns {Promise<string|null>}
|
||||||
|
*/
|
||||||
|
export async function fetchRadioStreamTitle(url, timeoutMs = 6000) {
|
||||||
|
if (!url || typeof url !== "string") return null;
|
||||||
|
const icyTitle = await fetchIcyStreamTitle(url, timeoutMs);
|
||||||
|
if (icyTitle) return icyTitle;
|
||||||
|
return fetchIcecastJsonTitle(url, 3000);
|
||||||
|
}
|
||||||
@@ -131,7 +131,7 @@ function requestOnce(u, { headers, lookup, connectTimeoutMs, idleTimeoutMs }) {
|
|||||||
method: "GET",
|
method: "GET",
|
||||||
agent: false,
|
agent: false,
|
||||||
lookup,
|
lookup,
|
||||||
headers: { Accept: "*/*", "Accept-Encoding": "identity", ...headers },
|
headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", Accept: "*/*", "Accept-Encoding": "identity", ...headers },
|
||||||
}, (res) => {
|
}, (res) => {
|
||||||
settled = true;
|
settled = true;
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ const StreamPipeline = {
|
|||||||
return resolve();
|
return resolve();
|
||||||
}
|
}
|
||||||
const onEnd = () => {
|
const onEnd = () => {
|
||||||
|
logger.player("[AudioBridge] Stream onEnd reached (durationMs=" + durationMs + ", playing=" + this._playing + ", stopped=" + this._stopped + ")");
|
||||||
if (durationMs > 0 && this._playing && !this._stopped) return;
|
if (durationMs > 0 && this._playing && !this._stopped) return;
|
||||||
resolve();
|
resolve();
|
||||||
};
|
};
|
||||||
@@ -349,7 +350,7 @@ const StreamPipeline = {
|
|||||||
try {
|
try {
|
||||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||||
if (!nlInfo) {
|
if (!nlInfo) {
|
||||||
logger.warn("[AudioBridge] _resolveUrlViaLavalink: no NodeLink info");
|
logger.player("[AudioBridge] _resolveUrlViaLavalink: no NodeLink info");
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -375,11 +376,13 @@ const StreamPipeline = {
|
|||||||
return encoded;
|
return encoded;
|
||||||
}
|
}
|
||||||
|
|
||||||
const loadType = body?.loadType ?? body?.data?.loadType;
|
const loadType = body?.loadType ?? body?.data?.loadType ?? "unknown";
|
||||||
logger.warn("[AudioBridge] Lavalink loadtracks returned no playable track (loadType=" + loadType + ")");
|
const errorMsg = body?.data?.message ?? body?.exception?.message ?? body?.message;
|
||||||
|
const details = errorMsg ? `: ${errorMsg}` : "";
|
||||||
|
logger.player("[AudioBridge] Lavalink loadtracks returned no playable track (loadType=" + loadType + details + ")");
|
||||||
return null;
|
return null;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[AudioBridge] _resolveUrlViaLavalink failed: " + e.message);
|
logger.player("[AudioBridge] _resolveUrlViaLavalink failed: " + e.message);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -327,10 +327,8 @@ export class StreamPositioner extends Transform {
|
|||||||
|
|
||||||
// Emit: cluster header (+ Timecode) then from the first surviving block on.
|
// Emit: cluster header (+ Timecode) then from the first surviving block on.
|
||||||
const skipped = firstKeptOffset - firstBlockRegionStart;
|
const skipped = firstKeptOffset - firstBlockRegionStart;
|
||||||
this._consume(firstKeptOffset); // buffer now starts at the surviving block
|
|
||||||
if (skipped > 0) {
|
if (skipped > 0) {
|
||||||
// Blocks were trimmed — the original size vint would now overstate the
|
this._consume(firstKeptOffset);
|
||||||
// payload and desync the demuxer. Rebuild the header with the real size.
|
|
||||||
const keptPayload =
|
const keptPayload =
|
||||||
(firstBlockRegionStart - headerLen) + (cluster.length - firstKeptOffset);
|
(firstBlockRegionStart - headerLen) + (cluster.length - firstKeptOffset);
|
||||||
this.push(Buffer.concat([
|
this.push(Buffer.concat([
|
||||||
@@ -451,19 +449,18 @@ export class StreamPositioner extends Transform {
|
|||||||
if (pageLen > MAX_OGG_PAGE_BYTES) { this._startPassthrough(); return; }
|
if (pageLen > MAX_OGG_PAGE_BYTES) { this._startPassthrough(); return; }
|
||||||
if (this._buf.length < pageLen) return;
|
if (this._buf.length < pageLen) return;
|
||||||
|
|
||||||
const granule = Number(this._buf.readBigUInt64LE(6));
|
const rawGranule = this._buf.readBigUInt64LE(6);
|
||||||
const page = Buffer.from(this._buf.subarray(0, pageLen));
|
const page = Buffer.from(this._buf.subarray(0, pageLen));
|
||||||
this._consume(pageLen);
|
this._consume(pageLen);
|
||||||
|
|
||||||
if (this._oggPagesKept < 2) {
|
if (this._oggPagesKept < 2) {
|
||||||
// OpusHead (BOS) + OpusTags pages must survive for the demuxer.
|
|
||||||
this._oggPagesKept++;
|
this._oggPagesKept++;
|
||||||
this.push(page);
|
this.push(page);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const isFiller = granule === -1n || granule === 0xffffffffffffffffn;
|
const isFiller = rawGranule === 0xffffffffffffffffn;
|
||||||
if (!isFiller && granule >= this._targetMs * OPUS_SAMPLE_RATE) {
|
if (!isFiller && Number(rawGranule) >= this._targetMs * OPUS_SAMPLE_RATE) {
|
||||||
for (const p of this._oggReplay) this.push(p);
|
for (const p of this._oggReplay) this.push(p);
|
||||||
this._oggReplay = [];
|
this._oggReplay = [];
|
||||||
this._startPassthrough(page);
|
this._startPassthrough(page);
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { Utils } from "../../utils/Utils.mjs";
|
import { Utils, cleanId } from "../../utils/Utils.mjs";
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
import meta from "../probe.mjs";
|
import meta from "../probe.mjs";
|
||||||
|
|
||||||
@@ -73,12 +73,12 @@ const DisplayMixin = {
|
|||||||
? `[Radio]: ${vid.title} - ${vid.author?.url || ""}`
|
? `[Radio]: ${vid.title} - ${vid.author?.url || ""}`
|
||||||
: `[Radio] [${vid.title} by ${vid.author?.name || "Unknown"}](${vid.author?.url || ""})`;
|
: `[Radio] [${vid.title} by ${vid.author?.name || "Unknown"}](${vid.author?.url || ""})`;
|
||||||
}
|
}
|
||||||
if (vid.type === "external" || vid.type === "stream") {
|
if (vid.type === "external" || vid.type === "stream" || vid.type === "attachment") {
|
||||||
return code
|
return code
|
||||||
? `${vid.title} - ${vid.url}`
|
? `${vid.title} - ${vid.url}`
|
||||||
: `[${vid.title}](${vid.url})`;
|
: `[${vid.title}](${vid.url})`;
|
||||||
}
|
}
|
||||||
if (vid.isLive || vid.type === "livestream") {
|
if (vid.isLive || vid.isStream || vid.type === "livestream") {
|
||||||
const link = vid.url || "";
|
const link = vid.url || "";
|
||||||
return code
|
return code
|
||||||
? `${vid.title} (LIVE) - ${link}`
|
? `${vid.title} (LIVE) - ${link}`
|
||||||
@@ -185,6 +185,9 @@ const DisplayMixin = {
|
|||||||
if (current.type === "radio") {
|
if (current.type === "radio") {
|
||||||
sourceName = this._t("responses.play.sourceRadio");
|
sourceName = this._t("responses.play.sourceRadio");
|
||||||
sourceIcon = "📻";
|
sourceIcon = "📻";
|
||||||
|
} else if (current.type === "attachment" || current.url?.includes("fluxerusercontent.com") || current.url?.includes("cdn.fluxer.app")) {
|
||||||
|
sourceName = this._t("responses.play.sourceAttachment");
|
||||||
|
sourceIcon = "📎";
|
||||||
} else if (current.spotifyUrl || current.type === "spotify") {
|
} else if (current.spotifyUrl || current.type === "spotify") {
|
||||||
sourceName = this._t("responses.play.sourceSpotify");
|
sourceName = this._t("responses.play.sourceSpotify");
|
||||||
sourceIcon = "🟢";
|
sourceIcon = "🟢";
|
||||||
@@ -214,15 +217,19 @@ const DisplayMixin = {
|
|||||||
let radioLiveTitle = null;
|
let radioLiveTitle = null;
|
||||||
|
|
||||||
if (current.type === "radio") {
|
if (current.type === "radio") {
|
||||||
try {
|
radioLiveTitle = current.currentStreamTitle || null;
|
||||||
const data = await meta(current.url);
|
if (!radioLiveTitle) {
|
||||||
radioLiveTitle = data?.title || null;
|
try {
|
||||||
textMsg = `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n${current.description || ""}\n\n🎵 Now playing: ${radioLiveTitle || "Unknown"}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`;
|
const data = await meta(current.url);
|
||||||
} catch (_) {
|
radioLiveTitle = data?.title || null;
|
||||||
/* Radio live metadata probe is optional — gracefully fall back to station display */
|
} catch (_) {
|
||||||
textMsg = `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`;
|
/* Radio live metadata probe is optional — gracefully fall back to station display */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if (current.type === "external" || current.type === "stream") {
|
if (radioLiveTitle) current.currentStreamTitle = radioLiveTitle;
|
||||||
|
const titleLine = radioLiveTitle ? `\n\n🎵 Now playing: ${radioLiveTitle}` : "";
|
||||||
|
textMsg = `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n${current.description || ""}${titleLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`;
|
||||||
|
} else if (current.type === "external" || current.type === "stream" || current.type === "attachment") {
|
||||||
const totalMs = this._getTrackDurationMs(current);
|
const totalMs = this._getTrackDurationMs(current);
|
||||||
const progressLine = totalMs > 0 ? `\n${this._createProgressBar(20)}` : "";
|
const progressLine = totalMs > 0 ? `\n${this._createProgressBar(20)}` : "";
|
||||||
textMsg = `${vcLine}🎵 **[${current.title}](${current.url})** by ${artistName}${progressLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`;
|
textMsg = `${vcLine}🎵 **[${current.title}](${current.url})** by ${artistName}${progressLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`;
|
||||||
@@ -425,12 +432,13 @@ const DisplayMixin = {
|
|||||||
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
||||||
|
|
||||||
if (s.type === "radio") {
|
if (s.type === "radio") {
|
||||||
|
const liveTitle = s.currentStreamTitle ? `🎶 **Now Playing:** ${s.currentStreamTitle}\n\n` : "";
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(0xe9196c)
|
.setColor(0xe9196c)
|
||||||
.setAuthor({ name: `📻 ${this._t("responses.play.autoNowPlaying")}` })
|
.setAuthor({ name: `📻 ${this._t("responses.play.autoNowPlaying")}` })
|
||||||
.setTitle(Utils.truncate(s.title || this._t("responses.play.sourceRadio"), 250))
|
.setTitle(Utils.truncate(s.title || this._t("responses.play.sourceRadio"), 250))
|
||||||
.setURL(s.author?.url || s.url || undefined)
|
.setURL(s.author?.url || s.url || undefined)
|
||||||
.setDescription(`🎵 **${s.description || this._t("responses.play.liveBroadcast")}**\n\n🔊 <#${this._channelId}>`)
|
.setDescription(`${liveTitle}🎵 **${s.description || this._t("responses.play.liveBroadcast")}**\n\n🔊 <#${this._channelId}>`)
|
||||||
.setFooter({ text: this._t("responses.play.controlsHint", { prefix }) });
|
.setFooter({ text: this._t("responses.play.controlsHint", { prefix }) });
|
||||||
if (s.thumbnail) embed.setThumbnail(s.thumbnail);
|
if (s.thumbnail) embed.setThumbnail(s.thumbnail);
|
||||||
this.emit("message", { embeds: [embed] });
|
this.emit("message", { embeds: [embed] });
|
||||||
|
|||||||
@@ -11,8 +11,10 @@
|
|||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { ERROR_COLOR } from "../../utils/UI.mjs";
|
import { ERROR_COLOR } from "../../utils/UI.mjs";
|
||||||
import { Utils, cleanId } from "../../utils/Utils.mjs";
|
import { Utils, cleanId } from "../../utils/Utils.mjs";
|
||||||
|
import { isPlayerConnectionDead } from "../../utils/Helpers247.mjs";
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
import { getBilibiliStreamUrl } from "../bilibili/index.mjs";
|
import { getBilibiliStreamUrl } from "../bilibili/index.mjs";
|
||||||
|
import { fetchRadioStreamTitle } from "../audio/RadioMetadata.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {object}
|
* @type {object}
|
||||||
@@ -32,6 +34,7 @@ const PlaybackMixin = {
|
|||||||
this._clearTrackEndTimer();
|
this._clearTrackEndTimer();
|
||||||
|
|
||||||
if (songData.type === "radio") {
|
if (songData.type === "radio") {
|
||||||
|
this._stopRadioTitlePolling();
|
||||||
logger.player(`[Player] Radio track ended: ${songData.title}`);
|
logger.player(`[Player] Radio track ended: ${songData.title}`);
|
||||||
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
|
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
|
||||||
this.queue.current = null;
|
this.queue.current = null;
|
||||||
@@ -54,6 +57,10 @@ const PlaybackMixin = {
|
|||||||
* @returns {number}
|
* @returns {number}
|
||||||
*/
|
*/
|
||||||
_getTrackDurationMs(track) {
|
_getTrackDurationMs(track) {
|
||||||
|
/* Live streams have unbounded/indeterminate length: duration is always 0 */
|
||||||
|
if (track?.isLive || track?.isStream || track?.info?.isStream || track?.info?.isLive || track?.type === "livestream" || track?.type === "radio") {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
if (track?._durationMs != null && track._durationMs > 0) {
|
if (track?._durationMs != null && track._durationMs > 0) {
|
||||||
return track._durationMs;
|
return track._durationMs;
|
||||||
}
|
}
|
||||||
@@ -69,7 +76,7 @@ const PlaybackMixin = {
|
|||||||
if (track?.info?.length) return track.info.length;
|
if (track?.info?.length) return track.info.length;
|
||||||
if (track?.info?.duration != null) {
|
if (track?.info?.duration != null) {
|
||||||
if (typeof track.info.duration === "number") return track.info.duration;
|
if (typeof track.info.duration === "number") return track.info.duration;
|
||||||
if (typeof track.info.duration === "object" && track.info.duration.seconds != null)
|
if (typeof track.info.duration === "object" && track.info.duration?.seconds != null)
|
||||||
return track.info.duration.seconds * 1000;
|
return track.info.duration.seconds * 1000;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
@@ -182,6 +189,15 @@ const PlaybackMixin = {
|
|||||||
this._stopInactivityTimer();
|
this._stopInactivityTimer();
|
||||||
this._wasRadio = songData.type === "radio";
|
this._wasRadio = songData.type === "radio";
|
||||||
|
|
||||||
|
if ((!this._voiceConn || (typeof this._voiceConn.isConnected === "function" && !this._voiceConn.isConnected())) && this._channelId && !this.leaving && !this._destroyed) {
|
||||||
|
try {
|
||||||
|
logger.player(`[Player] Reconnecting voice channel before play: ${this._channelId}`);
|
||||||
|
await this.join(this._channelId);
|
||||||
|
} catch (joinErr) {
|
||||||
|
logger.warn(`[Player] Reconnect before play failed: ${joinErr.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!this._voiceConn || this.leaving) return;
|
if (!this._voiceConn || this.leaving) return;
|
||||||
|
|
||||||
if (this._voiceConn) {
|
if (this._voiceConn) {
|
||||||
@@ -221,7 +237,10 @@ const PlaybackMixin = {
|
|||||||
if (!dup) this.announceSong(songData);
|
if (!dup) this.announceSong(songData);
|
||||||
else logger.player(`[Player:${this._guildId}] Suppressed duplicate now-playing for: ${songData.title}`);
|
else logger.player(`[Player:${this._guildId}] Suppressed duplicate now-playing for: ${songData.title}`);
|
||||||
this._lastAnnounce = { key: songData.url || songData.title, at: now };
|
this._lastAnnounce = { key: songData.url || songData.title, at: now };
|
||||||
if (songData.type === "radio") this._radioAnnounced = true;
|
if (songData.type === "radio") {
|
||||||
|
this._radioAnnounced = true;
|
||||||
|
this._startRadioTitlePolling(songData);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
this._skipVotes.clear();
|
this._skipVotes.clear();
|
||||||
this.emit("startplay", songData);
|
this.emit("startplay", songData);
|
||||||
@@ -280,7 +299,32 @@ const PlaybackMixin = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error("[Player] Play error:", err.message);
|
const errMsg = err?.message ?? String(err);
|
||||||
|
logger.error("[Player] Play error:", errMsg);
|
||||||
|
|
||||||
|
/* In-place recovery if playback failed due to a lost or dead voice connection */
|
||||||
|
const isVoiceLost = isPlayerConnectionDead(this)
|
||||||
|
|| /track publication timed out|No voice connection|Voice connection timeout/i.test(errMsg);
|
||||||
|
|
||||||
|
if (isVoiceLost && !this.leaving && !this._destroyed) {
|
||||||
|
logger.player(`[Player:${this._guildId}] Voice connection lost during playback — attempting in-place voice recovery`);
|
||||||
|
const cId = cleanId(this._channelId ?? this._home247Channel ?? "");
|
||||||
|
if (cId) {
|
||||||
|
this._voiceConn = null;
|
||||||
|
this.connection = null;
|
||||||
|
try {
|
||||||
|
await this.join(cId);
|
||||||
|
if (this._voiceConn) {
|
||||||
|
this._consecutiveErrors = 0;
|
||||||
|
await this._playTrackViaBridge(songData, { seekSeconds: seekSec });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (recErr) {
|
||||||
|
logger.player(`[Player:${this._guildId}] In-place voice recovery failed: ${recErr?.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!this._skipping && !this.leaving && !this._paused && songData.type !== "radio") {
|
if (!this._skipping && !this.leaving && !this._paused && songData.type !== "radio") {
|
||||||
const pfx = this._getPrefix?.(this._guildId) ?? "%";
|
const pfx = this._getPrefix?.(this._guildId) ?? "%";
|
||||||
const playErrEmbed = new EmbedBuilder()
|
const playErrEmbed = new EmbedBuilder()
|
||||||
@@ -336,7 +380,7 @@ const PlaybackMixin = {
|
|||||||
bridgeUrl = stream.url;
|
bridgeUrl = stream.url;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!songData.encoded && bridgeUrl && bridgeUrl.startsWith("http") && this._lavalink && songData.type !== "external") {
|
if (!songData.encoded && bridgeUrl && bridgeUrl.startsWith("http") && this._lavalink && songData.type !== "external" && songData.type !== "attachment") {
|
||||||
try {
|
try {
|
||||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||||
if (nlInfo) {
|
if (nlInfo) {
|
||||||
@@ -372,6 +416,19 @@ const PlaybackMixin = {
|
|||||||
const totalMs = this._getTrackDurationMs(songData);
|
const totalMs = this._getTrackDurationMs(songData);
|
||||||
const durationMs = totalMs > 0 ? Math.max(0, totalMs - seekMs) : 0;
|
const durationMs = totalMs > 0 ? Math.max(0, totalMs - seekMs) : 0;
|
||||||
|
|
||||||
|
const myPlayGen = (this._playSessionGen = (this._playSessionGen ?? 0) + 1);
|
||||||
|
|
||||||
|
this._clearPrefetchTimer();
|
||||||
|
if (durationMs > 20_000) {
|
||||||
|
this._prefetchTimer = setTimeout(() => {
|
||||||
|
this._prefetchNextTrack().catch(() => {});
|
||||||
|
}, Math.max(2_000, durationMs - 15_000));
|
||||||
|
} else if (durationMs > 0) {
|
||||||
|
this._prefetchTimer = setTimeout(() => {
|
||||||
|
this._prefetchNextTrack().catch(() => {});
|
||||||
|
}, 1_000);
|
||||||
|
}
|
||||||
|
|
||||||
const result = await this._audioBridge.play(this._voiceConn, {
|
const result = await this._audioBridge.play(this._voiceConn, {
|
||||||
encoded: songData.encoded,
|
encoded: songData.encoded,
|
||||||
url: bridgeUrl,
|
url: bridgeUrl,
|
||||||
@@ -384,9 +441,25 @@ const PlaybackMixin = {
|
|||||||
filterPayload: this.activeFilterPayload || null,
|
filterPayload: this.activeFilterPayload || null,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this._clearPrefetchTimer();
|
||||||
|
|
||||||
|
if (myPlayGen !== this._playSessionGen) {
|
||||||
|
/* Another track was started or stopped while this was playing — drop stale completion */
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result === null) {
|
||||||
|
throw new Error("Playback failed to start for track: " + (songData?.title ?? "unknown"));
|
||||||
|
}
|
||||||
|
|
||||||
if (result === "finished" && !this._skipping && !this.leaving && !this._paused) {
|
if (result === "finished" && !this._skipping && !this.leaving && !this._paused) {
|
||||||
this._handleTrackEnd();
|
this._handleTrackEnd();
|
||||||
} else if (result === "stopped") {
|
} else if (result === "stopped") {
|
||||||
|
if (!this._skipping && !this.leaving && !this._paused) {
|
||||||
|
/* Unintended stop (audio connection drop or source early-close): advance queue so playback does not stall */
|
||||||
|
logger.player(`[Player] Track ended unexpectedly with status '${result}', auto-advancing`);
|
||||||
|
this._handleTrackEnd();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -440,6 +513,51 @@ const PlaybackMixin = {
|
|||||||
}, 3_000).unref?.();
|
}, 3_000).unref?.();
|
||||||
},
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start polling out-of-band ICY and Icecast metadata for live radio stations.
|
||||||
|
* Updates songData.currentStreamTitle when changed and triggers dashboard update.
|
||||||
|
* @param {object} songData
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_startRadioTitlePolling(songData) {
|
||||||
|
this._stopRadioTitlePolling();
|
||||||
|
if (!songData || songData.type !== "radio" || !songData.url) return;
|
||||||
|
|
||||||
|
const poll = async () => {
|
||||||
|
try {
|
||||||
|
const current = this.queue.getCurrent();
|
||||||
|
if (!current || current.type !== "radio" || current.url !== songData.url) {
|
||||||
|
this._stopRadioTitlePolling();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const liveTitle = await fetchRadioStreamTitle(songData.url);
|
||||||
|
if (liveTitle && liveTitle !== current.currentStreamTitle) {
|
||||||
|
current.currentStreamTitle = liveTitle;
|
||||||
|
songData.currentStreamTitle = liveTitle;
|
||||||
|
logger.player(`[Player:${this._guildId}] Radio live title updated: ${liveTitle}`);
|
||||||
|
this.emit("radioTitleUpdate", { track: current, title: liveTitle });
|
||||||
|
this.dashboard?.playerUpdate?.({ type: "update" }, this);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.player(`[Player:${this._guildId}] Radio metadata poll error: ${e?.message}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
poll();
|
||||||
|
this._radioPollInterval = setInterval(poll, 25_000);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop the active radio metadata polling timer.
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_stopRadioTitlePolling() {
|
||||||
|
if (this._radioPollInterval) {
|
||||||
|
clearInterval(this._radioPollInterval);
|
||||||
|
this._radioPollInterval = null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @private Clear the track-end timer.
|
* @private Clear the track-end timer.
|
||||||
* @this {import('./Player.mjs').Player}
|
* @this {import('./Player.mjs').Player}
|
||||||
@@ -450,6 +568,89 @@ const PlaybackMixin = {
|
|||||||
this._trackEndTimer = null;
|
this._trackEndTimer = null;
|
||||||
}
|
}
|
||||||
this._trackEndRemainingMs = null;
|
this._trackEndRemainingMs = null;
|
||||||
|
this._clearPrefetchTimer();
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Clear the next-up pre-fetch timer.
|
||||||
|
* @this {import('./Player.mjs').Player}
|
||||||
|
*/
|
||||||
|
_clearPrefetchTimer() {
|
||||||
|
if (this._prefetchTimer) {
|
||||||
|
clearTimeout(this._prefetchTimer);
|
||||||
|
this._prefetchTimer = null;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Pre-fetch the upcoming track in the queue: pre-resolves Lavalink
|
||||||
|
* encoded payload if missing, and queries NodeLink /v4/trackstream in advance
|
||||||
|
* so the next track begins with 0ms transition latency.
|
||||||
|
* @this {import('./Player.mjs').Player}
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async _prefetchNextTrack() {
|
||||||
|
this._clearPrefetchTimer();
|
||||||
|
if (this._destroyed || this.leaving || !this.queue) return;
|
||||||
|
const nextTrack = typeof this.queue.peek === "function" ? this.queue.peek() : (this.queue.data?.[0] || null);
|
||||||
|
if (!nextTrack || nextTrack.type === "radio" || nextTrack.type === "livestream") return;
|
||||||
|
if (nextTrack._prefetchedDirect && Date.now() - (nextTrack._prefetchedDirect.cachedAt || 0) < 60_000) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!nextTrack.encoded && nextTrack.url && nextTrack.url.startsWith("http") && this._lavalink && nextTrack.type !== "external" && nextTrack.type !== "attachment") {
|
||||||
|
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||||
|
if (nlInfo) {
|
||||||
|
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 (this._guildId) headers["Guild-Id"] = this._guildId;
|
||||||
|
|
||||||
|
const loadtracksUrl = baseUrl + "/v4/loadtracks?identifier=" + encodeURIComponent(nextTrack.url);
|
||||||
|
const body = await this._request(loadtracksUrl, { headers }).catch(() => null);
|
||||||
|
const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data;
|
||||||
|
const encoded = track?.encoded ?? track?.data;
|
||||||
|
if (encoded && typeof encoded === "string") {
|
||||||
|
nextTrack.encoded = encoded;
|
||||||
|
logger.player(`[Player] Next track pre-resolved encoded payload: ${nextTrack.title || nextTrack.url}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nextTrack.encoded && this._audioBridge && typeof this._audioBridge._getTrackstreamUrl === "function") {
|
||||||
|
const direct = await this._audioBridge._getTrackstreamUrl({
|
||||||
|
encoded: nextTrack.encoded,
|
||||||
|
guildId: this._guildId,
|
||||||
|
}).catch(() => null);
|
||||||
|
|
||||||
|
if (direct?.url) {
|
||||||
|
nextTrack._prefetchedDirect = {
|
||||||
|
url: direct.url,
|
||||||
|
format: direct.format || "",
|
||||||
|
cachedAt: Date.now(),
|
||||||
|
};
|
||||||
|
logger.player(`[Player] Next-up pre-fetch ready for: ${nextTrack.title || nextTrack.url} (format=${direct.format})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.player("[Player] Next-up pre-fetch ignored error: " + (e?.message || e));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Trigger pre-fetching if the current track is already near completion.
|
||||||
|
* @this {import('./Player.mjs').Player}
|
||||||
|
*/
|
||||||
|
_maybePrefetchNext() {
|
||||||
|
if (!this.startedPlaying || this._paused || !this.queue?.getCurrent()) return;
|
||||||
|
const current = this.queue.getCurrent();
|
||||||
|
const totalMs = this._getTrackDurationMs(current);
|
||||||
|
if (totalMs <= 0) return;
|
||||||
|
const elapsedMs = Math.max(0, Date.now() - this.startedPlaying);
|
||||||
|
const remainingMs = totalMs - elapsedMs;
|
||||||
|
if (remainingMs <= 20_000) {
|
||||||
|
this._prefetchNextTrack().catch(() => {});
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -508,7 +709,6 @@ const PlaybackMixin = {
|
|||||||
this._seeking = true;
|
this._seeking = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this._bridgeStop();
|
|
||||||
const current = this.queue.getCurrent();
|
const current = this.queue.getCurrent();
|
||||||
if (current?.url) {
|
if (current?.url) {
|
||||||
this.startedPlaying = Date.now() - ms;
|
this.startedPlaying = Date.now() - ms;
|
||||||
@@ -521,7 +721,7 @@ const PlaybackMixin = {
|
|||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this._seeking = false;
|
this._seeking = false;
|
||||||
logger.error("[Player] Seek failed:", e?.message);
|
logger.player(`[Player] Seek failed: ${e?.message ?? e}`);
|
||||||
return false;
|
return false;
|
||||||
} finally {
|
} finally {
|
||||||
this._seeking = false;
|
this._seeking = false;
|
||||||
|
|||||||
@@ -74,6 +74,8 @@ class Player extends EventEmitter {
|
|||||||
_lastConnectedAt = null;
|
_lastConnectedAt = null;
|
||||||
/** @private @type {string|null} The home channel of a 24/7 spawn. */
|
/** @private @type {string|null} The home channel of a 24/7 spawn. */
|
||||||
_home247Channel = null;
|
_home247Channel = null;
|
||||||
|
/** @private @type {NodeJS.Timeout|null} */
|
||||||
|
_prefetchTimer = null;
|
||||||
|
|
||||||
/** @private @type {Set<string>} User IDs who have voted to skip the current track. Reset whenever a new track starts. */
|
/** @private @type {Set<string>} User IDs who have voted to skip the current track. Reset whenever a new track starts. */
|
||||||
_skipVotes = new Set();
|
_skipVotes = new Set();
|
||||||
@@ -150,7 +152,13 @@ class Player extends EventEmitter {
|
|||||||
super();
|
super();
|
||||||
|
|
||||||
this.queue = new Queue();
|
this.queue = new Queue();
|
||||||
this.queue.on("queue", (...args) => this.emit("queue", ...args));
|
this.queue.on("queue", (...args) => {
|
||||||
|
this.emit("queue", ...args);
|
||||||
|
const ev = args[0];
|
||||||
|
if (ev?.type === "add" || ev?.type === "addMany") {
|
||||||
|
this._maybePrefetchNext?.();
|
||||||
|
}
|
||||||
|
});
|
||||||
this.client = opts.client;
|
this.client = opts.client;
|
||||||
this.config = opts.config ?? {};
|
this.config = opts.config ?? {};
|
||||||
this.settings = opts.settings ?? null;
|
this.settings = opts.settings ?? null;
|
||||||
@@ -258,7 +266,7 @@ class Player extends EventEmitter {
|
|||||||
const channelId = this._channelId ?? this._home247Channel;
|
const channelId = this._channelId ?? this._home247Channel;
|
||||||
if (channelId) {
|
if (channelId) {
|
||||||
const ch = this.client?.channels?.get?.(channelId);
|
const ch = this.client?.channels?.get?.(channelId);
|
||||||
const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null;
|
const fromChannel = ch?.guildId ?? ch?.guild?.id ?? ch?.serverId ?? ch?.server_id ?? null;
|
||||||
if (fromChannel) return cleanId(fromChannel);
|
if (fromChannel) return cleanId(fromChannel);
|
||||||
}
|
}
|
||||||
} catch(e) { logger.warn("[Player] Guild resolution failed:", e?.message); }
|
} catch(e) { logger.warn("[Player] Guild resolution failed:", e?.message); }
|
||||||
@@ -340,6 +348,10 @@ class Player extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`);
|
logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`);
|
||||||
|
if (!this._inactivityWarned) {
|
||||||
|
this._inactivityWarned = true;
|
||||||
|
this.emit("inactivityWarning", { timeoutMs: this._inactivityLimit });
|
||||||
|
}
|
||||||
this._inactivityTimer = setTimeout(() => {
|
this._inactivityTimer = setTimeout(() => {
|
||||||
const currentMode = this._get247Mode();
|
const currentMode = this._get247Mode();
|
||||||
if (currentMode === "on") {
|
if (currentMode === "on") {
|
||||||
@@ -362,6 +374,7 @@ class Player extends EventEmitter {
|
|||||||
/** Clear the inactivity timer if running. */
|
/** Clear the inactivity timer if running. */
|
||||||
_stopInactivityTimer() {
|
_stopInactivityTimer() {
|
||||||
this._pendingInactivityCheck = false;
|
this._pendingInactivityCheck = false;
|
||||||
|
this._inactivityWarned = false;
|
||||||
if (this._inactivityTimer) {
|
if (this._inactivityTimer) {
|
||||||
logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`);
|
logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`);
|
||||||
clearTimeout(this._inactivityTimer);
|
clearTimeout(this._inactivityTimer);
|
||||||
@@ -424,7 +437,7 @@ class Player extends EventEmitter {
|
|||||||
path: urlObj.pathname + urlObj.search,
|
path: urlObj.pathname + urlObj.search,
|
||||||
method: options.method || "GET",
|
method: options.method || "GET",
|
||||||
headers: {
|
headers: {
|
||||||
"User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)",
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||||
"Accept": "*/*",
|
"Accept": "*/*",
|
||||||
...options.headers,
|
...options.headers,
|
||||||
},
|
},
|
||||||
@@ -486,7 +499,8 @@ class Player extends EventEmitter {
|
|||||||
logger.player(`[Player] Busy joining. Ignoring: ${channelId}`);
|
logger.player(`[Player] Busy joining. Ignoring: ${channelId}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this._voiceConn && this._channelId === channelId) {
|
const isConnActive = this._voiceConn && (typeof this._voiceConn.isConnected !== "function" || this._voiceConn.isConnected());
|
||||||
|
if (isConnActive && this._channelId === channelId) {
|
||||||
logger.player(`[Player] Already in channel: ${channelId}`);
|
logger.player(`[Player] Already in channel: ${channelId}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -511,7 +525,7 @@ class Player extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this._channelId = channelId;
|
this._channelId = channelId;
|
||||||
this._guildId = cleanId(channel.guildId);
|
this._guildId = cleanId(channel.guildId ?? channel.guild?.id ?? channel.serverId ?? channel.server_id ?? "");
|
||||||
this._lastConnectedAt = Date.now();
|
this._lastConnectedAt = Date.now();
|
||||||
this.leaving = false;
|
this.leaving = false;
|
||||||
|
|
||||||
@@ -559,7 +573,8 @@ class Player extends EventEmitter {
|
|||||||
const check = () => {
|
const check = () => {
|
||||||
try {
|
try {
|
||||||
if (voiceConn.isConnected()) { clearTimeout(timeout); return resolve(); }
|
if (voiceConn.isConnected()) { clearTimeout(timeout); return resolve(); }
|
||||||
if (voiceConn.connectionState === 0) { clearTimeout(timeout); return resolve(); }
|
const cs = voiceConn.connectionState;
|
||||||
|
if (cs === 2 || cs === "connected" || cs === "CONN_CONNECTED") { clearTimeout(timeout); return resolve(); }
|
||||||
} catch (_) { clearTimeout(timeout); return resolve(); }
|
} catch (_) { clearTimeout(timeout); return resolve(); }
|
||||||
setTimeout(check, 200);
|
setTimeout(check, 200);
|
||||||
};
|
};
|
||||||
@@ -603,6 +618,21 @@ class Player extends EventEmitter {
|
|||||||
voiceConn.on("disconnect", () => {
|
voiceConn.on("disconnect", () => {
|
||||||
if (this.leaving || this._destroyed) return;
|
if (this.leaving || this._destroyed) return;
|
||||||
logger.player(`[Player] Voice connection disconnected`);
|
logger.player(`[Player] Voice connection disconnected`);
|
||||||
|
this._voiceConn = null;
|
||||||
|
this.connection = null;
|
||||||
|
const cId = cleanId(this._channelId ?? this._home247Channel ?? "");
|
||||||
|
const is247 = this._get247Mode() === "on";
|
||||||
|
if (is247) {
|
||||||
|
/* 24/7 channels are managed centrally by GatewayHandler and schedule247Rejoin to prevent race conditions */
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (cId && (this.queue?.getCurrent() || !(this.queue?.isEmpty?.() ?? true))) {
|
||||||
|
logger.player(`[Player] Voice disconnected with active session — scheduling reconnect to channel ${cId} in 2.5s`);
|
||||||
|
setTimeout(() => {
|
||||||
|
if (this.leaving || this._destroyed || this._voiceConn) return;
|
||||||
|
this.join(cId).catch(err => logger.player(`[Player] Voice reconnect after disconnect failed: ${err?.message}`));
|
||||||
|
}, 2_500).unref?.();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -710,6 +740,8 @@ class Player extends EventEmitter {
|
|||||||
if (this._stateHeartbeat) { clearInterval(this._stateHeartbeat); this._stateHeartbeat = null; }
|
if (this._stateHeartbeat) { clearInterval(this._stateHeartbeat); this._stateHeartbeat = null; }
|
||||||
|
|
||||||
this._clearTrackEndTimer();
|
this._clearTrackEndTimer();
|
||||||
|
this._stopRadioTitlePolling?.();
|
||||||
|
this._inactivityWarned = false;
|
||||||
this._activeTrackOpt = null;
|
this._activeTrackOpt = null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -1060,6 +1092,9 @@ class Player extends EventEmitter {
|
|||||||
|
|
||||||
/** @private Stop the audio bridge if currently playing. */
|
/** @private Stop the audio bridge if currently playing. */
|
||||||
_bridgeStop() {
|
_bridgeStop() {
|
||||||
|
this._playSessionGen = (this._playSessionGen ?? 0) + 1;
|
||||||
|
this._clearPrefetchTimer?.();
|
||||||
|
this._stopRadioTitlePolling?.();
|
||||||
if (this._audioBridge) {
|
if (this._audioBridge) {
|
||||||
try { this._audioBridge.stop(); } catch (_) {}
|
try { this._audioBridge.stop(); } catch (_) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,6 +41,21 @@ export class Queue extends EventEmitter {
|
|||||||
/** @returns {number} Number of tracks in the queue (excluding current). */
|
/** @returns {number} Number of tracks in the queue (excluding current). */
|
||||||
size() { return this.data.length; }
|
size() { return this.data.length; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Peek at the track that will play next without modifying the queue.
|
||||||
|
* @param {object} [options]
|
||||||
|
* @param {boolean} [options.ignoreSongLoop=false]
|
||||||
|
* @returns {object|null}
|
||||||
|
*/
|
||||||
|
peek({ ignoreSongLoop = false } = {}) {
|
||||||
|
if (!ignoreSongLoop && this.songLoop && this.current) return this.current;
|
||||||
|
if (this.isEmpty()) {
|
||||||
|
if (this.loop && this.current) return this.current;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return this.data[0] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Advance to the next track in the queue. If songLoop is active, returns
|
* Advance to the next track in the queue. If songLoop is active, returns
|
||||||
* the current track. If queue loop is active, re-appends the current track.
|
* the current track. If queue loop is active, re-appends the current track.
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { Utils } from "../../utils/Utils.mjs";
|
|||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
import { PROVIDERS, PROVIDER_NAMES } from "../providers.mjs";
|
import { PROVIDERS, PROVIDER_NAMES } from "../providers.mjs";
|
||||||
import { bilibiliEnabled, isBilibiliUrl, resolveBilibiliVideo } from "../bilibili/index.mjs";
|
import { bilibiliEnabled, isBilibiliUrl, resolveBilibiliVideo } from "../bilibili/index.mjs";
|
||||||
|
import { isFluxerAttachmentUrl, extractMediaTitle } from "../../utils/AttachmentUtils.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Broad music genres are ambiguous when used by themselves: searching for
|
* Broad music genres are ambiguous when used by themselves: searching for
|
||||||
@@ -305,7 +306,7 @@ const SearchMixin = {
|
|||||||
if (ms === 0 && info.duration != null) {
|
if (ms === 0 && info.duration != null) {
|
||||||
if (typeof info.duration === "number") {
|
if (typeof info.duration === "number") {
|
||||||
ms = info.duration;
|
ms = info.duration;
|
||||||
} else if (typeof info.duration === "object" && info.duration.seconds != null) {
|
} else if (typeof info.duration === "object" && info.duration?.seconds != null) {
|
||||||
ms = info.duration.seconds * 1000;
|
ms = info.duration.seconds * 1000;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -318,7 +319,8 @@ const SearchMixin = {
|
|||||||
videoId: info.identifier ?? "",
|
videoId: info.identifier ?? "",
|
||||||
encoded: track.encoded ?? info.encoded ?? "",
|
encoded: track.encoded ?? info.encoded ?? "",
|
||||||
sourceName: info.sourceName ?? "unknown",
|
sourceName: info.sourceName ?? "unknown",
|
||||||
isLive: info.isLive === true,
|
isLive: info.isLive === true || info.isStream === true,
|
||||||
|
isStream: info.isStream === true || info.isLive === true,
|
||||||
title: Utils.cleanTitle(info.title ?? "Unknown"),
|
title: Utils.cleanTitle(info.title ?? "Unknown"),
|
||||||
url: trackUri,
|
url: trackUri,
|
||||||
thumbnail: info.artworkUrl ?? null,
|
thumbnail: info.artworkUrl ?? null,
|
||||||
@@ -373,38 +375,19 @@ const SearchMixin = {
|
|||||||
*/
|
*/
|
||||||
async _searchFreeText(query, source) {
|
async _searchFreeText(query, source) {
|
||||||
const variants = searchQueryVariants(query, source);
|
const variants = searchQueryVariants(query, source);
|
||||||
const attempts = await Promise.allSettled(
|
for (const candidate of variants) {
|
||||||
variants.map(candidate => this._lavalink.search(candidate, { source }))
|
try {
|
||||||
);
|
const res = await this._lavalink.search(candidate, { source });
|
||||||
const successful = attempts
|
if (res?.tracks?.length > 0) {
|
||||||
.filter(attempt => attempt.status === "fulfilled")
|
return res;
|
||||||
.map(attempt => attempt.value)
|
}
|
||||||
.filter(Boolean);
|
} catch (err) {
|
||||||
|
/* Search candidate exploration is a normal fallback mechanism; log as player diagnostic */
|
||||||
if (successful.length === 0) {
|
const errMsg = err?.message || err?.error || (typeof err === "string" ? err : "") || "unknown error";
|
||||||
const failed = attempts.find(attempt => attempt.status === "rejected");
|
logger.player(`[Player] Free text search candidate "${candidate}" failed (${source}):`, errMsg);
|
||||||
if (failed) throw failed.reason;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const unique = new Map();
|
|
||||||
for (const result of successful) {
|
|
||||||
for (const track of result?.tracks ?? []) {
|
|
||||||
const key = searchTrackKey(track);
|
|
||||||
if (!unique.has(key)) unique.set(key, track);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
const tracks = [...unique.values()]
|
|
||||||
.map((track, index) => ({ track, index, score: scoreSearchTrack(track, query) }))
|
|
||||||
.sort((a, b) => b.score - a.score || a.index - b.index)
|
|
||||||
.map(({ track }) => track);
|
|
||||||
|
|
||||||
if (variants.length > 1) {
|
|
||||||
logger.player(`[Player] Topic-aware search for "${query}": ${tracks.length} unique results ranked from ${variants.length} queries.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return { ...successful[0], tracks };
|
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -473,7 +456,6 @@ const SearchMixin = {
|
|||||||
} catch (searchErr) {
|
} catch (searchErr) {
|
||||||
logger.warn("[Player] URL/primary search failed:", searchErr?.message);
|
logger.warn("[Player] URL/primary search failed:", searchErr?.message);
|
||||||
result = null;
|
result = null;
|
||||||
if (!isUrl) throw searchErr;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let lcTracks = result?.tracks ?? [];
|
let lcTracks = result?.tracks ?? [];
|
||||||
@@ -646,8 +628,12 @@ const SearchMixin = {
|
|||||||
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error("[Player] play() search error:", err?.message);
|
logger.warn("[Player] play() search error:", err?.message);
|
||||||
events.emit("message", err?.message || "An error occurred while loading the track.");
|
const isTimeout = err?.name === "TimeoutError" || err?.message?.toLowerCase()?.includes("timeout");
|
||||||
|
const msg = isTimeout
|
||||||
|
? "⚠️ **Search timed out.** The audio service took too long to respond. Please try again or specify a provider (e.g. `%p yt " + query + "`)."
|
||||||
|
: (err?.message || "An error occurred while loading the track.");
|
||||||
|
events.emit("message", msg);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
@@ -666,7 +652,7 @@ const SearchMixin = {
|
|||||||
try {
|
try {
|
||||||
const source = this._getSource(provider);
|
const source = this._getSource(provider);
|
||||||
const result = await this._searchFreeText(query, source);
|
const result = await this._searchFreeText(query, source);
|
||||||
return result.tracks || [];
|
return result?.tracks || [];
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error(`[Player] lavalink search error:`, e?.message);
|
logger.error(`[Player] lavalink search error:`, e?.message);
|
||||||
return [];
|
return [];
|
||||||
@@ -743,12 +729,15 @@ const SearchMixin = {
|
|||||||
* @returns {object}
|
* @returns {object}
|
||||||
*/
|
*/
|
||||||
_buildExternalTrack(url, title = null, artist = null, trackType = "external") {
|
_buildExternalTrack(url, title = null, artist = null, trackType = "external") {
|
||||||
const displayTitle = title || this._extractFilenameFromUrl(url);
|
const isAttachment = isFluxerAttachmentUrl(url);
|
||||||
|
const resolvedType = isAttachment ? "attachment" : trackType;
|
||||||
|
const displayTitle = title || (isAttachment ? extractMediaTitle(url) : this._extractFilenameFromUrl(url));
|
||||||
|
const displayArtist = artist || (isAttachment ? "Fluxer Attachment" : null);
|
||||||
return {
|
return {
|
||||||
type: trackType,
|
type: resolvedType,
|
||||||
title: displayTitle,
|
title: displayTitle,
|
||||||
url: url,
|
url: url,
|
||||||
artist: artist || null,
|
artist: displayArtist,
|
||||||
thumbnail: null,
|
thumbnail: null,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -0,0 +1,582 @@
|
|||||||
|
/**
|
||||||
|
* @module src/services/PlaylistManager
|
||||||
|
* @description Manages personal saved playlists and track bookmarks (favorites) in MySQL.
|
||||||
|
* All playlist and bookmark records are keyed per-user, making them accessible across all servers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
|
export const MAX_PLAYLISTS_PER_USER = 50;
|
||||||
|
export const MAX_TRACKS_PER_PLAYLIST = 250;
|
||||||
|
export const MAX_FAVORITES_PER_USER = 250;
|
||||||
|
export const MAX_NAME_LENGTH = 32;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sanitize user-provided playlist name.
|
||||||
|
* @param {string} raw
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function sanitizePlaylistName(raw) {
|
||||||
|
if (!raw || typeof raw !== "string") return "";
|
||||||
|
return raw
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[\/\\]/g, "")
|
||||||
|
.slice(0, MAX_NAME_LENGTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class PlaylistManager
|
||||||
|
* @description Provides CRUD operations for user favorites and personal playlists stored in MySQL.
|
||||||
|
*/
|
||||||
|
export class PlaylistManager {
|
||||||
|
/**
|
||||||
|
* @param {import('mysql2/promise').Pool} pool - Shared promise-based MySQL pool.
|
||||||
|
*/
|
||||||
|
constructor(pool) {
|
||||||
|
this._pool = pool;
|
||||||
|
this._ready = false;
|
||||||
|
this._readyPromise = this._ensureTables();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure database tables exist.
|
||||||
|
* @private
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async _ensureTables() {
|
||||||
|
if (!this._pool) return;
|
||||||
|
try {
|
||||||
|
await this._pool.execute(`
|
||||||
|
CREATE TABLE IF NOT EXISTS \`user_favorites\` (
|
||||||
|
\`id\` INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
\`user_id\` VARCHAR(32) NOT NULL,
|
||||||
|
\`title\` VARCHAR(512) NOT NULL,
|
||||||
|
\`author\` VARCHAR(255) NOT NULL DEFAULT '',
|
||||||
|
\`uri\` VARCHAR(1024) NOT NULL,
|
||||||
|
\`duration_ms\` BIGINT NOT NULL DEFAULT 0,
|
||||||
|
\`source_name\` VARCHAR(64) NOT NULL DEFAULT '',
|
||||||
|
\`thumbnail\` VARCHAR(1024) NOT NULL DEFAULT '',
|
||||||
|
\`created_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE KEY \`uniq_user_uri\` (\`user_id\`, \`uri\`(255)),
|
||||||
|
INDEX \`idx_user_fav_created\` (\`user_id\`, \`created_at\` DESC)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
`);
|
||||||
|
|
||||||
|
await this._pool.execute(`
|
||||||
|
CREATE TABLE IF NOT EXISTS \`user_playlists\` (
|
||||||
|
\`id\` INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
\`user_id\` VARCHAR(32) NOT NULL,
|
||||||
|
\`name\` VARCHAR(64) NOT NULL,
|
||||||
|
\`tracks\` JSON NOT NULL,
|
||||||
|
\`created_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
\`updated_at\` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
UNIQUE KEY \`uniq_user_pl_name\` (\`user_id\`, \`name\`),
|
||||||
|
INDEX \`idx_user_pl_updated\` (\`user_id\`, \`updated_at\` DESC)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
`);
|
||||||
|
|
||||||
|
this._ready = true;
|
||||||
|
logger.info("[PlaylistManager] Database tables initialized successfully.");
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Failed to initialize database tables:", err?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wait for table initialization.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async ready() {
|
||||||
|
if (this._ready) return;
|
||||||
|
await this._readyPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* =========================================================================
|
||||||
|
FAVORITES / BOOKMARKS API
|
||||||
|
========================================================================= */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a track to the user's personal favorites.
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {object} track
|
||||||
|
* @returns {Promise<{added: boolean, alreadySaved: boolean, limitReached: boolean, count: number}>}
|
||||||
|
*/
|
||||||
|
async addFavorite(userId, track) {
|
||||||
|
await this.ready();
|
||||||
|
if (!this._pool || !userId || !track) {
|
||||||
|
return { added: false, alreadySaved: false, limitReached: false, count: 0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const count = await this.getFavoriteCount(userId);
|
||||||
|
if (count >= MAX_FAVORITES_PER_USER) {
|
||||||
|
return { added: false, alreadySaved: false, limitReached: true, count };
|
||||||
|
}
|
||||||
|
|
||||||
|
const title = String(track.title || "Unknown").slice(0, 512);
|
||||||
|
const author = String(track.author?.name || track.author || "").slice(0, 255);
|
||||||
|
const uri = String(track.url || track.uri || "").slice(0, 1024);
|
||||||
|
const durationMs = Number(track._durationMs || track.duration?.seconds * 1000 || 0) || 0;
|
||||||
|
const sourceName = String(track.sourceName || "unknown").slice(0, 64);
|
||||||
|
const thumbnail = String(track.thumbnail || "").slice(0, 1024);
|
||||||
|
|
||||||
|
if (!uri) {
|
||||||
|
return { added: false, alreadySaved: false, limitReached: false, count };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [result] = await this._pool.execute(`
|
||||||
|
INSERT INTO \`user_favorites\`
|
||||||
|
(\`user_id\`, \`title\`, \`author\`, \`uri\`, \`duration_ms\`, \`source_name\`, \`thumbnail\`)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON DUPLICATE KEY UPDATE
|
||||||
|
\`title\` = VALUES(\`title\`),
|
||||||
|
\`author\` = VALUES(\`author\`),
|
||||||
|
\`duration_ms\` = VALUES(\`duration_ms\`),
|
||||||
|
\`thumbnail\` = VALUES(\`thumbnail\`);
|
||||||
|
`, [userId, title, author, uri, durationMs, sourceName, thumbnail]);
|
||||||
|
|
||||||
|
/* affectedRows = 1 on insert, 2 on duplicate update, 0 if identical */
|
||||||
|
const isNew = result.affectedRows === 1;
|
||||||
|
const newCount = isNew ? count + 1 : count;
|
||||||
|
return { added: isNew, alreadySaved: !isNew, limitReached: false, count: newCount };
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error adding favorite:", err?.message);
|
||||||
|
return { added: false, alreadySaved: false, limitReached: false, count };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a track from user favorites by URI or index.
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {string|number} identifier
|
||||||
|
* @returns {Promise<{removed: boolean, track: object|null}>}
|
||||||
|
*/
|
||||||
|
async removeFavorite(userId, identifier) {
|
||||||
|
await this.ready();
|
||||||
|
if (!this._pool || !userId) return { removed: false, track: null };
|
||||||
|
|
||||||
|
try {
|
||||||
|
/* If numeric index, resolve track at that position */
|
||||||
|
if (typeof identifier === "number" || (/^\d+$/.test(String(identifier).trim()) && !String(identifier).includes("http"))) {
|
||||||
|
const idx = Math.max(0, parseInt(identifier, 10) - 1);
|
||||||
|
const favs = await this.getFavorites(userId, 1, idx);
|
||||||
|
if (favs.length === 0) return { removed: false, track: null };
|
||||||
|
|
||||||
|
const target = favs[0];
|
||||||
|
await this._pool.execute(
|
||||||
|
"DELETE FROM `user_favorites` WHERE `id` = ? AND `user_id` = ?",
|
||||||
|
[target.id, userId]
|
||||||
|
);
|
||||||
|
return { removed: true, track: target };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Otherwise match by URI or partial title */
|
||||||
|
const query = String(identifier).trim();
|
||||||
|
const [rows] = await this._pool.execute(`
|
||||||
|
SELECT * FROM \`user_favorites\`
|
||||||
|
WHERE \`user_id\` = ? AND (\`uri\` = ? OR \`title\` LIKE ?)
|
||||||
|
LIMIT 1
|
||||||
|
`, [userId, query, `%${query}%`]);
|
||||||
|
|
||||||
|
if (!rows || rows.length === 0) return { removed: false, track: null };
|
||||||
|
|
||||||
|
const target = rows[0];
|
||||||
|
await this._pool.execute(
|
||||||
|
"DELETE FROM `user_favorites` WHERE `id` = ? AND `user_id` = ?",
|
||||||
|
[target.id, userId]
|
||||||
|
);
|
||||||
|
return { removed: true, track: target };
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error removing favorite:", err?.message);
|
||||||
|
return { removed: false, track: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Toggle a track in user favorites (heart/bookmark shortcut).
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {object} track
|
||||||
|
* @returns {Promise<{action: "added"|"removed"|"limit", track: object, count: number}>}
|
||||||
|
*/
|
||||||
|
async toggleFavorite(userId, track) {
|
||||||
|
await this.ready();
|
||||||
|
const uri = String(track?.url || track?.uri || "").trim();
|
||||||
|
if (!uri) return { action: "removed", track: null, count: 0 };
|
||||||
|
|
||||||
|
const favs = await this.getFavorites(userId, 500, 0);
|
||||||
|
const existing = favs.find(f => f.uri === uri);
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
await this.removeFavorite(userId, existing.uri);
|
||||||
|
return { action: "removed", track: existing, count: Math.max(0, favs.length - 1) };
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await this.addFavorite(userId, track);
|
||||||
|
if (res.limitReached) {
|
||||||
|
return { action: "limit", track, count: favs.length };
|
||||||
|
}
|
||||||
|
return { action: "added", track, count: res.count };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get total count of favorites for a user.
|
||||||
|
* @param {string} userId
|
||||||
|
* @returns {Promise<number>}
|
||||||
|
*/
|
||||||
|
async getFavoriteCount(userId) {
|
||||||
|
await this.ready();
|
||||||
|
if (!this._pool || !userId) return 0;
|
||||||
|
try {
|
||||||
|
const [rows] = await this._pool.execute(
|
||||||
|
"SELECT COUNT(*) AS total FROM `user_favorites` WHERE `user_id` = ?",
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
return Number(rows?.[0]?.total || 0);
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error counting favorites:", err?.message);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all favorite tracks for a user with pagination.
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {number} [limit=100]
|
||||||
|
* @param {number} [offset=0]
|
||||||
|
* @returns {Promise<Array<object>>}
|
||||||
|
*/
|
||||||
|
async getFavorites(userId, limit = 100, offset = 0) {
|
||||||
|
await this.ready();
|
||||||
|
if (!this._pool || !userId) return [];
|
||||||
|
try {
|
||||||
|
const safeLimit = Math.max(1, Math.min(limit, 500));
|
||||||
|
const safeOffset = Math.max(0, offset);
|
||||||
|
const [rows] = await this._pool.execute(`
|
||||||
|
SELECT \`id\`, \`title\`, \`author\`, \`uri\`, \`duration_ms\`, \`source_name\`, \`thumbnail\`, \`created_at\`
|
||||||
|
FROM \`user_favorites\`
|
||||||
|
WHERE \`user_id\` = ?
|
||||||
|
ORDER BY \`created_at\` DESC
|
||||||
|
LIMIT ${safeLimit} OFFSET ${safeOffset}
|
||||||
|
`, [userId]);
|
||||||
|
return Array.isArray(rows) ? rows : [];
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error fetching favorites:", err?.message);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear all favorites for a user.
|
||||||
|
* @param {string} userId
|
||||||
|
* @returns {Promise<number>} Number of cleared favorites.
|
||||||
|
*/
|
||||||
|
async clearFavorites(userId) {
|
||||||
|
await this.ready();
|
||||||
|
if (!this._pool || !userId) return 0;
|
||||||
|
try {
|
||||||
|
const [result] = await this._pool.execute(
|
||||||
|
"DELETE FROM `user_favorites` WHERE `user_id` = ?",
|
||||||
|
[userId]
|
||||||
|
);
|
||||||
|
return Number(result.affectedRows || 0);
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error clearing favorites:", err?.message);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* =========================================================================
|
||||||
|
PLAYLISTS API
|
||||||
|
========================================================================= */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save a list of tracks as a personal playlist.
|
||||||
|
* Overwrites if the playlist already exists.
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {string} rawName
|
||||||
|
* @param {Array<object>} rawTracks
|
||||||
|
* @returns {Promise<{success: boolean, name: string, count: number, isNew: boolean, error?: string}>}
|
||||||
|
*/
|
||||||
|
async savePlaylist(userId, rawName, rawTracks) {
|
||||||
|
await this.ready();
|
||||||
|
const name = sanitizePlaylistName(rawName);
|
||||||
|
if (!name) {
|
||||||
|
return { success: false, name: "", count: 0, isNew: false, error: "INVALID_NAME" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(rawTracks) || rawTracks.length === 0) {
|
||||||
|
return { success: false, name, count: 0, isNew: false, error: "EMPTY_TRACKS" };
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Check playlist count limit if creating new */
|
||||||
|
const existing = await this.getPlaylist(userId, name);
|
||||||
|
if (!existing) {
|
||||||
|
const allPlaylists = await this.listPlaylists(userId);
|
||||||
|
if (allPlaylists.length >= MAX_PLAYLISTS_PER_USER) {
|
||||||
|
return { success: false, name, count: 0, isNew: false, error: "LIMIT_REACHED" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Serialize tracks up to cap */
|
||||||
|
const tracksToSave = rawTracks.slice(0, MAX_TRACKS_PER_PLAYLIST).map(t => ({
|
||||||
|
title: String(t.title || "Unknown").slice(0, 512),
|
||||||
|
author: String(t.author?.name || t.author || "").slice(0, 255),
|
||||||
|
uri: String(t.url || t.uri || ""),
|
||||||
|
durationMs: Number(t._durationMs || t.duration?.seconds * 1000 || 0) || 0,
|
||||||
|
sourceName: String(t.sourceName || "unknown").slice(0, 64),
|
||||||
|
thumbnail: String(t.thumbnail || "").slice(0, 1024),
|
||||||
|
})).filter(t => t.uri.length > 0);
|
||||||
|
|
||||||
|
if (tracksToSave.length === 0) {
|
||||||
|
return { success: false, name, count: 0, isNew: false, error: "EMPTY_TRACKS" };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const jsonStr = JSON.stringify(tracksToSave);
|
||||||
|
const [res] = await this._pool.execute(`
|
||||||
|
INSERT INTO \`user_playlists\` (\`user_id\`, \`name\`, \`tracks\`)
|
||||||
|
VALUES (?, ?, ?)
|
||||||
|
ON DUPLICATE KEY UPDATE \`tracks\` = VALUES(\`tracks\`), \`updated_at\` = CURRENT_TIMESTAMP;
|
||||||
|
`, [userId, name, jsonStr]);
|
||||||
|
|
||||||
|
const isNew = res.affectedRows === 1;
|
||||||
|
return { success: true, name, count: tracksToSave.length, isNew };
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error saving playlist:", err?.message);
|
||||||
|
return { success: false, name, count: 0, isNew: false, error: "DB_ERROR" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a saved playlist by name.
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {string} rawName
|
||||||
|
* @returns {Promise<{id: number, name: string, tracks: Array<object>, created_at: Date, updated_at: Date}|null>}
|
||||||
|
*/
|
||||||
|
async getPlaylist(userId, rawName) {
|
||||||
|
await this.ready();
|
||||||
|
const name = sanitizePlaylistName(rawName);
|
||||||
|
if (!this._pool || !userId || !name) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [rows] = await this._pool.execute(
|
||||||
|
"SELECT * FROM `user_playlists` WHERE `user_id` = ? AND `name` = ? LIMIT 1",
|
||||||
|
[userId, name]
|
||||||
|
);
|
||||||
|
if (!rows || rows.length === 0) return null;
|
||||||
|
|
||||||
|
const record = rows[0];
|
||||||
|
let tracks = [];
|
||||||
|
try {
|
||||||
|
tracks = typeof record.tracks === "string" ? JSON.parse(record.tracks) : (record.tracks || []);
|
||||||
|
} catch (_) {
|
||||||
|
tracks = [];
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: record.id,
|
||||||
|
name: record.name,
|
||||||
|
tracks: Array.isArray(tracks) ? tracks : [],
|
||||||
|
created_at: record.created_at,
|
||||||
|
updated_at: record.updated_at,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error getting playlist:", err?.message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List all saved playlists for a user.
|
||||||
|
* @param {string} userId
|
||||||
|
* @returns {Promise<Array<{name: string, trackCount: number, updated_at: Date, created_at: Date}>>}
|
||||||
|
*/
|
||||||
|
async listPlaylists(userId) {
|
||||||
|
await this.ready();
|
||||||
|
if (!this._pool || !userId) return [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [rows] = await this._pool.execute(`
|
||||||
|
SELECT \`name\`, \`tracks\`, \`created_at\`, \`updated_at\`
|
||||||
|
FROM \`user_playlists\`
|
||||||
|
WHERE \`user_id\` = ?
|
||||||
|
ORDER BY \`updated_at\` DESC
|
||||||
|
`, [userId]);
|
||||||
|
|
||||||
|
if (!Array.isArray(rows)) return [];
|
||||||
|
|
||||||
|
return rows.map(r => {
|
||||||
|
let count = 0;
|
||||||
|
try {
|
||||||
|
const parsed = typeof r.tracks === "string" ? JSON.parse(r.tracks) : r.tracks;
|
||||||
|
count = Array.isArray(parsed) ? parsed.length : 0;
|
||||||
|
} catch (_) {
|
||||||
|
count = 0;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
name: r.name,
|
||||||
|
trackCount: count,
|
||||||
|
created_at: r.created_at,
|
||||||
|
updated_at: r.updated_at,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error listing playlists:", err?.message);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a saved playlist by name.
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {string} rawName
|
||||||
|
* @returns {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
async deletePlaylist(userId, rawName) {
|
||||||
|
await this.ready();
|
||||||
|
const name = sanitizePlaylistName(rawName);
|
||||||
|
if (!this._pool || !userId || !name) return false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [res] = await this._pool.execute(
|
||||||
|
"DELETE FROM `user_playlists` WHERE `user_id` = ? AND `name` = ?",
|
||||||
|
[userId, name]
|
||||||
|
);
|
||||||
|
return Number(res.affectedRows || 0) > 0;
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error deleting playlist:", err?.message);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a single track to an existing playlist.
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {string} rawName
|
||||||
|
* @param {object} track
|
||||||
|
* @returns {Promise<{success: boolean, name: string, count: number, error?: string}>}
|
||||||
|
*/
|
||||||
|
async addToPlaylist(userId, rawName, track) {
|
||||||
|
await this.ready();
|
||||||
|
const name = sanitizePlaylistName(rawName);
|
||||||
|
if (!name || !track) {
|
||||||
|
return { success: false, name, count: 0, error: "INVALID_ARG" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const playlist = await this.getPlaylist(userId, name);
|
||||||
|
if (!playlist) {
|
||||||
|
return { success: false, name, count: 0, error: "NOT_FOUND" };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (playlist.tracks.length >= MAX_TRACKS_PER_PLAYLIST) {
|
||||||
|
return { success: false, name, count: playlist.tracks.length, error: "PLAYLIST_FULL" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const uri = String(track.url || track.uri || "");
|
||||||
|
if (!uri) return { success: false, name, count: playlist.tracks.length, error: "NO_URI" };
|
||||||
|
|
||||||
|
playlist.tracks.push({
|
||||||
|
title: String(track.title || "Unknown").slice(0, 512),
|
||||||
|
author: String(track.author?.name || track.author || "").slice(0, 255),
|
||||||
|
uri,
|
||||||
|
durationMs: Number(track._durationMs || track.duration?.seconds * 1000 || 0) || 0,
|
||||||
|
sourceName: String(track.sourceName || "unknown").slice(0, 64),
|
||||||
|
thumbnail: String(track.thumbnail || "").slice(0, 1024),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this._pool.execute(
|
||||||
|
"UPDATE `user_playlists` SET `tracks` = ?, `updated_at` = CURRENT_TIMESTAMP WHERE `user_id` = ? AND `name` = ?",
|
||||||
|
[JSON.stringify(playlist.tracks), userId, name]
|
||||||
|
);
|
||||||
|
return { success: true, name, count: playlist.tracks.length };
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error adding to playlist:", err?.message);
|
||||||
|
return { success: false, name, count: playlist.tracks.length, error: "DB_ERROR" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add multiple tracks to an existing playlist up to MAX_TRACKS_PER_PLAYLIST.
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {string} rawName
|
||||||
|
* @param {Array<object>} newTracks
|
||||||
|
* @returns {Promise<{success: boolean, name: string, addedCount: number, count: number, error?: string}>}
|
||||||
|
*/
|
||||||
|
async addTracksToPlaylist(userId, rawName, newTracks) {
|
||||||
|
await this.ready();
|
||||||
|
const name = sanitizePlaylistName(rawName);
|
||||||
|
if (!name || !Array.isArray(newTracks) || newTracks.length === 0) {
|
||||||
|
return { success: false, name, addedCount: 0, count: 0, error: "INVALID_ARG" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const playlist = await this.getPlaylist(userId, name);
|
||||||
|
if (!playlist) {
|
||||||
|
return { success: false, name, addedCount: 0, count: 0, error: "NOT_FOUND" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const availableSlots = MAX_TRACKS_PER_PLAYLIST - playlist.tracks.length;
|
||||||
|
if (availableSlots <= 0) {
|
||||||
|
return { success: false, name, addedCount: 0, count: playlist.tracks.length, error: "PLAYLIST_FULL" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const sanitized = newTracks.slice(0, availableSlots).map(t => ({
|
||||||
|
title: String(t.title || "Unknown").slice(0, 512),
|
||||||
|
author: String(t.author?.name || t.author || "").slice(0, 255),
|
||||||
|
uri: String(t.url || t.uri || ""),
|
||||||
|
durationMs: Number(t._durationMs || t.durationMs || t.duration?.seconds * 1000 || 0) || 0,
|
||||||
|
sourceName: String(t.sourceName || "unknown").slice(0, 64),
|
||||||
|
thumbnail: String(t.thumbnail || "").slice(0, 1024),
|
||||||
|
})).filter(t => t.uri.length > 0);
|
||||||
|
|
||||||
|
if (sanitized.length === 0) {
|
||||||
|
return { success: false, name, addedCount: 0, count: playlist.tracks.length, error: "NO_VALID_TRACKS" };
|
||||||
|
}
|
||||||
|
|
||||||
|
playlist.tracks.push(...sanitized);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this._pool.execute(
|
||||||
|
"UPDATE `user_playlists` SET `tracks` = ?, `updated_at` = CURRENT_TIMESTAMP WHERE `user_id` = ? AND `name` = ?",
|
||||||
|
[JSON.stringify(playlist.tracks), userId, name]
|
||||||
|
);
|
||||||
|
return { success: true, name, addedCount: sanitized.length, count: playlist.tracks.length };
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error adding tracks to playlist:", err?.message);
|
||||||
|
return { success: false, name, addedCount: 0, count: playlist.tracks.length, error: "DB_ERROR" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a track at 1-based index from a playlist.
|
||||||
|
* @param {string} userId
|
||||||
|
* @param {string} rawName
|
||||||
|
* @param {number} oneBasedIndex
|
||||||
|
* @returns {Promise<{success: boolean, name: string, removedTrack: object|null, count: number, error?: string}>}
|
||||||
|
*/
|
||||||
|
async removeFromPlaylist(userId, rawName, oneBasedIndex) {
|
||||||
|
await this.ready();
|
||||||
|
const name = sanitizePlaylistName(rawName);
|
||||||
|
const playlist = await this.getPlaylist(userId, name);
|
||||||
|
if (!playlist) {
|
||||||
|
return { success: false, name, removedTrack: null, count: 0, error: "NOT_FOUND" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const idx = parseInt(oneBasedIndex, 10) - 1;
|
||||||
|
if (isNaN(idx) || idx < 0 || idx >= playlist.tracks.length) {
|
||||||
|
return { success: false, name, removedTrack: null, count: playlist.tracks.length, error: "INVALID_INDEX" };
|
||||||
|
}
|
||||||
|
|
||||||
|
const removedTrack = playlist.tracks.splice(idx, 1)[0];
|
||||||
|
try {
|
||||||
|
await this._pool.execute(
|
||||||
|
"UPDATE `user_playlists` SET `tracks` = ?, `updated_at` = CURRENT_TIMESTAMP WHERE `user_id` = ? AND `name` = ?",
|
||||||
|
[JSON.stringify(playlist.tracks), userId, name]
|
||||||
|
);
|
||||||
|
return { success: true, name, removedTrack, count: playlist.tracks.length };
|
||||||
|
} catch (err) {
|
||||||
|
logger.error("[PlaylistManager] Error removing track from playlist:", err?.message);
|
||||||
|
return { success: false, name, removedTrack: null, count: playlist.tracks.length, error: "DB_ERROR" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,657 @@
|
|||||||
|
/**
|
||||||
|
* @module src/services/StatusChannelManager
|
||||||
|
* @description Dedicated status channel and automated incident management for Remix.
|
||||||
|
* Manages two core operational components:
|
||||||
|
* 1. A self-editing live status card in a designated Fluxer channel,
|
||||||
|
* reporting real-time gateway latency, active music channels, listeners,
|
||||||
|
* RAM/CPU metrics with visual Unicode progress bars, and subsystem status.
|
||||||
|
* 2. An event-driven incident monitor tracking Gateway, Audio Node (NodeLink),
|
||||||
|
* Database, Dashboard, and REST API availability with automatic downtime
|
||||||
|
* calculation and dual-color lifecycle embeds (🔴 Outage / ✅ Resolved).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
|
/** @type {string} Default API endpoint for direct REST fallback */
|
||||||
|
const DEFAULT_API_BASE = "https://fluxer.com/api/v1";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Detect transient network or socket reset errors that can be retried.
|
||||||
|
* @param {Error|object} err
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function isTransientNetworkError(err) {
|
||||||
|
if (!err) return false;
|
||||||
|
const msg = String(err?.message ?? err);
|
||||||
|
const cause = String(err?.cause?.message ?? err?.cause ?? "");
|
||||||
|
return (
|
||||||
|
/other side closed|fetch failed|ECONNRESET|ETIMEDOUT|ECONNREFUSED|UND_ERR_SOCKET|socket hang up/i.test(msg) ||
|
||||||
|
/other side closed|ECONNRESET|ETIMEDOUT|ECONNREFUSED|UND_ERR_SOCKET/i.test(cause)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class StatusChannelManager
|
||||||
|
* @description Oversees public status notifications and live health telemetry.
|
||||||
|
*/
|
||||||
|
export class StatusChannelManager {
|
||||||
|
/**
|
||||||
|
* @param {object} remix - The main Remix bot instance.
|
||||||
|
* @param {object} [config] - The statusChannel config section.
|
||||||
|
*/
|
||||||
|
constructor(remix, config = {}) {
|
||||||
|
this.remix = remix;
|
||||||
|
this.client = remix.client;
|
||||||
|
this.config = config || {};
|
||||||
|
|
||||||
|
this.enabled = this.config.enabled === true;
|
||||||
|
this.channelId = typeof this.config.channelId === "string" && this.config.channelId.trim()
|
||||||
|
? this.config.channelId.trim()
|
||||||
|
: null;
|
||||||
|
this.mentionRoleId = typeof this.config.mentionRoleId === "string" && this.config.mentionRoleId.trim()
|
||||||
|
? this.config.mentionRoleId.trim()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const rawInterval = Number(this.config.updateIntervalSeconds);
|
||||||
|
this.updateIntervalMs = Math.max(60, Number.isFinite(rawInterval) && rawInterval > 0 ? rawInterval : 300) * 1000;
|
||||||
|
|
||||||
|
this.statusPageUrl = typeof this.config.statusPageUrl === "string" && this.config.statusPageUrl.trim()
|
||||||
|
? this.config.statusPageUrl.trim()
|
||||||
|
: "status.remix.bot";
|
||||||
|
|
||||||
|
this.statePath = path.join(process.cwd(), "storage", "status_card.json");
|
||||||
|
this.liveMessageId = typeof this.config.liveMessageId === "string" && this.config.liveMessageId.trim()
|
||||||
|
? this.config.liveMessageId.trim()
|
||||||
|
: null;
|
||||||
|
|
||||||
|
this.apiBase = remix.config?.instanceUrl
|
||||||
|
? String(remix.config.instanceUrl).trim().replace(/\/+$/, "")
|
||||||
|
: DEFAULT_API_BASE;
|
||||||
|
|
||||||
|
this._timer = null;
|
||||||
|
this._dashboardProbeTimer = null;
|
||||||
|
this._isUpdating = false;
|
||||||
|
this._lastCpuUsage = null;
|
||||||
|
this._lastCpuTime = null;
|
||||||
|
|
||||||
|
this.incidents = new Map([
|
||||||
|
["gateway", { name: "Fluxer Gateway", down: false, startedAt: 0, impact: "Critical" }],
|
||||||
|
["audioNode", { name: "Audio Engine (NodeLink)", down: false, startedAt: 0, impact: "High" }],
|
||||||
|
["database", { name: "Database (MySQL)", down: false, startedAt: 0, impact: "High" }],
|
||||||
|
["dashboard", { name: "Web Dashboard", down: false, startedAt: 0, impact: "Low" }],
|
||||||
|
["api", { name: "Fluxer REST API", down: false, startedAt: 0, impact: "Critical" }],
|
||||||
|
]);
|
||||||
|
|
||||||
|
this._loadState();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translate a key using the Remix locale system.
|
||||||
|
* @param {string} key
|
||||||
|
* @param {object} [data]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
t(key, data = {}) {
|
||||||
|
return this.remix?.locale?.translate?.(null, key, data) ?? key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start the periodic health card update loop and dashboard probing.
|
||||||
|
*/
|
||||||
|
start() {
|
||||||
|
if (!this.enabled || !this.channelId) {
|
||||||
|
logger.info("[StatusChannel] Disabled (enabled=false or missing channelId).");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`[StatusChannel] Active — monitoring channel ${this.channelId} (interval: ${this.updateIntervalMs / 1000}s).`);
|
||||||
|
|
||||||
|
/* Initial update delayed slightly so initial connections settle */
|
||||||
|
setTimeout(() => {
|
||||||
|
this.updateLiveCard().catch((err) => {
|
||||||
|
logger.warn("[StatusChannel] Initial live card update failed:", err?.message);
|
||||||
|
});
|
||||||
|
}, 5000);
|
||||||
|
|
||||||
|
if (this._timer) clearInterval(this._timer);
|
||||||
|
this._timer = setInterval(() => {
|
||||||
|
this.updateLiveCard().catch((err) => {
|
||||||
|
logger.warn("[StatusChannel] Periodic live card update failed:", err?.message);
|
||||||
|
});
|
||||||
|
}, this.updateIntervalMs);
|
||||||
|
this._timer.unref?.();
|
||||||
|
|
||||||
|
this._setupDashboardProbe();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stop background timers and release resources.
|
||||||
|
*/
|
||||||
|
destroy() {
|
||||||
|
if (this._timer) {
|
||||||
|
clearInterval(this._timer);
|
||||||
|
this._timer = null;
|
||||||
|
}
|
||||||
|
if (this._dashboardProbeTimer) {
|
||||||
|
clearInterval(this._dashboardProbeTimer);
|
||||||
|
this._dashboardProbeTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trigger an incident for a given subsystem.
|
||||||
|
* @param {"gateway"|"audioNode"|"database"|"dashboard"|"api"} key
|
||||||
|
* @param {string} [reason]
|
||||||
|
*/
|
||||||
|
async triggerIncident(key, reason = "") {
|
||||||
|
if (!this.enabled || !this.channelId) return;
|
||||||
|
|
||||||
|
const inc = this.incidents.get(key);
|
||||||
|
if (!inc || inc.down) return;
|
||||||
|
|
||||||
|
inc.down = true;
|
||||||
|
inc.startedAt = Date.now();
|
||||||
|
const startedSec = Math.floor(inc.startedAt / 1000);
|
||||||
|
|
||||||
|
const desc = reason || this.t("responses.statusChannel.incidentDefaultDesc", { name: inc.name });
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe74c3c)
|
||||||
|
.setAuthor({ name: this.t("responses.statusChannel.incidentAuthor") })
|
||||||
|
.setTitle(this.t("responses.statusChannel.incidentTitle", { name: inc.name }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.addFields(
|
||||||
|
{ name: this.t("responses.statusChannel.startedField"), value: `<t:${startedSec}:f> (<t:${startedSec}:R>)`, inline: true },
|
||||||
|
{ name: this.t("responses.statusChannel.statusField"), value: this.t("responses.statusChannel.investigating"), inline: true },
|
||||||
|
{ name: this.t("responses.statusChannel.severityField"), value: inc.impact, inline: true }
|
||||||
|
)
|
||||||
|
.setFooter({ text: `Remix Incident Monitor • ${this.statusPageUrl}` })
|
||||||
|
.setTimestamp(new Date());
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
embeds: [embed],
|
||||||
|
};
|
||||||
|
if (this.mentionRoleId) {
|
||||||
|
payload.content = `<@&${this.mentionRoleId}>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this._postMessage(payload);
|
||||||
|
logger.info(`[StatusChannel] Incident published for ${inc.name}: ${desc}`);
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn(`[StatusChannel] Failed to post incident for ${inc.name}:`, err?.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Force an immediate edit on the live card to reflect degraded/critical state */
|
||||||
|
this.updateLiveCard().catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve an ongoing incident for a given subsystem.
|
||||||
|
* @param {"gateway"|"audioNode"|"database"|"dashboard"|"api"} key
|
||||||
|
* @param {string} [resolutionNote]
|
||||||
|
*/
|
||||||
|
async resolveIncident(key, resolutionNote = "") {
|
||||||
|
if (!this.enabled || !this.channelId) return;
|
||||||
|
|
||||||
|
const inc = this.incidents.get(key);
|
||||||
|
if (!inc || !inc.down) return;
|
||||||
|
|
||||||
|
const resolvedAt = Date.now();
|
||||||
|
const durationMs = Math.max(1000, resolvedAt - (inc.startedAt || resolvedAt));
|
||||||
|
inc.down = false;
|
||||||
|
inc.startedAt = 0;
|
||||||
|
|
||||||
|
const resolvedSec = Math.floor(resolvedAt / 1000);
|
||||||
|
const downtimeStr = this._formatDuration(durationMs);
|
||||||
|
const desc = resolutionNote || this.t("responses.statusChannel.resolvedDefaultDesc", { name: inc.name });
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0x2ecc71)
|
||||||
|
.setAuthor({ name: this.t("responses.statusChannel.resolvedAuthor") })
|
||||||
|
.setTitle(this.t("responses.statusChannel.resolvedTitle", { name: inc.name }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.addFields(
|
||||||
|
{ name: this.t("responses.statusChannel.downtimeField"), value: `**${downtimeStr}**`, inline: true },
|
||||||
|
{ name: this.t("responses.statusChannel.resolvedField"), value: `<t:${resolvedSec}:f> (<t:${resolvedSec}:R>)`, inline: true },
|
||||||
|
{ name: this.t("responses.statusChannel.statusField"), value: this.t("responses.statusChannel.stable"), inline: true }
|
||||||
|
)
|
||||||
|
.setFooter({ text: `Remix Incident Monitor • ${this.statusPageUrl}` })
|
||||||
|
.setTimestamp(new Date());
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this._postMessage({ embeds: [embed] });
|
||||||
|
logger.info(`[StatusChannel] Incident resolved for ${inc.name} (Downtime: ${downtimeStr})`);
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn(`[StatusChannel] Failed to post incident resolution for ${inc.name}:`, err?.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Update live card back to operational */
|
||||||
|
this.updateLiveCard().catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build and update the live status card in the configured channel.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async updateLiveCard() {
|
||||||
|
if (!this.enabled || !this.channelId || this._isUpdating) return;
|
||||||
|
this._isUpdating = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const embed = this._buildLiveCardEmbed();
|
||||||
|
|
||||||
|
if (this.liveMessageId) {
|
||||||
|
try {
|
||||||
|
await this._patchMessage(this.liveMessageId, { embeds: [embed] });
|
||||||
|
this._consecutivePatchFailures = 0;
|
||||||
|
return;
|
||||||
|
} catch (err) {
|
||||||
|
const status = err?.statusCode ?? err?.status;
|
||||||
|
/* If message was deleted (404), fall through to post a fresh one */
|
||||||
|
if (status === 404) {
|
||||||
|
this.liveMessageId = null;
|
||||||
|
} else {
|
||||||
|
this._consecutivePatchFailures = (this._consecutivePatchFailures || 0) + 1;
|
||||||
|
/* Only log warning if not a transient network drop or if failing repeatedly */
|
||||||
|
if (!isTransientNetworkError(err) || this._consecutivePatchFailures >= 3) {
|
||||||
|
logger.warn("[StatusChannel] Failed to patch status card:", err?.message);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Post a new live card message and persist ID */
|
||||||
|
const sent = await this._postMessage({ embeds: [embed] });
|
||||||
|
const newId = sent?.id ?? sent?.message?.id ?? null;
|
||||||
|
if (newId) {
|
||||||
|
this.liveMessageId = String(newId);
|
||||||
|
this._saveState();
|
||||||
|
logger.info(`[StatusChannel] New status card created (ID: ${this.liveMessageId})`);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
this._isUpdating = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructs the live status embed with current system and bot metrics.
|
||||||
|
* @private
|
||||||
|
* @returns {EmbedBuilder}
|
||||||
|
*/
|
||||||
|
_buildLiveCardEmbed() {
|
||||||
|
const ping = Math.round(Number(this.client?.ws?.ping ?? this.client?.ping ?? 0));
|
||||||
|
const uptimeMs = process.uptime() * 1000;
|
||||||
|
const uptimeStr = this._formatUptime(uptimeMs);
|
||||||
|
|
||||||
|
/* Active music playback metrics */
|
||||||
|
const playerMap = this.remix.players?.playerMap;
|
||||||
|
const activePlayers = playerMap ? [...new Set(playerMap.values())].filter((p) => p && !p._destroyed && !p.leaving).length : 0;
|
||||||
|
let totalListeners = 0;
|
||||||
|
if (playerMap) {
|
||||||
|
for (const p of playerMap.values()) {
|
||||||
|
if (!p || p._destroyed) continue;
|
||||||
|
const members = p.getVoiceMembers?.();
|
||||||
|
if (Array.isArray(members)) {
|
||||||
|
totalListeners += members.filter((m) => !m.bot).length;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Hardware metrics */
|
||||||
|
const mem = this._getMemoryInfo();
|
||||||
|
const cpuPct = this._getCpuUsagePercent();
|
||||||
|
const cpuCores = os.cpus()?.length || 1;
|
||||||
|
const ramBar = this._createProgressBar(mem.systemPct, 10);
|
||||||
|
const cpuBar = this._createProgressBar(cpuPct, 10);
|
||||||
|
|
||||||
|
/* Subsystem status synthesis */
|
||||||
|
const { list: subsystems, overallState } = this._getSubsystemsHealth();
|
||||||
|
|
||||||
|
let color = 0x2ecc71;
|
||||||
|
let stateBadge = this.t("responses.statusChannel.operationalDesc");
|
||||||
|
if (overallState === "critical") {
|
||||||
|
color = 0xe74c3c;
|
||||||
|
stateBadge = this.t("responses.statusChannel.criticalDesc");
|
||||||
|
} else if (overallState === "degraded") {
|
||||||
|
color = 0xf1c40f;
|
||||||
|
stateBadge = this.t("responses.statusChannel.degradedDesc");
|
||||||
|
}
|
||||||
|
|
||||||
|
const guildCount = this.client?.guilds?.cache?.size ?? this.client?.guilds?.size ?? 0;
|
||||||
|
const intervalSec = Math.round(this.updateIntervalMs / 1000);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(color)
|
||||||
|
.setAuthor({
|
||||||
|
name: this.t("responses.statusChannel.liveCardAuthor"),
|
||||||
|
icon_url: this.client?.user?.avatarURL?.() ?? null,
|
||||||
|
})
|
||||||
|
.setTitle(this.t("responses.statusChannel.liveCardTitle"))
|
||||||
|
.setDescription(stateBadge)
|
||||||
|
.addFields(
|
||||||
|
{ name: this.t("responses.statusChannel.gatewayField"), value: `${ping > 0 ? ping : "< 1"} ms`, inline: true },
|
||||||
|
{ name: this.t("responses.statusChannel.uptimeField"), value: uptimeStr, inline: true },
|
||||||
|
{ name: this.t("responses.statusChannel.sessionsField"), value: `${activePlayers} active (${totalListeners} listeners)`, inline: true },
|
||||||
|
{ name: this.t("responses.statusChannel.ramField"), value: `\`${ramBar}\` ${mem.systemPct}%\n${mem.rssMb} MB / ${mem.totalMemMb} MB`, inline: true },
|
||||||
|
{ name: this.t("responses.statusChannel.cpuField"), value: `\`${cpuBar}\` ${cpuPct}%\n${cpuCores} cores available`, inline: true },
|
||||||
|
{ name: this.t("responses.statusChannel.guildsField"), value: `${guildCount.toLocaleString()} communities`, inline: true },
|
||||||
|
{
|
||||||
|
name: this.t("responses.statusChannel.subsystemsField"),
|
||||||
|
value: subsystems.map((s) => `• **${s.name}**: ${s.status}`).join("\n"),
|
||||||
|
inline: false,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.setFooter({ text: `Auto-updates every ${intervalSec}s • ${this.statusPageUrl}` })
|
||||||
|
.setTimestamp(new Date());
|
||||||
|
|
||||||
|
return embed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes the health overview of monitored dependencies.
|
||||||
|
* @private
|
||||||
|
* @returns {{list: Array<{name: string, status: string}>, overallState: "operational"|"degraded"|"critical"}}
|
||||||
|
*/
|
||||||
|
_getSubsystemsHealth() {
|
||||||
|
let hasCriticalDown = false;
|
||||||
|
let hasMinorDown = false;
|
||||||
|
const list = [];
|
||||||
|
|
||||||
|
for (const [key, inc] of this.incidents) {
|
||||||
|
if (key === "dashboard" && !this.remix.config?.dashboard?.enabled) {
|
||||||
|
list.push({ name: inc.name, status: `⚪ ${this.t("responses.statusChannel.disabled")}` });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (key === "audioNode" && inc.down && (this.remix.lavalink?._nodeConnected || Boolean(this.remix.lavalink?.getNode?.()))) {
|
||||||
|
/* Self-heal: audio engine node is connected and operational */
|
||||||
|
this.resolveIncident("audioNode", "Audio engine reconnected successfully").catch?.(() => {});
|
||||||
|
}
|
||||||
|
if (key === "gateway" && inc.down && this.remix._gatewayConnected) {
|
||||||
|
/* Self-heal: gateway connection is operational */
|
||||||
|
this.resolveIncident("gateway", "Fluxer Gateway reconnected").catch?.(() => {});
|
||||||
|
}
|
||||||
|
if (inc.down) {
|
||||||
|
list.push({ name: inc.name, status: `🔴 ${this.t("responses.statusChannel.outage")}` });
|
||||||
|
if (inc.impact === "Critical") hasCriticalDown = true;
|
||||||
|
else hasMinorDown = true;
|
||||||
|
} else {
|
||||||
|
list.push({ name: inc.name, status: `🟢 ${this.t("responses.statusChannel.operational")}` });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let overallState = "operational";
|
||||||
|
if (hasCriticalDown) overallState = "critical";
|
||||||
|
else if (hasMinorDown) overallState = "degraded";
|
||||||
|
|
||||||
|
return { list, overallState };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Background probe for the Web Dashboard if enabled.
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_setupDashboardProbe() {
|
||||||
|
if (!this.remix.config?.dashboard?.enabled) return;
|
||||||
|
|
||||||
|
const probe = async () => {
|
||||||
|
try {
|
||||||
|
const rawUrl = this.remix.config?.dashboard?.url;
|
||||||
|
const port = this.remix.config?.dashboard?.port || this.remix.dashboard?.port;
|
||||||
|
const targetUrl = rawUrl || (port ? `http://127.0.0.1:${port}/` : null);
|
||||||
|
|
||||||
|
if (targetUrl) {
|
||||||
|
const res = await fetch(targetUrl, {
|
||||||
|
signal: AbortSignal.timeout(4000),
|
||||||
|
});
|
||||||
|
if (res.ok || res.status === 401 || res.status === 403 || res.status === 302) {
|
||||||
|
this.resolveIncident("dashboard");
|
||||||
|
} else {
|
||||||
|
this.triggerIncident("dashboard", `Dashboard HTTP check returned status ${res.status}`);
|
||||||
|
}
|
||||||
|
} else if (this.remix.dashboard?.redis) {
|
||||||
|
/* When dashboard runs as decoupled service via Redis pub/sub, verify Redis IPC */
|
||||||
|
if (typeof this.remix.dashboard.redis.isReady === "function" && this.remix.dashboard.redis.isReady()) {
|
||||||
|
this.resolveIncident("dashboard");
|
||||||
|
} else {
|
||||||
|
this.triggerIncident("dashboard", "Dashboard Redis bridge disconnected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
this.triggerIncident("dashboard", `Dashboard is unreachable (${err?.message})`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
this._dashboardProbeTimer = setInterval(probe, 60_000);
|
||||||
|
this._dashboardProbeTimer.unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper to format millisecond durations into clean time strings.
|
||||||
|
* @private
|
||||||
|
* @param {number} ms
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
_formatDuration(ms) {
|
||||||
|
const totalSec = Math.max(0, Math.floor(ms / 1000));
|
||||||
|
const h = Math.floor(totalSec / 3600);
|
||||||
|
const m = Math.floor((totalSec % 3600) / 60);
|
||||||
|
const s = totalSec % 60;
|
||||||
|
if (h > 0) return `${h}h ${m}m ${s}s`;
|
||||||
|
if (m > 0) return `${m}m ${s}s`;
|
||||||
|
return `${s}s`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats process uptime into human-readable strings.
|
||||||
|
* @private
|
||||||
|
* @param {number} ms
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
_formatUptime(ms) {
|
||||||
|
const totalSec = Math.max(0, Math.floor(ms / 1000));
|
||||||
|
const d = Math.floor(totalSec / 86400);
|
||||||
|
const h = Math.floor((totalSec % 86400) / 3600);
|
||||||
|
const m = Math.floor((totalSec % 3600) / 60);
|
||||||
|
if (d > 0) return `${d}d ${h}h ${m}m`;
|
||||||
|
if (h > 0) return `${h}h ${m}m`;
|
||||||
|
return `${m}m`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a visual Unicode progress bar.
|
||||||
|
* @private
|
||||||
|
* @param {number} percent
|
||||||
|
* @param {number} [length=10]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
_createProgressBar(percent, length = 10) {
|
||||||
|
const clamped = Math.max(0, Math.min(100, Math.round(percent)));
|
||||||
|
const filled = Math.round((clamped / 100) * length);
|
||||||
|
const empty = Math.max(0, length - filled);
|
||||||
|
return "█".repeat(filled) + "░".repeat(empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Measures delta CPU percentage over the elapsed update window.
|
||||||
|
* @private
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
_getCpuUsagePercent() {
|
||||||
|
const currentUsage = process.cpuUsage();
|
||||||
|
const now = Date.now();
|
||||||
|
if (!this._lastCpuUsage || !this._lastCpuTime) {
|
||||||
|
this._lastCpuUsage = currentUsage;
|
||||||
|
this._lastCpuTime = now;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const elapsedMs = now - this._lastCpuTime;
|
||||||
|
const userDiff = (currentUsage.user - this._lastCpuUsage.user) / 1000;
|
||||||
|
const sysDiff = (currentUsage.system - this._lastCpuUsage.system) / 1000;
|
||||||
|
const totalDiff = userDiff + sysDiff;
|
||||||
|
|
||||||
|
this._lastCpuUsage = currentUsage;
|
||||||
|
this._lastCpuTime = now;
|
||||||
|
|
||||||
|
if (elapsedMs <= 0) return 0;
|
||||||
|
const cores = os.cpus()?.length || 1;
|
||||||
|
return Math.min(100, Math.max(0, Math.round((totalDiff / (elapsedMs * cores)) * 100)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Memory statistics for the host and current process.
|
||||||
|
* @private
|
||||||
|
* @returns {{rssMb: number, totalMemMb: number, systemPct: number}}
|
||||||
|
*/
|
||||||
|
_getMemoryInfo() {
|
||||||
|
const mem = process.memoryUsage();
|
||||||
|
const rssMb = Math.round(mem.rss / (1024 * 1024));
|
||||||
|
const totalMemMb = Math.round(os.totalmem() / (1024 * 1024));
|
||||||
|
const freeMemMb = Math.round(os.freemem() / (1024 * 1024));
|
||||||
|
const usedSys = Math.max(0, totalMemMb - freeMemMb);
|
||||||
|
const systemPct = Math.min(100, Math.max(0, Math.round((usedSys / totalMemMb) * 100)));
|
||||||
|
return { rssMb, totalMemMb, systemPct };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalizes payload for client REST or raw fetch calls.
|
||||||
|
* @private
|
||||||
|
* @param {object} data
|
||||||
|
* @returns {object}
|
||||||
|
*/
|
||||||
|
_normalizePayload(data) {
|
||||||
|
if (data && typeof data === "object") {
|
||||||
|
if (Array.isArray(data.embeds)) {
|
||||||
|
return {
|
||||||
|
...data,
|
||||||
|
embeds: data.embeds.map((e) => (typeof e?.toJSON === "function" ? e.toJSON() : e)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (data.embed) {
|
||||||
|
const raw = typeof data.embed.toJSON === "function" ? data.embed.toJSON() : data.embed;
|
||||||
|
return { embeds: [raw] };
|
||||||
|
}
|
||||||
|
if (typeof data.toJSON === "function") {
|
||||||
|
return { embeds: [data.toJSON()] };
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
return { content: String(data ?? "") };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post a message to the status channel with raw fetch fallback and transient retry.
|
||||||
|
* @private
|
||||||
|
* @param {object} payload
|
||||||
|
* @param {number} [retries=2]
|
||||||
|
* @returns {Promise<object>}
|
||||||
|
*/
|
||||||
|
async _postMessage(payload, retries = 2) {
|
||||||
|
const body = this._normalizePayload(payload);
|
||||||
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||||
|
try {
|
||||||
|
const rest = this.client?.rest;
|
||||||
|
if (typeof rest?.post === "function") {
|
||||||
|
return await rest.post(`/channels/${this.channelId}/messages`, { body });
|
||||||
|
}
|
||||||
|
const token = this.client?.token || this.remix.config?.token;
|
||||||
|
const res = await fetch(`${this.apiBase}/channels/${this.channelId}/messages`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(10_000),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error("HTTP " + res.status);
|
||||||
|
return await res.json().catch(() => ({}));
|
||||||
|
} catch (err) {
|
||||||
|
if (attempt < retries && isTransientNetworkError(err)) {
|
||||||
|
await new Promise((res) => setTimeout(res, 1_000 * (attempt + 1)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Patch an existing message in the status channel with raw fetch fallback and transient retry.
|
||||||
|
* @private
|
||||||
|
* @param {string} messageId
|
||||||
|
* @param {object} payload
|
||||||
|
* @param {number} [retries=2]
|
||||||
|
* @returns {Promise<object>}
|
||||||
|
*/
|
||||||
|
async _patchMessage(messageId, payload, retries = 2) {
|
||||||
|
const body = this._normalizePayload(payload);
|
||||||
|
for (let attempt = 0; attempt <= retries; attempt++) {
|
||||||
|
try {
|
||||||
|
const rest = this.client?.rest;
|
||||||
|
if (typeof rest?.patch === "function") {
|
||||||
|
return await rest.patch(`/channels/${this.channelId}/messages/${messageId}`, { body });
|
||||||
|
}
|
||||||
|
const token = this.client?.token || this.remix.config?.token;
|
||||||
|
const res = await fetch(`${this.apiBase}/channels/${this.channelId}/messages/${messageId}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(10_000),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error("HTTP " + res.status);
|
||||||
|
return await res.json().catch(() => ({}));
|
||||||
|
} catch (err) {
|
||||||
|
if (attempt < retries && isTransientNetworkError(err)) {
|
||||||
|
await new Promise((res) => setTimeout(res, 1_000 * (attempt + 1)));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load persisted card ID from disk.
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_loadState() {
|
||||||
|
try {
|
||||||
|
if (fs.existsSync(this.statePath)) {
|
||||||
|
const raw = fs.readFileSync(this.statePath, "utf8");
|
||||||
|
const parsed = JSON.parse(raw);
|
||||||
|
if (parsed?.liveMessageId) {
|
||||||
|
this.liveMessageId = String(parsed.liveMessageId).trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save card ID to disk.
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_saveState() {
|
||||||
|
try {
|
||||||
|
const dir = path.dirname(this.statePath);
|
||||||
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||||
|
fs.writeFileSync(
|
||||||
|
this.statePath,
|
||||||
|
JSON.stringify(
|
||||||
|
{
|
||||||
|
liveMessageId: this.liveMessageId,
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2
|
||||||
|
),
|
||||||
|
"utf8"
|
||||||
|
);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default StatusChannelManager;
|
||||||
@@ -243,8 +243,8 @@ export class LastFmManager {
|
|||||||
|
|
||||||
/** @private Extract the duration in seconds from a track object, supporting number (ms), object with .seconds, ISO 8601, or plain seconds. @param {object} track - Track object. @returns {string|number} Duration in seconds, or empty string if unavailable. */
|
/** @private Extract the duration in seconds from a track object, supporting number (ms), object with .seconds, ISO 8601, or plain seconds. @param {object} track - Track object. @returns {string|number} Duration in seconds, or empty string if unavailable. */
|
||||||
_extractDurationSec(track) {
|
_extractDurationSec(track) {
|
||||||
if (!track.duration) return "";
|
if (!track?.duration) return "";
|
||||||
if (typeof track.duration === "object" && track.duration.seconds) return track.duration.seconds;
|
if (typeof track.duration === "object" && track.duration?.seconds) return track.duration.seconds;
|
||||||
if (typeof track.duration === "number") return Math.round(track.duration / 1000);
|
if (typeof track.duration === "number") return Math.round(track.duration / 1000);
|
||||||
if (typeof track.duration === "string") {
|
if (typeof track.duration === "string") {
|
||||||
const m = track.duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
|
const m = track.duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
|
||||||
@@ -260,9 +260,9 @@ export class LastFmManager {
|
|||||||
* @returns {boolean} True if the track meets the scrobble threshold.
|
* @returns {boolean} True if the track meets the scrobble threshold.
|
||||||
*/
|
*/
|
||||||
shouldScrobble(track, playedMs) {
|
shouldScrobble(track, playedMs) {
|
||||||
const durationMs = typeof track.duration === "object" && track.duration.seconds
|
const durationMs = track?.duration?.seconds != null
|
||||||
? track.duration.seconds * 1000
|
? track.duration.seconds * 1000
|
||||||
: typeof track.duration === "number"
|
: typeof track?.duration === "number"
|
||||||
? track.duration
|
? track.duration
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
import { apiCall, isLastFmFatalLinkError, isLastFmUserNotFound, noteStaleUser } from "./constants.mjs";
|
import { apiCall, isLastFmFatalLinkError, isLastFmUserNotFound, isLastFmNotFound, noteStaleUser } from "./constants.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {object}
|
* @type {object}
|
||||||
@@ -48,6 +48,7 @@ const ScrobblingMixin = {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (isLastFmNotFound(err)) return;
|
||||||
logger.warn(`[LastFm] updateNowPlaying failed for ${userId}: ${err.message}`);
|
logger.warn(`[LastFm] updateNowPlaying failed for ${userId}: ${err.message}`);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -89,6 +90,7 @@ const ScrobblingMixin = {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (isLastFmNotFound(err)) return;
|
||||||
logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`);
|
logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -124,7 +126,7 @@ const ScrobblingMixin = {
|
|||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
if (!e?.message?.includes("fetch failed")) {
|
if (!isLastFmNotFound(e) && !e?.message?.includes("fetch failed")) {
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logger.warn("[LastFm] Error:", e?.message);
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
|
|||||||
@@ -7,7 +7,17 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
import { isLastFmUserNotFound, noteStaleUser } from "./constants.mjs";
|
import { isLastFmUserNotFound, isLastFmNotFound, noteStaleUser } from "./constants.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Log failure only if it is an unexpected error, suppressing expected Last.fm not-found responses.
|
||||||
|
* @param {Error} e
|
||||||
|
*/
|
||||||
|
function logStatsWarning(e) {
|
||||||
|
if (isLastFmNotFound(e)) return;
|
||||||
|
logger.warn("[LastFm] Error:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {object}
|
* @type {object}
|
||||||
@@ -51,7 +61,7 @@ const ServerStatsMixin = {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logStatsWarning(e);
|
||||||
return {
|
return {
|
||||||
userId: uid,
|
userId: uid,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
@@ -110,7 +120,7 @@ const ServerStatsMixin = {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logStatsWarning(e);
|
||||||
return {
|
return {
|
||||||
userId: uid,
|
userId: uid,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
@@ -169,7 +179,7 @@ const ServerStatsMixin = {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logStatsWarning(e);
|
||||||
return {
|
return {
|
||||||
userId: uid,
|
userId: uid,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
@@ -240,7 +250,7 @@ const ServerStatsMixin = {
|
|||||||
matchPercentage,
|
matchPercentage,
|
||||||
};
|
};
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logStatsWarning(e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -340,7 +350,7 @@ const ServerStatsMixin = {
|
|||||||
);
|
);
|
||||||
return Number(rows[0]?.linked_users ?? 0);
|
return Number(rows[0]?.linked_users ?? 0);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logStatsWarning(e);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -506,7 +516,7 @@ const ServerStatsMixin = {
|
|||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logStatsWarning(e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -586,7 +596,7 @@ const ServerStatsMixin = {
|
|||||||
|
|
||||||
crowns.sort((a, b) => b.userPlaycount - a.userPlaycount);
|
crowns.sort((a, b) => b.userPlaycount - a.userPlaycount);
|
||||||
return crowns;
|
return crowns;
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logStatsWarning(e); return []; }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,17 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
import { apiCall, normalizeTrackText } from "./constants.mjs";
|
import { apiCall, normalizeTrackText, isLastFmNotFound } from "./constants.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Log query failure only if it is an unexpected error, suppressing expected Last.fm not-found responses.
|
||||||
|
* @param {Error} e
|
||||||
|
*/
|
||||||
|
function logQueryWarning(e) {
|
||||||
|
if (isLastFmNotFound(e)) return;
|
||||||
|
logger.warn("[LastFm] Error:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {object}
|
* @type {object}
|
||||||
@@ -34,7 +44,7 @@ const TrackQueriesMixin = {
|
|||||||
const data = await apiCall(params, this.apiSecret);
|
const data = await apiCall(params, this.apiSecret);
|
||||||
return data.track;
|
return data.track;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logQueryWarning(e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -226,7 +236,7 @@ const TrackQueriesMixin = {
|
|||||||
url: t.url ?? "",
|
url: t.url ?? "",
|
||||||
match: parseFloat(t.match ?? 0),
|
match: parseFloat(t.match ?? 0),
|
||||||
})).filter(t => t.match > 0.1);
|
})).filter(t => t.match > 0.1);
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -273,7 +283,7 @@ const TrackQueriesMixin = {
|
|||||||
userplaycount: a.stats?.userplaycount ? Number(a.stats.userplaycount) : null,
|
userplaycount: a.stats?.userplaycount ? Number(a.stats.userplaycount) : null,
|
||||||
};
|
};
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logQueryWarning(e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -321,7 +331,7 @@ const TrackQueriesMixin = {
|
|||||||
userplaycount: a.userplaycount ? Number(a.userplaycount) : null,
|
userplaycount: a.userplaycount ? Number(a.userplaycount) : null,
|
||||||
};
|
};
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logQueryWarning(e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -354,7 +364,7 @@ const TrackQueriesMixin = {
|
|||||||
playcount: Number(t.playcount ?? 0),
|
playcount: Number(t.playcount ?? 0),
|
||||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -385,7 +395,7 @@ const TrackQueriesMixin = {
|
|||||||
playcount: Number(a.playcount ?? 0),
|
playcount: Number(a.playcount ?? 0),
|
||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -415,7 +425,7 @@ const TrackQueriesMixin = {
|
|||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
match: parseFloat(a.match ?? 0),
|
match: parseFloat(a.match ?? 0),
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -448,7 +458,7 @@ const TrackQueriesMixin = {
|
|||||||
summary: t.wiki?.summary ?? "",
|
summary: t.wiki?.summary ?? "",
|
||||||
};
|
};
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[LastFm] Error:", e?.message);
|
logQueryWarning(e);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -481,7 +491,7 @@ const TrackQueriesMixin = {
|
|||||||
playcount: Number(t.playcount ?? 0),
|
playcount: Number(t.playcount ?? 0),
|
||||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -511,7 +521,7 @@ const TrackQueriesMixin = {
|
|||||||
playcount: Number(a.playcount ?? 0),
|
playcount: Number(a.playcount ?? 0),
|
||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -548,7 +558,7 @@ const TrackQueriesMixin = {
|
|||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
listeners: Number(a.listeners ?? 0),
|
listeners: Number(a.listeners ?? 0),
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -585,7 +595,7 @@ const TrackQueriesMixin = {
|
|||||||
url: a.url ?? "",
|
url: a.url ?? "",
|
||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -609,7 +619,7 @@ const TrackQueriesMixin = {
|
|||||||
url: t.url ?? "",
|
url: t.url ?? "",
|
||||||
count: Number(t.count ?? 0),
|
count: Number(t.count ?? 0),
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -635,7 +645,7 @@ const TrackQueriesMixin = {
|
|||||||
url: t.url ?? "",
|
url: t.url ?? "",
|
||||||
count: Number(t.count ?? 0),
|
count: Number(t.count ?? 0),
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -661,7 +671,7 @@ const TrackQueriesMixin = {
|
|||||||
url: t.url ?? "",
|
url: t.url ?? "",
|
||||||
count: Number(t.count ?? 0),
|
count: Number(t.count ?? 0),
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -687,7 +697,7 @@ const TrackQueriesMixin = {
|
|||||||
playcount: Number(a.playcount ?? 0),
|
playcount: Number(a.playcount ?? 0),
|
||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -712,7 +722,7 @@ const TrackQueriesMixin = {
|
|||||||
listeners: Number(a.listeners ?? 0),
|
listeners: Number(a.listeners ?? 0),
|
||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -738,7 +748,7 @@ const TrackQueriesMixin = {
|
|||||||
listeners: Number(t.listeners ?? 0),
|
listeners: Number(t.listeners ?? 0),
|
||||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -763,7 +773,7 @@ const TrackQueriesMixin = {
|
|||||||
playcount: Number(t.playcount ?? 0),
|
playcount: Number(t.playcount ?? 0),
|
||||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -787,7 +797,7 @@ const TrackQueriesMixin = {
|
|||||||
playcount: Number(a.playcount ?? 0),
|
playcount: Number(a.playcount ?? 0),
|
||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,17 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { logger } from "../../core/Logger.mjs";
|
import { logger } from "../../core/Logger.mjs";
|
||||||
import { apiCall } from "./constants.mjs";
|
import { apiCall, isLastFmNotFound } from "./constants.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Log query failure only if it is an unexpected error, suppressing expected Last.fm not-found responses.
|
||||||
|
* @param {Error} e
|
||||||
|
*/
|
||||||
|
function logQueryWarning(e) {
|
||||||
|
if (isLastFmNotFound(e)) return;
|
||||||
|
logger.warn("[LastFm] Error:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {object}
|
* @type {object}
|
||||||
@@ -115,7 +125,7 @@ const UserQueriesMixin = {
|
|||||||
url: t.url ?? "",
|
url: t.url ?? "",
|
||||||
count: Number(t.count ?? 0),
|
count: Number(t.count ?? 0),
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -144,7 +154,7 @@ const UserQueriesMixin = {
|
|||||||
from: Number(c.from ?? 0),
|
from: Number(c.from ?? 0),
|
||||||
to: Number(c.to ?? 0),
|
to: Number(c.to ?? 0),
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -442,7 +452,7 @@ const UserQueriesMixin = {
|
|||||||
query: `${t.name} ${t.artist ?? ar.name}`,
|
query: `${t.name} ${t.artist ?? ar.name}`,
|
||||||
image: t.image ?? ar.image ?? "",
|
image: t.image ?? ar.image ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
for (const r of artistResults) {
|
for (const r of artistResults) {
|
||||||
@@ -495,7 +505,7 @@ const UserQueriesMixin = {
|
|||||||
realname: f.realname ?? "",
|
realname: f.realname ?? "",
|
||||||
country: f.country ?? "",
|
country: f.country ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -525,7 +535,7 @@ const UserQueriesMixin = {
|
|||||||
playcount: Number(a.playcount ?? 0),
|
playcount: Number(a.playcount ?? 0),
|
||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -556,7 +566,7 @@ const UserQueriesMixin = {
|
|||||||
playcount: Number(t.playcount ?? 0),
|
playcount: Number(t.playcount ?? 0),
|
||||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -587,7 +597,7 @@ const UserQueriesMixin = {
|
|||||||
playcount: Number(a.playcount ?? 0),
|
playcount: Number(a.playcount ?? 0),
|
||||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||||
}));
|
}));
|
||||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
} catch (e) { logQueryWarning(e); return []; }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -63,6 +63,20 @@ function isLastFmUserNotFound(err) {
|
|||||||
return /user not found/i.test(String(err?.message ?? ""));
|
return /user not found/i.test(String(err?.message ?? ""));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether a Last.fm error is an expected "Not Found" response (track, artist, album, tag, or user not found, code 6).
|
||||||
|
* Common when querying streams, YouTube videos, or uncataloged tracks that do not exist in Last.fm's database.
|
||||||
|
* @param {Error|object} err
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
function isLastFmNotFound(err) {
|
||||||
|
if (!err) return false;
|
||||||
|
const msg = String(err?.message ?? err ?? "");
|
||||||
|
const code = Number(err?.code) || 0;
|
||||||
|
return code === 6
|
||||||
|
|| /track not found|artist not found|album not found|user not found|tag not found|could not be found/i.test(msg);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check whether an error means the stored Last.fm link is unrecoverable —
|
* Check whether an error means the stored Last.fm link is unrecoverable —
|
||||||
* the linked account no longer exists or its session was revoked. Deliberately
|
* the linked account no longer exists or its session was revoked. Deliberately
|
||||||
@@ -164,4 +178,4 @@ async function apiCall(params, apiSecret, post = false) {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { BASE_URL, normalizeTrackText, buildSignature, apiCall, LastFmApiError, isLastFmUserNotFound, isLastFmFatalLinkError, noteStaleUser, clearStaleUserFlag };
|
export { BASE_URL, normalizeTrackText, buildSignature, apiCall, LastFmApiError, isLastFmUserNotFound, isLastFmNotFound, isLastFmFatalLinkError, noteStaleUser, clearStaleUserFlag };
|
||||||
+55
-82
@@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* @module src/ui/HelpCommand
|
* @module src/ui/HelpCommand
|
||||||
* @description The rich tabbed help command (Home / Music / Utilities /
|
* @description The rich tabbed help command (Home / Music / Utilities /
|
||||||
* Support) rendered through RichPaginator, plus interception of plain-text
|
* Support) rendered through RichPaginator, with full i18n support and
|
||||||
* help aliases so both styles coexist.
|
* interception of plain-text help aliases.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { RichPaginator } from "./Paginators.mjs";
|
import { RichPaginator } from "./Paginators.mjs";
|
||||||
@@ -15,77 +15,45 @@ const HELP_SESSION_MS = 30 * 1000;
|
|||||||
/** @type {object[]} Tab definitions for the rich help. */
|
/** @type {object[]} Tab definitions for the rich help. */
|
||||||
const HELP_TABS = [
|
const HELP_TABS = [
|
||||||
{
|
{
|
||||||
emoji: "🏠",
|
key: "home",
|
||||||
title: "Home",
|
emoji: "🏠",
|
||||||
header: "Home Page",
|
titleKey: "cmdHandler.help.tabHome",
|
||||||
static: true,
|
headerKey: "cmdHandler.help.tabHomeHeader",
|
||||||
|
static: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
key: "music",
|
||||||
emoji: "🎵",
|
emoji: "🎵",
|
||||||
title: "Music",
|
titleKey: "cmdHandler.help.tabMusic",
|
||||||
header: "Music Commands",
|
headerKey: "cmdHandler.help.tabMusicHeader",
|
||||||
categories: ["music"],
|
categories: ["music"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
key: "util",
|
||||||
emoji: "🔧",
|
emoji: "🔧",
|
||||||
title: "Utilities",
|
titleKey: "cmdHandler.help.tabUtil",
|
||||||
header: "Utility Commands",
|
headerKey: "cmdHandler.help.tabUtilHeader",
|
||||||
categories: ["util", "default"],
|
categories: ["util", "default"],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
emoji: "ℹ️",
|
key: "support",
|
||||||
title: "Support",
|
emoji: "ℹ️",
|
||||||
header: "Support Info",
|
titleKey: "cmdHandler.help.tabSupport",
|
||||||
static: true,
|
headerKey: "cmdHandler.help.tabSupportHeader",
|
||||||
|
static: true,
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @private
|
* @private Build paginated content for a help category tab using localized strings.
|
||||||
* @param {string} prefix
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
function _helpHomeContent(prefix) {
|
|
||||||
return (
|
|
||||||
"**Remix** is a high-fidelity 24/7 music bot supporting YouTube, Spotify, SoundCloud, Deezer, and more.\n\n" +
|
|
||||||
"**✨ Core Highlights**\n" +
|
|
||||||
"• **48kHz Hi-Fi Audio** — Crystal-clear audio stream pipeline\n" +
|
|
||||||
"• **30+ Audio Filters** — Bassboost, 8D, Nightcore, Vaporwave, Equalizer\n" +
|
|
||||||
"• **Dynamic Normalizer** — EBU R128 loudness leveling across music sources\n" +
|
|
||||||
"• **24/7 Web Radio** — Over 30,000 global live radio stations\n\n" +
|
|
||||||
"**📂 Command Categories**\n" +
|
|
||||||
"🏠 • **Home** — Quick bot overview & status\n" +
|
|
||||||
"🎵 • **Music** — Playback, queue, search, filters (`" + prefix + "play`, `" + prefix + "skip`, `" + prefix + "queue`)\n" +
|
|
||||||
"🔧 • **Utility** — Settings, 24/7 voice, ping, vote (`" + prefix + "settings`, `" + prefix + "ping`)\n" +
|
|
||||||
"ℹ️ • **Support** — Community server & assistance\n\n" +
|
|
||||||
"💡 **Tip:** Click the tab emojis below to switch sections, or use `" + prefix + "help <command>` for detailed info."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @private
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
function _helpSupportContent() {
|
|
||||||
return (
|
|
||||||
"Need help, want to report a bug, or suggest new features?\n\n" +
|
|
||||||
"💬 **[Join Remix Support Server](https://fluxer.gg/remix)**\n\n" +
|
|
||||||
"**Team & Maintainers:**\n" +
|
|
||||||
"• **Fantic** — Community Manager\n" +
|
|
||||||
"• **Shadow** — Lead Developer\n" +
|
|
||||||
"• **NoLogicAlan** — Lead Developer\n\n" +
|
|
||||||
"You can also use `%invite` to add Remix to your server."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @private Build paginated content for a help category tab.
|
|
||||||
* @param {object} tab
|
* @param {object} tab
|
||||||
* @param {Array} allCmds
|
* @param {Array} allCmds
|
||||||
* @param {string} prefix
|
* @param {string} prefix
|
||||||
|
* @param {string|null} guildId
|
||||||
|
* @param {import('../commands/CommandHandler.mjs').CommandHandler} commandHandler
|
||||||
* @returns {string[]}
|
* @returns {string[]}
|
||||||
*/
|
*/
|
||||||
function _helpBuildCategoryPages(tab, allCmds, prefix) {
|
function _helpBuildCategoryPages(tab, allCmds, prefix, guildId, commandHandler) {
|
||||||
const cmds = allCmds
|
const cmds = allCmds
|
||||||
.filter(cmd => {
|
.filter(cmd => {
|
||||||
if (cmd.requirements?.some(r => r.ownerOnly)) return false;
|
if (cmd.requirements?.some(r => r.ownerOnly)) return false;
|
||||||
@@ -93,19 +61,23 @@ function _helpBuildCategoryPages(tab, allCmds, prefix) {
|
|||||||
})
|
})
|
||||||
.sort((a, b) => a.name.localeCompare(b.name));
|
.sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
|
||||||
if (cmds.length === 0) return ["_No commands available._"];
|
if (cmds.length === 0) {
|
||||||
|
return [commandHandler.t(guildId, "cmdHandler.help.noCommands")];
|
||||||
|
}
|
||||||
|
|
||||||
const pages = [];
|
const pages = [];
|
||||||
for (let i = 0; i < cmds.length; i += HELP_CMDS_PER_PAGE) {
|
for (let i = 0; i < cmds.length; i += HELP_CMDS_PER_PAGE) {
|
||||||
const slice = cmds.slice(i, i + HELP_CMDS_PER_PAGE);
|
const slice = cmds.slice(i, i + HELP_CMDS_PER_PAGE);
|
||||||
let page = "";
|
let page = "";
|
||||||
slice.forEach((cmd, j) => {
|
slice.forEach((cmd) => {
|
||||||
const d = (cmd.description || "No description.").split("\n")[0];
|
const translated = commandHandler.t(guildId, "commands." + cmd.name);
|
||||||
|
const d = (translated && translated !== "commands." + cmd.name ? translated : (cmd.description || "No description.")).split("\n")[0];
|
||||||
page += `\`${prefix}${cmd.name}\` — ${d}\n`;
|
page += `\`${prefix}${cmd.name}\` — ${d}\n`;
|
||||||
});
|
});
|
||||||
page += `\nTo learn more about a command, run \`${prefix}help <command name>\`!`;
|
page += commandHandler.t(guildId, "cmdHandler.help.learnMore");
|
||||||
if (cmds.length > HELP_CMDS_PER_PAGE)
|
if (cmds.length > HELP_CMDS_PER_PAGE) {
|
||||||
page += `\n\n**Tip:** Use ⬅️ ➡️ to scroll between pages.`;
|
page += commandHandler.t(guildId, "cmdHandler.help.subpageTip");
|
||||||
|
}
|
||||||
pages.push(page);
|
pages.push(page);
|
||||||
}
|
}
|
||||||
return pages;
|
return pages;
|
||||||
@@ -144,21 +116,19 @@ export class HelpCommand {
|
|||||||
|
|
||||||
const _reply = this._commands.replyHandler.bind(this._commands);
|
const _reply = this._commands.replyHandler.bind(this._commands);
|
||||||
this._commands.replyHandler = (message, msg) => {
|
this._commands.replyHandler = (message, msg) => {
|
||||||
if (typeof message === "string" && message.toLowerCase().includes("unknown command")) {
|
const content = msg?.content ?? msg?.message?.content ?? "";
|
||||||
const content = msg?.content ?? msg?.message?.content ?? "";
|
const guildId = msg?.channel?.channel?.guildId ?? msg?.message?.guildId;
|
||||||
const guildId = msg?.channel?.channel?.guildId ?? msg?.message?.guildId;
|
const prefix = this._commands.getPrefix(guildId);
|
||||||
const prefix = this._commands.getPrefix(guildId);
|
const botId = this._commands.client.user?.id;
|
||||||
const botId = this._commands.client.user?.id;
|
const ping = `<@${botId}>`;
|
||||||
const ping = `<@${botId}>`;
|
const pingBang = `<@!${botId}>`;
|
||||||
const pingBang = `<@!${botId}>`;
|
let body = null;
|
||||||
let body = null;
|
if (content.startsWith(prefix)) body = content.slice(prefix.length).trim();
|
||||||
if (content.startsWith(prefix)) body = content.slice(prefix.length).trim();
|
else if (content.startsWith(pingBang)) body = content.slice(pingBang.length).trim();
|
||||||
else if (content.startsWith(pingBang)) body = content.slice(pingBang.length).trim();
|
else if (content.startsWith(ping)) body = content.slice(ping.length).trim();
|
||||||
else if (content.startsWith(ping)) body = content.slice(ping.length).trim();
|
if (body !== null) {
|
||||||
if (body !== null) {
|
const first = body.split(/\s+/)[0]?.toLowerCase();
|
||||||
const first = body.split(/\s+/)[0]?.toLowerCase();
|
if (HELP_ALIASES.includes(first)) return;
|
||||||
if (HELP_ALIASES.includes(first)) return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return _reply(message, msg);
|
return _reply(message, msg);
|
||||||
};
|
};
|
||||||
@@ -212,6 +182,7 @@ export class HelpCommand {
|
|||||||
_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();
|
||||||
|
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
|
||||||
if (query && isNaN(Number(query))) {
|
if (query && isNaN(Number(query))) {
|
||||||
let currCmd = null;
|
let currCmd = null;
|
||||||
@@ -221,7 +192,6 @@ export class HelpCommand {
|
|||||||
c.aliases.some(a => a.toLowerCase() === word.toLowerCase())
|
c.aliases.some(a => a.toLowerCase() === word.toLowerCase())
|
||||||
);
|
);
|
||||||
if (!found) {
|
if (!found) {
|
||||||
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
|
||||||
msg.reply(this._commands.t(guildId, "cmdHandler.help.unknownCommand", { command: word, prefix }));
|
msg.reply(this._commands.t(guildId, "cmdHandler.help.unknownCommand", { command: word, prefix }));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -242,14 +212,17 @@ export class HelpCommand {
|
|||||||
.setStartTab(startTab);
|
.setStartTab(startTab);
|
||||||
|
|
||||||
for (const tab of HELP_TABS) {
|
for (const tab of HELP_TABS) {
|
||||||
|
const title = this._commands.t(guildId, tab.titleKey);
|
||||||
|
const header = this._commands.t(guildId, tab.headerKey);
|
||||||
if (tab.static) {
|
if (tab.static) {
|
||||||
const content = tab.title === "Home"
|
const contentKey = tab.key === "home"
|
||||||
? _helpHomeContent(prefix)
|
? "cmdHandler.help.homeContent"
|
||||||
: _helpSupportContent();
|
: "cmdHandler.help.supportContent";
|
||||||
paginator.addTab({ emoji: tab.emoji, title: tab.title, header: tab.header, content });
|
const content = this._commands.t(guildId, contentKey);
|
||||||
|
paginator.addTab({ emoji: tab.emoji, title, header, content });
|
||||||
} else {
|
} else {
|
||||||
const pages = _helpBuildCategoryPages(tab, allCmds, prefix);
|
const pages = _helpBuildCategoryPages(tab, allCmds, prefix, guildId, this._commands);
|
||||||
paginator.addTab({ emoji: tab.emoji, title: tab.title, header: tab.header, pages });
|
paginator.addTab({ emoji: tab.emoji, title, header, pages });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+273
-54
@@ -380,6 +380,74 @@ export class MessageHandler {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if an error is a transient socket, connection, or gateway HTTP failure.
|
||||||
|
* @param {Error|object} err
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
isTransientNetworkError(err) {
|
||||||
|
if (!err) return false;
|
||||||
|
const status = Number(err.statusCode ?? err.status);
|
||||||
|
if (status === 502 || status === 503 || status === 504 || status === 520 || status === 521 || status === 522 || status === 524) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const codes = new Set([
|
||||||
|
"UND_ERR_SOCKET",
|
||||||
|
"UND_ERR_CONNECT_TIMEOUT",
|
||||||
|
"UND_ERR_HEADERS_TIMEOUT",
|
||||||
|
"UND_ERR_BODY_TIMEOUT",
|
||||||
|
"ECONNRESET",
|
||||||
|
"ETIMEDOUT",
|
||||||
|
"EPIPE",
|
||||||
|
"EAI_AGAIN",
|
||||||
|
"ENOTFOUND",
|
||||||
|
"ECONNREFUSED",
|
||||||
|
]);
|
||||||
|
if (
|
||||||
|
codes.has(err.code) ||
|
||||||
|
codes.has(err.cause?.code) ||
|
||||||
|
codes.has(err.cause?.cause?.code)
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const full = `${err.message || ""} ${err.cause?.message || ""} ${err.cause?.cause?.message || ""}`.toLowerCase();
|
||||||
|
return (
|
||||||
|
full.includes("other side closed") ||
|
||||||
|
full.includes("fetch failed") ||
|
||||||
|
full.includes("socket hung up") ||
|
||||||
|
full.includes("network socket disconnected") ||
|
||||||
|
full.includes("econnreset")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if an error is a Fluxer API rate limit (429 / RATE_LIMITED).
|
||||||
|
* @param {Error|object} err
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
isRateLimitError(err) {
|
||||||
|
if (!err) return false;
|
||||||
|
if (err.name === "RateLimitError" || err.code === "RATE_LIMITED" || Number(err.statusCode ?? err.status) === 429) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const msg = String(err.message || "").toLowerCase();
|
||||||
|
return msg.includes("rate limited") || msg.includes("rate_limited");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate a backoff delay in ms based on rate-limit headers or defaults.
|
||||||
|
* @param {Error|object} err
|
||||||
|
* @param {number} attempt
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
getRateLimitDelayMs(err, attempt) {
|
||||||
|
const retrySec = Number(err?.retryAfter ?? err?.rawBody?.retry_after ?? err?.headers?.get?.("retry-after"));
|
||||||
|
if (Number.isFinite(retrySec) && retrySec > 0) {
|
||||||
|
return Math.min(Math.ceil(retrySec * 1000) + 100, 5000);
|
||||||
|
}
|
||||||
|
return 300 * attempt;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @async Reply to a message with permission checks.
|
* @async Reply to a message with permission checks.
|
||||||
* @param {object} replyingTo
|
* @param {object} replyingTo
|
||||||
@@ -395,15 +463,69 @@ export class MessageHandler {
|
|||||||
} else {
|
} else {
|
||||||
opts = { ...message };
|
opts = { ...message };
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
return new Message(await replyingTo.reply(opts, { ping: false }), this);
|
const MAX_ATTEMPTS = 3;
|
||||||
} catch (err) {
|
const RETRY_DELAY_MS = 250;
|
||||||
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
|
||||||
logger.warn(`[MessageHandler] Cannot reply in channel ${replyingTo.channelId ?? replyingTo.channel?.id}: ${err.code ?? err.message}`);
|
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||||
return null;
|
try {
|
||||||
|
return new Message(await replyingTo.reply(opts, { ping: false }), this);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === ErrorCodes.MessageNotFound || err.code === "UNKNOWN_MESSAGE" || err.statusCode === 404 || String(err?.message ?? "").includes("Message wasn't found")) {
|
||||||
|
/* Referenced message was deleted before reply arrived — fall back to channel send */
|
||||||
|
try {
|
||||||
|
const ch = replyingTo.channel ?? (typeof this.getChannel === "function" ? this.getChannel(replyingTo.channelId) : null);
|
||||||
|
if (ch && typeof ch.send === "function") {
|
||||||
|
return new Message(await ch.send(opts), this);
|
||||||
|
}
|
||||||
|
} catch (fallbackErr) {
|
||||||
|
logger.warn(`[MessageHandler] Fallback channel send failed in ${replyingTo.channelId ?? replyingTo.channel?.id}: ${fallbackErr.code ?? fallbackErr.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[MessageHandler] Cannot reply in channel ${replyingTo.channelId ?? replyingTo.channel?.id}: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isRateLimitError(err)) {
|
||||||
|
if (attempt < MAX_ATTEMPTS) {
|
||||||
|
const delay = this.getRateLimitDelayMs(err, attempt);
|
||||||
|
logger.warn(`[MessageHandler] reply: rate limited (429) in ${replyingTo.channelId ?? replyingTo.channel?.id}, retrying in ${delay}ms (attempt ${attempt}/${MAX_ATTEMPTS})`);
|
||||||
|
await new Promise((r) => setTimeout(r, delay));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
logger.warn(`[MessageHandler] reply: rate limited after ${MAX_ATTEMPTS} attempts in ${replyingTo.channelId ?? replyingTo.channel?.id}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isTransientNetworkError(err) && attempt < MAX_ATTEMPTS) {
|
||||||
|
logger.warn(`[MessageHandler] reply: transient network error (${err.code ?? err.message}) on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS * attempt}ms…`);
|
||||||
|
await new Promise((r) => setTimeout(r, RETRY_DELAY_MS * attempt));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* If socket closed persistently on reply, try fallback channel send before failing */
|
||||||
|
if (this.isTransientNetworkError(err)) {
|
||||||
|
try {
|
||||||
|
const ch = replyingTo.channel ?? (typeof this.getChannel === "function" ? this.getChannel(replyingTo.channelId) : null);
|
||||||
|
if (ch && typeof ch.send === "function") {
|
||||||
|
logger.warn(`[MessageHandler] reply: socket closed on reply, attempting fallback channel send in ${replyingTo.channelId ?? replyingTo.channel?.id}`);
|
||||||
|
return new Message(await ch.send(opts), this);
|
||||||
|
}
|
||||||
|
} catch (fallbackErr) {
|
||||||
|
logger.warn(`[MessageHandler] Fallback channel send failed: ${fallbackErr.code ?? fallbackErr.message}`);
|
||||||
|
}
|
||||||
|
logger.warn(`[MessageHandler] reply: network socket unavailable after ${MAX_ATTEMPTS} attempts: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw err;
|
||||||
}
|
}
|
||||||
throw err;
|
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -416,38 +538,84 @@ export class MessageHandler {
|
|||||||
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;
|
||||||
|
|
||||||
|
let payload;
|
||||||
if (typeof message === "object" && Array.isArray(message.embeds)) {
|
if (typeof message === "object" && Array.isArray(message.embeds)) {
|
||||||
|
payload = message;
|
||||||
|
} else {
|
||||||
|
options = {
|
||||||
|
mention: false,
|
||||||
|
embed: {},
|
||||||
|
...options
|
||||||
|
};
|
||||||
|
const content = (typeof message === "object") ? message.embedText : message;
|
||||||
|
payload = this.#createEmbed(content, options.embed);
|
||||||
|
if (typeof message === "object") {
|
||||||
|
const { embedText, ...rest } = message;
|
||||||
|
payload = { ...payload, ...rest };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_ATTEMPTS = 3;
|
||||||
|
const RETRY_DELAY_MS = 250;
|
||||||
|
|
||||||
|
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||||
try {
|
try {
|
||||||
return new Message(await replyingTo.reply(message, { ping: false }), this);
|
return new Message(await replyingTo.reply(payload, { ping: false }), this);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
if (err.code === ErrorCodes.MessageNotFound || err.code === "UNKNOWN_MESSAGE" || err.statusCode === 404 || String(err?.message ?? "").includes("Message wasn't found")) {
|
||||||
|
/* Referenced message was deleted before reply arrived — fall back to channel send */
|
||||||
|
try {
|
||||||
|
const ch = replyingTo.channel ?? (typeof this.getChannel === "function" ? this.getChannel(replyingTo.channelId) : null);
|
||||||
|
if (ch && typeof ch.send === "function") {
|
||||||
|
return new Message(await ch.send(payload), this);
|
||||||
|
}
|
||||||
|
} catch (fallbackErr) {
|
||||||
|
logger.warn(`[MessageHandler] Fallback channel send failed in ${replyingTo.channelId ?? replyingTo.channel?.id}: ${fallbackErr.code ?? fallbackErr.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
logger.warn(`[MessageHandler] Cannot replyEmbed in channel ${replyingTo.channelId ?? replyingTo.channel?.id}: ${err.code ?? err.message}`);
|
logger.warn(`[MessageHandler] Cannot replyEmbed in channel ${replyingTo.channelId ?? replyingTo.channel?.id}: ${err.code ?? err.message}`);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this.isRateLimitError(err)) {
|
||||||
|
if (attempt < MAX_ATTEMPTS) {
|
||||||
|
const delay = this.getRateLimitDelayMs(err, attempt);
|
||||||
|
logger.warn(`[MessageHandler] replyEmbed: rate limited (429) in ${replyingTo.channelId ?? replyingTo.channel?.id}, retrying in ${delay}ms (attempt ${attempt}/${MAX_ATTEMPTS})`);
|
||||||
|
await new Promise((r) => setTimeout(r, delay));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
logger.warn(`[MessageHandler] replyEmbed: rate limited after ${MAX_ATTEMPTS} attempts in ${replyingTo.channelId ?? replyingTo.channel?.id}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isTransientNetworkError(err) && attempt < MAX_ATTEMPTS) {
|
||||||
|
logger.warn(`[MessageHandler] replyEmbed: transient network error (${err.code ?? err.message}) on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS * attempt}ms…`);
|
||||||
|
await new Promise((r) => setTimeout(r, RETRY_DELAY_MS * attempt));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isTransientNetworkError(err)) {
|
||||||
|
try {
|
||||||
|
const ch = replyingTo.channel ?? (typeof this.getChannel === "function" ? this.getChannel(replyingTo.channelId) : null);
|
||||||
|
if (ch && typeof ch.send === "function") {
|
||||||
|
logger.warn(`[MessageHandler] replyEmbed: socket closed on reply, attempting fallback channel send in ${replyingTo.channelId ?? replyingTo.channel?.id}`);
|
||||||
|
return new Message(await ch.send(payload), this);
|
||||||
|
}
|
||||||
|
} catch (fallbackErr) {
|
||||||
|
logger.warn(`[MessageHandler] Fallback channel send failed: ${fallbackErr.code ?? fallbackErr.message}`);
|
||||||
|
}
|
||||||
|
logger.warn(`[MessageHandler] replyEmbed: network socket unavailable after ${MAX_ATTEMPTS} attempts: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
options = {
|
|
||||||
mention: false,
|
|
||||||
embed: {},
|
|
||||||
...options
|
|
||||||
};
|
|
||||||
const content = (typeof message === "object") ? message.embedText : message;
|
|
||||||
let payload = this.#createEmbed(content, options.embed);
|
|
||||||
if (typeof message === "object") {
|
|
||||||
const { embedText, ...rest } = message;
|
|
||||||
payload = { ...payload, ...rest };
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return new Message(await replyingTo.reply(payload, { ping: false }), this);
|
|
||||||
} catch (err) {
|
|
||||||
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
|
||||||
logger.warn(`[MessageHandler] Cannot replyEmbed in channel ${replyingTo.channelId ?? replyingTo.channel?.id}: ${err.code ?? err.message}`);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -467,15 +635,41 @@ export class MessageHandler {
|
|||||||
} else {
|
} else {
|
||||||
opts = message;
|
opts = message;
|
||||||
}
|
}
|
||||||
try {
|
|
||||||
return new Message(await channel.send(opts), this);
|
const MAX_ATTEMPTS = 3;
|
||||||
} catch (err) {
|
const RETRY_DELAY_MS = 250;
|
||||||
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
|
||||||
logger.warn(`[MessageHandler] Cannot sendMessage in channel ${channel.id}: ${err.code ?? err.message}`);
|
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||||
return null;
|
try {
|
||||||
|
return new Message(await channel.send(opts), this);
|
||||||
|
} catch (err) {
|
||||||
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
|
logger.warn(`[MessageHandler] Cannot sendMessage in channel ${channel.id}: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (this.isRateLimitError(err)) {
|
||||||
|
if (attempt < MAX_ATTEMPTS) {
|
||||||
|
const delay = this.getRateLimitDelayMs(err, attempt);
|
||||||
|
logger.warn(`[MessageHandler] sendMessage: rate limited (429) in channel ${channel.id}, retrying in ${delay}ms (attempt ${attempt}/${MAX_ATTEMPTS})`);
|
||||||
|
await new Promise((r) => setTimeout(r, delay));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
logger.warn(`[MessageHandler] sendMessage: rate limited after ${MAX_ATTEMPTS} attempts in channel ${channel.id}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (this.isTransientNetworkError(err) && attempt < MAX_ATTEMPTS) {
|
||||||
|
logger.warn(`[MessageHandler] sendMessage: transient network error (${err.code ?? err.message}) on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS * attempt}ms…`);
|
||||||
|
await new Promise((r) => setTimeout(r, RETRY_DELAY_MS * attempt));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (this.isTransientNetworkError(err)) {
|
||||||
|
logger.warn(`[MessageHandler] sendMessage: network socket unavailable in channel ${channel.id} after ${MAX_ATTEMPTS} attempts: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
}
|
}
|
||||||
throw err;
|
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -489,32 +683,52 @@ export class MessageHandler {
|
|||||||
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 ?? "");
|
||||||
}
|
}
|
||||||
|
let payload;
|
||||||
if (typeof content === "object" && Array.isArray(content.embeds)) {
|
if (typeof content === "object" && Array.isArray(content.embeds)) {
|
||||||
|
payload = content;
|
||||||
|
} else {
|
||||||
|
const text = (typeof content === "object") ? content.embedText : content;
|
||||||
|
payload = this.#createEmbed(text, embedOptions);
|
||||||
|
if (typeof content === "object") {
|
||||||
|
const { embedText, ...rest } = content;
|
||||||
|
Object.assign(payload, rest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_ATTEMPTS = 3;
|
||||||
|
const RETRY_DELAY_MS = 250;
|
||||||
|
|
||||||
|
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||||
try {
|
try {
|
||||||
return new Message(await channel.send(content), this);
|
return new Message(await channel.send(payload), this);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
||||||
logger.warn(`[MessageHandler] Cannot sendEmbed in channel ${channel.id}: ${err.code ?? err.message}`);
|
logger.warn(`[MessageHandler] Cannot sendEmbed in channel ${channel.id}: ${err.code ?? err.message}`);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
if (this.isRateLimitError(err)) {
|
||||||
|
if (attempt < MAX_ATTEMPTS) {
|
||||||
|
const delay = this.getRateLimitDelayMs(err, attempt);
|
||||||
|
logger.warn(`[MessageHandler] sendEmbed: rate limited (429) in channel ${channel.id}, retrying in ${delay}ms (attempt ${attempt}/${MAX_ATTEMPTS})`);
|
||||||
|
await new Promise((r) => setTimeout(r, delay));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
logger.warn(`[MessageHandler] sendEmbed: rate limited after ${MAX_ATTEMPTS} attempts in channel ${channel.id}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (this.isTransientNetworkError(err) && attempt < MAX_ATTEMPTS) {
|
||||||
|
logger.warn(`[MessageHandler] sendEmbed: transient network error (${err.code ?? err.message}) on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS * attempt}ms…`);
|
||||||
|
await new Promise((r) => setTimeout(r, RETRY_DELAY_MS * attempt));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (this.isTransientNetworkError(err)) {
|
||||||
|
logger.warn(`[MessageHandler] sendEmbed: network socket unavailable in channel ${channel.id} after ${MAX_ATTEMPTS} attempts: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const text = (typeof content === "object") ? content.embedText : content;
|
return null;
|
||||||
const payload = this.#createEmbed(text, embedOptions);
|
|
||||||
if (typeof content === "object") {
|
|
||||||
const { embedText, ...rest } = content;
|
|
||||||
Object.assign(payload, rest);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return new Message(await channel.send(payload), this);
|
|
||||||
} catch (err) {
|
|
||||||
if (err.code === "MISSING_PERMISSIONS" || err.code === "COMMUNICATION_DISABLED" || err.statusCode === 403) {
|
|
||||||
logger.warn(`[MessageHandler] Cannot sendEmbed in channel ${channel.id}: ${err.code ?? err.message}`);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
throw err;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -556,12 +770,17 @@ export class MessageHandler {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (RETRYABLE.has(err.statusCode) && attempt < MAX_ATTEMPTS) {
|
if ((RETRYABLE.has(err.statusCode) || this.isTransientNetworkError(err)) && attempt < MAX_ATTEMPTS) {
|
||||||
logger.warn(`[MessageHandler] editEmbed: ${err.statusCode} on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS}ms…`);
|
logger.warn(`[MessageHandler] editEmbed: ${err.statusCode ?? err.code ?? err.message} on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS}ms…`);
|
||||||
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
|
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (this.isTransientNetworkError(err)) {
|
||||||
|
logger.warn(`[MessageHandler] editEmbed: network socket unavailable after ${MAX_ATTEMPTS} attempts: ${err.code ?? err.message}`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -128,8 +128,14 @@ export class Message {
|
|||||||
get authorId() { return this.message.author?.id; }
|
get authorId() { return this.message.author?.id; }
|
||||||
/** @returns {object|null} The guild member, if available. */
|
/** @returns {object|null} The guild member, if available. */
|
||||||
get member() { return this.message.member ?? null; }
|
get member() { return this.message.member ?? null; }
|
||||||
|
/** @returns {Array|object} Raw attachments attached to this message. */
|
||||||
|
get attachments() { return this.message.attachments ?? []; }
|
||||||
/** @returns {Channel} The wrapped channel this message was sent in. */
|
/** @returns {Channel} The wrapped channel this message was sent in. */
|
||||||
get channel() { return this.handler.getChannel(this.message.channelId); }
|
get channel() { return this.handler.getChannel(this.message.channelId); }
|
||||||
|
/** @returns {string|null} The guild ID. */
|
||||||
|
get guildId() { return this.message?.guildId ?? this.message?.guild?.id ?? this.channel?.channel?.guildId ?? this.channel?.guildId ?? null; }
|
||||||
|
/** @returns {object|null} The guild instance, if available. */
|
||||||
|
get guild() { return this.message?.guild ?? this.channel?.channel?.guild ?? this.channel?.guild ?? null; }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Observe reactions on this message.
|
* Observe reactions on this message.
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
/**
|
||||||
|
* @module src/utils/AttachmentUtils
|
||||||
|
* @description Utilities for detecting, inspecting, and extracting media from
|
||||||
|
* Fluxer attachments, uploaded message files, and direct fluxerusercontent.com URLs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Common media file extensions supported for direct streaming or decoding.
|
||||||
|
* Includes native zero-re-encode formats (WebM, Opus, OGG) and container formats (MP4, MP3, AAC, FLAC, WAV).
|
||||||
|
*/
|
||||||
|
export const MEDIA_EXTENSIONS = /\.(?:mp4|webm|mkv|mov|opus|ogg|mp3|m4a|aac|flac|wav|wma)(?:\?|$)/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Formats handled natively by FluxerAudioBridge without re-encoding (WebM/Opus, OGG/Opus).
|
||||||
|
*/
|
||||||
|
export const NATIVE_MEDIA_EXTENSIONS = /\.(?:opus|webm|ogg)(?:\?|$)/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a URL originates from the official Fluxer user-content CDN.
|
||||||
|
* @param {string} str
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isFluxerAttachmentUrl(str) {
|
||||||
|
if (!str || typeof str !== "string") return false;
|
||||||
|
return /fluxerusercontent\.com\/attachments\//i.test(str) ||
|
||||||
|
/cdn\.fluxer\.app\/attachments\//i.test(str);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if a string is a direct playable media link (Fluxer attachment or audio/video extension).
|
||||||
|
* Excludes standard service hosts (YouTube, Spotify, etc.) which use search/catalog resolvers.
|
||||||
|
* @param {string} str
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isPlayableMediaUrl(str) {
|
||||||
|
if (!str || typeof str !== "string") return false;
|
||||||
|
const trimmed = str.trim();
|
||||||
|
if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) return false;
|
||||||
|
if (isFluxerAttachmentUrl(trimmed)) return true;
|
||||||
|
return MEDIA_EXTENSIONS.test(trimmed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract all attachments from a message or message wrapper.
|
||||||
|
* Safely handles arrays, Collections, Maps, and object dictionaries.
|
||||||
|
* @param {object} msg
|
||||||
|
* @returns {Array<object>}
|
||||||
|
*/
|
||||||
|
export function getMessageAttachments(msg) {
|
||||||
|
const raw = msg?.attachments ?? msg?.message?.attachments;
|
||||||
|
if (!raw) return [];
|
||||||
|
if (Array.isArray(raw)) return raw;
|
||||||
|
if (typeof raw.values === "function") return [...raw.values()];
|
||||||
|
if (typeof raw === "object") return Object.values(raw);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the first playable media attachment in a message.
|
||||||
|
* @param {object} msg
|
||||||
|
* @returns {{ url: string, filename: string, size: number, contentType: string }|null}
|
||||||
|
*/
|
||||||
|
export function getPlayableAttachment(msg) {
|
||||||
|
const list = getMessageAttachments(msg);
|
||||||
|
for (const att of list) {
|
||||||
|
if (!att || typeof att !== "object") continue;
|
||||||
|
const url = att.url || att.proxy_url || att.proxyUrl;
|
||||||
|
const filename = att.filename || att.name || "";
|
||||||
|
const contentType = att.content_type || att.contentType || "";
|
||||||
|
const isMedia = MEDIA_EXTENSIONS.test(filename) ||
|
||||||
|
MEDIA_EXTENSIONS.test(url) ||
|
||||||
|
contentType.startsWith("audio/") ||
|
||||||
|
contentType.startsWith("video/") ||
|
||||||
|
contentType === "application/ogg" ||
|
||||||
|
isFluxerAttachmentUrl(url);
|
||||||
|
|
||||||
|
if (url && isMedia) {
|
||||||
|
return {
|
||||||
|
url,
|
||||||
|
filename: filename || "Attachment",
|
||||||
|
size: Number(att.size ?? 0),
|
||||||
|
contentType,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract a clean, human-readable display title from a media URL or filename.
|
||||||
|
* Removes URL query parameters, directory paths, and file extensions.
|
||||||
|
* @param {string} urlOrFilename
|
||||||
|
* @param {string} [fallback="Attachment"]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function extractMediaTitle(urlOrFilename, fallback = "Attachment") {
|
||||||
|
if (!urlOrFilename || typeof urlOrFilename !== "string") return fallback;
|
||||||
|
try {
|
||||||
|
let clean = urlOrFilename;
|
||||||
|
if (clean.startsWith("http://") || clean.startsWith("https://")) {
|
||||||
|
clean = new URL(clean).pathname;
|
||||||
|
}
|
||||||
|
const filename = clean.split("/").pop();
|
||||||
|
if (filename && filename.includes(".")) {
|
||||||
|
const decoded = decodeURIComponent(filename.replace(/\.[^.]+$/, "").trim());
|
||||||
|
if (decoded) return decoded;
|
||||||
|
}
|
||||||
|
} catch (_) { }
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
@@ -25,14 +25,18 @@ export function isPlayerConnectionDead(player) {
|
|||||||
const conn = player._voiceConn ?? player.connection ?? null;
|
const conn = player._voiceConn ?? player.connection ?? null;
|
||||||
if (!conn) return true;
|
if (!conn) return true;
|
||||||
|
|
||||||
const room = conn.room ?? null;
|
if (typeof conn.isConnected === "function") {
|
||||||
if (!room) {
|
try {
|
||||||
try { return conn.isConnected?.() === false; } catch (_) { return false; }
|
if (!conn.isConnected()) return true;
|
||||||
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
if (room.isConnected === false) return true;
|
|
||||||
|
|
||||||
const cs = room.connectionState;
|
const room = conn.room ?? null;
|
||||||
if (cs === 0 || cs === "CONN_DISCONNECTED") return true;
|
if (room) {
|
||||||
|
if (room.isConnected === false || room.isClosed === true) return true;
|
||||||
|
const cs = (room.state ?? room.connectionState ?? "").toString().toLowerCase();
|
||||||
|
if (cs === "disconnected" || cs === "0" || cs === "conn_disconnected") return true;
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -54,10 +58,12 @@ export function get247ChannelMode(set, channelId) {
|
|||||||
if (!set?.get) return "off";
|
if (!set?.get) return "off";
|
||||||
const raw = set.get("stay_247");
|
const raw = set.get("stay_247");
|
||||||
if (!raw || raw === "none") return "off";
|
if (!raw || raw === "none") return "off";
|
||||||
|
const target = cleanId(channelId);
|
||||||
|
if (!target) return "off";
|
||||||
const channels = Array.isArray(raw)
|
const channels = Array.isArray(raw)
|
||||||
? raw.map(id => String(id).trim()).filter(Boolean)
|
? raw.map(id => cleanId(id)).filter(Boolean)
|
||||||
: [String(raw).trim()];
|
: [cleanId(raw)].filter(Boolean);
|
||||||
return channels.includes(channelId) ? "on" : "off";
|
return channels.includes(target) ? "on" : "off";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+1
-1
@@ -372,7 +372,7 @@ export class Utils {
|
|||||||
if (includeDuration && track.duration) {
|
if (includeDuration && track.duration) {
|
||||||
const duration = typeof track.duration === "number"
|
const duration = typeof track.duration === "number"
|
||||||
? this.prettifyMS(track.duration)
|
? this.prettifyMS(track.duration)
|
||||||
: track.duration.timestamp || track.duration.seconds
|
: (track.duration?.timestamp || track.duration?.seconds)
|
||||||
? this.formatSeconds(track.duration.seconds)
|
? this.formatSeconds(track.duration.seconds)
|
||||||
: "?:??";
|
: "?:??";
|
||||||
return `${title} - ${author} [${duration}]`;
|
return `${title} - ${author} [${duration}]`;
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ import Watchdog247 from "./Watchdog247.mjs";
|
|||||||
import RejoinBackoff from "./RejoinBackoff.mjs";
|
import RejoinBackoff from "./RejoinBackoff.mjs";
|
||||||
|
|
||||||
const RAW_GATEWAY_INTEREST =
|
const RAW_GATEWAY_INTEREST =
|
||||||
/"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/;
|
/"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED|MESSAGE_CREATE)"|(?:0|7|9|10|11|12)\b)/;
|
||||||
|
|
||||||
/** @class GatewayHandler @description Handles all 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. */
|
/** @class GatewayHandler @description Handles all 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. */
|
||||||
class GatewayHandler {
|
class GatewayHandler {
|
||||||
@@ -132,9 +132,11 @@ class GatewayHandler {
|
|||||||
if (typeof old.removeEventListener === "function") {
|
if (typeof old.removeEventListener === "function") {
|
||||||
old.removeEventListener("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler);
|
old.removeEventListener("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler);
|
||||||
old.removeEventListener("error", remix._rawGatewayErrorHandler);
|
old.removeEventListener("error", remix._rawGatewayErrorHandler);
|
||||||
|
old.removeEventListener("close", remix._rawGatewayCloseHandler);
|
||||||
} else if (typeof old.off === "function") {
|
} else if (typeof old.off === "function") {
|
||||||
old.off("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler);
|
old.off("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler);
|
||||||
old.off("error", remix._rawGatewayErrorHandler);
|
old.off("error", remix._rawGatewayErrorHandler);
|
||||||
|
old.off("close", remix._rawGatewayCloseHandler);
|
||||||
}
|
}
|
||||||
} catch(e) { logger.warn("[Gateway] Failed to detach old WS listener:", e?.message); }
|
} catch(e) { logger.warn("[Gateway] Failed to detach old WS listener:", e?.message); }
|
||||||
attached.delete(old);
|
attached.delete(old);
|
||||||
@@ -149,24 +151,99 @@ class GatewayHandler {
|
|||||||
if (typeof data === "string" && !RAW_GATEWAY_INTEREST.test(data)) return;
|
if (typeof data === "string" && !RAW_GATEWAY_INTEREST.test(data)) return;
|
||||||
const payload = typeof data === "string" ? JSON.parse(data) : data;
|
const payload = typeof data === "string" ? JSON.parse(data) : data;
|
||||||
|
|
||||||
|
/* Opcode 11 (Heartbeat ACK): confirms the gateway received and acknowledged bot heartbeat */
|
||||||
|
if (payload?.op === GatewayOpcodes.HeartbeatAck || payload?.op === 11) {
|
||||||
|
remix._lastGatewayHeartbeat = Date.now();
|
||||||
|
remix._gatewayConnected = true;
|
||||||
|
remix._lastGatewayDisconnect = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (payload?.op === GatewayOpcodes.GatewayError || payload?.op === 12) {
|
if (payload?.op === GatewayOpcodes.GatewayError || payload?.op === 12) {
|
||||||
logger.warn("[Gateway] GatewayError (12) received from Fluxer:", payload.d);
|
logger.warn("[Gateway] GatewayError (12) received from Fluxer:", payload.d);
|
||||||
|
remix._gatewayConnected = false;
|
||||||
|
if (!remix._lastGatewayDisconnect) remix._lastGatewayDisconnect = Date.now();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload?.op === GatewayOpcodes.Hello || payload?.op === 10) {
|
if (payload?.op === GatewayOpcodes.Hello || payload?.op === 10) {
|
||||||
logger.player(`[Gateway] HELLO received (heartbeat ${payload.d?.heartbeat_interval ?? "unknown"}ms)`);
|
logger.player(`[Gateway] HELLO received (heartbeat ${payload.d?.heartbeat_interval ?? "unknown"}ms)`);
|
||||||
|
remix._gatewayConnected = true;
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Opcode 7 (Reconnect): Gateway requests immediate close and resume */
|
||||||
if (payload?.op === GatewayOpcodes.Reconnect || payload?.op === 7) {
|
if (payload?.op === GatewayOpcodes.Reconnect || payload?.op === 7) {
|
||||||
logger.warn("[Gateway] RECONNECT requested by gateway.");
|
logger.player("[Gateway] RECONNECT (op 7) requested by gateway — terminating socket to trigger reconnect.");
|
||||||
|
remix._gatewayConnected = false;
|
||||||
|
if (!remix._lastGatewayDisconnect) remix._lastGatewayDisconnect = Date.now();
|
||||||
|
this._lastReadyAt = 0;
|
||||||
|
const wsObjs = ShardingUtils.localShardSockets(client);
|
||||||
|
for (const ws of wsObjs) {
|
||||||
|
try {
|
||||||
|
if (typeof ws?.close === "function") ws.close(4000, "Gateway requested reconnect");
|
||||||
|
else if (typeof ws?.terminate === "function") ws.terminate();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
setTimeout(() => {
|
||||||
|
for (const [id, shard] of ShardingUtils.getLocalShards(client)) {
|
||||||
|
try {
|
||||||
|
if (typeof shard.connect === "function") shard.connect();
|
||||||
|
else if (typeof shard.reconnect === "function") shard.reconnect();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}, 1_000).unref?.();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Opcode 9 (InvalidSession): Session invalidated by gateway */
|
||||||
if (payload?.op === GatewayOpcodes.InvalidSession || payload?.op === 9) {
|
if (payload?.op === GatewayOpcodes.InvalidSession || payload?.op === 9) {
|
||||||
logger.warn("[Gateway] INVALID_SESSION received from gateway.");
|
const canResume = Boolean(payload.d);
|
||||||
|
logger.player(`[Gateway] INVALID_SESSION (op 9, resumable=${canResume}) received from gateway.`);
|
||||||
|
remix._gatewayConnected = false;
|
||||||
|
if (!remix._lastGatewayDisconnect) remix._lastGatewayDisconnect = Date.now();
|
||||||
|
this._lastReadyAt = 0;
|
||||||
|
if (!canResume) {
|
||||||
|
for (const [id, shard] of ShardingUtils.getLocalShards(client)) {
|
||||||
|
try {
|
||||||
|
if (shard.sessionId) shard.sessionId = null;
|
||||||
|
if (shard.session_id) shard.session_id = null;
|
||||||
|
if (shard.resumeGatewayUrl) shard.resumeGatewayUrl = null;
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const wsObjs = ShardingUtils.localShardSockets(client);
|
||||||
|
for (const ws of wsObjs) {
|
||||||
|
try {
|
||||||
|
if (typeof ws?.close === "function") ws.close(canResume ? 4000 : 1000, "Invalid session");
|
||||||
|
else if (typeof ws?.terminate === "function") ws.terminate();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
setTimeout(() => {
|
||||||
|
for (const [id, shard] of ShardingUtils.getLocalShards(client)) {
|
||||||
|
try {
|
||||||
|
if (typeof shard.connect === "function") shard.connect();
|
||||||
|
else if (typeof shard.reconnect === "function") shard.reconnect();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}, 1_500).unref?.();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload?.op !== 0) return;
|
if (payload?.op !== 0) return;
|
||||||
|
|
||||||
|
/* Genuine Dispatch event (op 0) — gateway is actively delivering traffic */
|
||||||
|
remix._lastGatewayHeartbeat = Date.now();
|
||||||
|
remix._gatewayConnected = true;
|
||||||
|
remix._lastGatewayDisconnect = 0;
|
||||||
|
|
||||||
if (payload.t === "READY") {
|
if (payload.t === "READY") {
|
||||||
|
remix.statusChannel?.resolveIncident("gateway");
|
||||||
logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`);
|
logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`);
|
||||||
|
this._lastReadyAt = Date.now();
|
||||||
|
remix._lastGatewayHeartbeat = Date.now();
|
||||||
|
remix._gatewayConnected = true;
|
||||||
|
this.rejoinBackoff?.clear?.();
|
||||||
const readyGuilds = payload.d?.guilds;
|
const readyGuilds = payload.d?.guilds;
|
||||||
if (Array.isArray(readyGuilds)) {
|
if (Array.isArray(readyGuilds)) {
|
||||||
for (const g of readyGuilds) {
|
for (const g of readyGuilds) {
|
||||||
@@ -181,10 +258,43 @@ class GatewayHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (remix._hasBooted) {
|
||||||
|
logger.voice247("[Gateway] Re-READY after gateway reconnection — scheduling 24/7 self-healing sweep in 3s...");
|
||||||
|
setTimeout(() => {
|
||||||
|
if (typeof this._sweep247Channels === "function") {
|
||||||
|
this._sweep247Channels().catch(err => {
|
||||||
|
logger.warn("[Watchdog247] Post-reconnect sweep failed:", err?.message ?? err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (remix.players?.resumeAllOnNodeReconnect) {
|
||||||
|
remix.players.resumeAllOnNodeReconnect();
|
||||||
|
}
|
||||||
|
}, 3_000).unref?.();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload.t === "RESUMED") {
|
if (payload.t === "RESUMED") {
|
||||||
|
remix.statusChannel?.resolveIncident("gateway");
|
||||||
logger.player("[Gateway] RESUMED received from gateway.");
|
logger.player("[Gateway] RESUMED received from gateway.");
|
||||||
|
this._lastReadyAt = Date.now();
|
||||||
|
remix._lastGatewayHeartbeat = Date.now();
|
||||||
|
remix._gatewayConnected = true;
|
||||||
|
this.rejoinBackoff?.clear?.();
|
||||||
|
|
||||||
|
if (remix._hasBooted) {
|
||||||
|
logger.voice247("[Gateway] RESUMED session active — scheduling 24/7 self-healing sweep in 3s...");
|
||||||
|
setTimeout(() => {
|
||||||
|
if (typeof this._sweep247Channels === "function") {
|
||||||
|
this._sweep247Channels().catch(err => {
|
||||||
|
logger.warn("[Watchdog247] Post-resume sweep failed:", err?.message ?? err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (remix.players?.resumeAllOnNodeReconnect) {
|
||||||
|
remix.players.resumeAllOnNodeReconnect();
|
||||||
|
}
|
||||||
|
}, 3_000).unref?.();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (payload.t === "GUILD_CREATE") {
|
if (payload.t === "GUILD_CREATE") {
|
||||||
@@ -208,9 +318,9 @@ class GatewayHandler {
|
|||||||
|
|
||||||
if (payload.t === "VOICE_STATE_UPDATE") {
|
if (payload.t === "VOICE_STATE_UPDATE") {
|
||||||
const d = payload.d;
|
const d = payload.d;
|
||||||
const userId = d?.user_id;
|
const userId = cleanId(d?.user_id ?? d?.userId);
|
||||||
const channelId = d?.channel_id ?? null;
|
const channelId = cleanId(d?.channel_id ?? d?.channelId) || null;
|
||||||
const guildId = d?.guild_id;
|
const guildId = cleanId(d?.guild_id ?? d?.guildId);
|
||||||
const isBot = resolveIsBotUser({ userId, member: d?.member, guild: client.guilds?.get?.(guildId), client, botId: client.user?.id });
|
const isBot = resolveIsBotUser({ userId, member: d?.member, guild: client.guilds?.get?.(guildId), client, botId: client.user?.id });
|
||||||
if (!userId) return;
|
if (!userId) return;
|
||||||
if (channelId) {
|
if (channelId) {
|
||||||
@@ -218,6 +328,11 @@ class GatewayHandler {
|
|||||||
} else {
|
} else {
|
||||||
remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot });
|
remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot });
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
this._handleVoiceStateUpdate(d);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Gateway] Error in _handleVoiceStateUpdate from raw event:", e?.message);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch(e) { logger.warn("[Gateway] Raw gateway handler error:", e?.message); }
|
} catch(e) { logger.warn("[Gateway] Raw gateway handler error:", e?.message); }
|
||||||
};
|
};
|
||||||
@@ -228,7 +343,27 @@ class GatewayHandler {
|
|||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
|
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
|
||||||
_wsErrorCooldown.lastLogged = now;
|
_wsErrorCooldown.lastLogged = now;
|
||||||
logger.warn("[Gateway] Raw WS socket error (will reconnect):", err?.message ?? err);
|
logger.player("[Gateway] Raw WS socket error (will reconnect):", err?.message ?? err);
|
||||||
|
};
|
||||||
|
remix._rawGatewayCloseHandler = (eventOrCode, maybeReason) => {
|
||||||
|
const code = eventOrCode?.code ?? (typeof eventOrCode === "number" ? eventOrCode : "unknown");
|
||||||
|
const reason = eventOrCode?.reason ?? maybeReason ?? "";
|
||||||
|
remix._gatewayConnected = false;
|
||||||
|
if (!remix._lastGatewayDisconnect) remix._lastGatewayDisconnect = Date.now();
|
||||||
|
remix.statusChannel?.triggerIncident("gateway", `Gateway WebSocket closed (code=${code}). Reconnecting...`);
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - _wsErrorCooldown.lastLogged >= _wsErrorCooldown.COOLDOWN_MS) {
|
||||||
|
_wsErrorCooldown.lastLogged = now;
|
||||||
|
logger.player(`[Gateway] Raw WebSocket closed (code=${code}, reason=${reason || "none"}) — proactively reconnecting shards.`);
|
||||||
|
}
|
||||||
|
/* Immediately attempt proactive shard reconnect */
|
||||||
|
for (const [id, shard] of ShardingUtils.getLocalShards(remix.client)) {
|
||||||
|
try {
|
||||||
|
if (typeof shard.connect === "function") shard.connect();
|
||||||
|
else if (typeof shard.reconnect === "function") shard.reconnect();
|
||||||
|
else if (typeof shard.ws?.connect === "function") shard.ws.connect();
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
remix._rawGatewayMessageListener = (event) => remix._rawGatewayHandler(event?.data ?? event);
|
remix._rawGatewayMessageListener = (event) => remix._rawGatewayHandler(event?.data ?? event);
|
||||||
}
|
}
|
||||||
@@ -239,9 +374,11 @@ class GatewayHandler {
|
|||||||
if (typeof wsObj.addEventListener === "function") {
|
if (typeof wsObj.addEventListener === "function") {
|
||||||
wsObj.addEventListener("message", remix._rawGatewayMessageListener);
|
wsObj.addEventListener("message", remix._rawGatewayMessageListener);
|
||||||
wsObj.addEventListener("error", remix._rawGatewayErrorHandler);
|
wsObj.addEventListener("error", remix._rawGatewayErrorHandler);
|
||||||
|
wsObj.addEventListener("close", remix._rawGatewayCloseHandler);
|
||||||
} else if (typeof wsObj.on === "function") {
|
} else if (typeof wsObj.on === "function") {
|
||||||
wsObj.on("message", remix._rawGatewayMessageListener);
|
wsObj.on("message", remix._rawGatewayMessageListener);
|
||||||
wsObj.on("error", remix._rawGatewayErrorHandler);
|
wsObj.on("error", remix._rawGatewayErrorHandler);
|
||||||
|
wsObj.on("close", remix._rawGatewayCloseHandler);
|
||||||
}
|
}
|
||||||
|
|
||||||
attached.add(wsObj);
|
attached.add(wsObj);
|
||||||
@@ -409,8 +546,10 @@ class GatewayHandler {
|
|||||||
this._processGuildDelete(guildId);
|
this._processGuildDelete(guildId);
|
||||||
});
|
});
|
||||||
|
|
||||||
client.on(Events.VoiceStateUpdate, async (data) => {
|
client.on(Events.VoiceStateUpdate, async (oldOrNew, maybeNew) => {
|
||||||
this._handleVoiceStateUpdate(data);
|
const data = maybeNew ?? oldOrNew;
|
||||||
|
const extra = maybeNew ? oldOrNew : null;
|
||||||
|
this._handleVoiceStateUpdate(data, extra);
|
||||||
});
|
});
|
||||||
|
|
||||||
client.on(Events.VoiceStatesSync, (data) => {
|
client.on(Events.VoiceStatesSync, (data) => {
|
||||||
@@ -547,6 +686,18 @@ class GatewayHandler {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Ensure backoff cooldowns from previous session/downtime are reset */
|
||||||
|
this.rejoinBackoff?.clear?.();
|
||||||
|
|
||||||
|
/* Wait for gateway to establish connection so voice joins do not immediately time out */
|
||||||
|
if (remix._gatewayConnected === false) {
|
||||||
|
logger.voice247("[BootRecovery] Waiting up to 30s for gateway connection before rejoining 24/7 channels...");
|
||||||
|
const startWait = Date.now();
|
||||||
|
while (remix._gatewayConnected === false && Date.now() - startWait < 30_000) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 500));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const lava = remix.lavalink;
|
const lava = remix.lavalink;
|
||||||
if (lava?.hasConnectedNode && !lava.hasConnectedNode() && lava.waitForNode) {
|
if (lava?.hasConnectedNode && !lava.hasConnectedNode() && lava.waitForNode) {
|
||||||
@@ -569,7 +720,16 @@ class GatewayHandler {
|
|||||||
const cleanG = cleanId(guildId);
|
const cleanG = cleanId(guildId);
|
||||||
const cleanC = cleanId(channelId);
|
const cleanC = cleanId(channelId);
|
||||||
|
|
||||||
const guild = remix.client?.guilds?.get?.(cleanG);
|
let guild = remix.client?.guilds?.get?.(cleanG);
|
||||||
|
if (!guild && typeof remix.client?.guilds?.fetch === "function") {
|
||||||
|
try { guild = await remix.client.guilds.fetch(cleanG).catch(() => null); } catch (_) {}
|
||||||
|
}
|
||||||
|
if (!guild) {
|
||||||
|
const { channel: chCheck } = await this._resolve247Channel(cleanC);
|
||||||
|
if (chCheck) {
|
||||||
|
guild = chCheck.guild ?? { id: cleanG };
|
||||||
|
}
|
||||||
|
}
|
||||||
if (!guild) {
|
if (!guild) {
|
||||||
logger.voice247(
|
logger.voice247(
|
||||||
`[BootRecovery] Bot is not currently in guild ${cleanG} — skipping channel ${cleanC} (setting kept intact).`
|
`[BootRecovery] Bot is not currently in guild ${cleanG} — skipping channel ${cleanC} (setting kept intact).`
|
||||||
@@ -605,13 +765,14 @@ class GatewayHandler {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (!channelObj && !definitive) {
|
if (!channelObj && !definitive) {
|
||||||
logger.warn(
|
logger.voice247(
|
||||||
`[BootRecovery] Channel ${channelId} could not be resolved (cache miss + REST failure) — ` +
|
`[BootRecovery] Channel ${channelId} could not be resolved (cache miss + REST failure) — ` +
|
||||||
`keeping the 24/7 setting; the watchdog will retry later.`
|
`keeping the 24/7 setting; the watchdog will retry later.`
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (channelObj.type !== 2) {
|
const isVoice = channelObj.type === 2 || channelObj.type === 13 || channelObj.type === "voice";
|
||||||
|
if (!isVoice) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
`[BootRecovery] Channel ${channelId} in guild ${guildId} is not a voice channel (type: ${channelObj.type}) — skipping.`
|
`[BootRecovery] Channel ${channelId} in guild ${guildId} is not a voice channel (type: ${channelObj.type}) — skipping.`
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -13,12 +13,12 @@
|
|||||||
export class RejoinBackoff {
|
export class RejoinBackoff {
|
||||||
/**
|
/**
|
||||||
* @param {object} [o]
|
* @param {object} [o]
|
||||||
* @param {number} [o.baseMs=120000] - Cool-down after the first failed attempt cycle (doubles each time).
|
* @param {number} [o.baseMs=30000] - Cool-down after the first failed attempt cycle (doubles each time).
|
||||||
* @param {number} [o.maxMs=3600000] - Upper bound for the cool-down.
|
* @param {number} [o.maxMs=3600000] - Upper bound for the cool-down.
|
||||||
* @param {number} [o.maxEntries=5000] - Safety cap on remembered channels (oldest evicted first).
|
* @param {number} [o.maxEntries=5000] - Safety cap on remembered channels (oldest evicted first).
|
||||||
* @param {() => number} [o.now] - Clock (injectable for tests).
|
* @param {() => number} [o.now] - Clock (injectable for tests).
|
||||||
*/
|
*/
|
||||||
constructor({ baseMs = 120_000, maxMs = 3_600_000, maxEntries = 5_000, now = Date.now } = {}) {
|
constructor({ baseMs = 30_000, maxMs = 3_600_000, maxEntries = 5_000, now = Date.now } = {}) {
|
||||||
this.baseMs = baseMs;
|
this.baseMs = baseMs;
|
||||||
this.maxMs = maxMs;
|
this.maxMs = maxMs;
|
||||||
this.maxEntries = maxEntries;
|
this.maxEntries = maxEntries;
|
||||||
@@ -47,6 +47,11 @@ export class RejoinBackoff {
|
|||||||
this._entries.delete(String(channelId));
|
this._entries.delete(String(channelId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Clear all backoff entries (used on gateway reconnection). */
|
||||||
|
clear() {
|
||||||
|
this._entries.clear();
|
||||||
|
}
|
||||||
|
|
||||||
/** @returns {number} Milliseconds until the watchdog may try this channel again (0 = go ahead). */
|
/** @returns {number} Milliseconds until the watchdog may try this channel again (0 = go ahead). */
|
||||||
remainingMs(channelId) {
|
remainingMs(channelId) {
|
||||||
const e = this._entries.get(String(channelId));
|
const e = this._entries.get(String(channelId));
|
||||||
|
|||||||
@@ -56,11 +56,13 @@ const RejoinManager = {
|
|||||||
|| errMsg.includes("internal error")
|
|| errMsg.includes("internal error")
|
||||||
|| errMsg.includes("ETIMEDOUT")
|
|| errMsg.includes("ETIMEDOUT")
|
||||||
|| errMsg.includes("ECONNRESET")
|
|| errMsg.includes("ECONNRESET")
|
||||||
|
|| errMsg.includes("Gateway")
|
||||||
|
|| this.remix?._gatewayConnected === false
|
||||||
);
|
);
|
||||||
|
|
||||||
if (isTransientError && attempt < maxRetries) {
|
if (isTransientError && attempt < maxRetries) {
|
||||||
const backoffMs = baseDelay * Math.pow(2, attempt - 1);
|
const backoffMs = baseDelay * Math.pow(2, attempt - 1);
|
||||||
logger.warn(
|
logger.voice247(
|
||||||
`[${context}] Voice connection/track failed for channel ${channelId} (attempt ${attempt}/${maxRetries}) — ` +
|
`[${context}] Voice connection/track failed for channel ${channelId} (attempt ${attempt}/${maxRetries}) — ` +
|
||||||
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
||||||
);
|
);
|
||||||
@@ -74,7 +76,7 @@ const RejoinManager = {
|
|||||||
`[${context}] Background rejoin failed for channel ${channelId} (failure #${failCount + 1}): ${errMsg} — keeping 24/7 setting intact.`
|
`[${context}] Background rejoin failed for channel ${channelId} (failure #${failCount + 1}): ${errMsg} — keeping 24/7 setting intact.`
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
logger.warn(
|
logger.voice247(
|
||||||
`[${context}] Failed to rejoin channel ${channelId}: ${errMsg} — keeping 24/7 setting intact.`
|
`[${context}] Failed to rejoin channel ${channelId}: ${errMsg} — keeping 24/7 setting intact.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -97,7 +99,10 @@ const RejoinManager = {
|
|||||||
const cleanGuildId = cleanId(guildId);
|
const cleanGuildId = cleanId(guildId);
|
||||||
const cleanChannelId = cleanId(channelId);
|
const cleanChannelId = cleanId(channelId);
|
||||||
|
|
||||||
const guild = remix.client?.guilds?.get?.(cleanGuildId);
|
let guild = remix.client?.guilds?.get?.(cleanGuildId);
|
||||||
|
if (!guild && typeof remix.client?.guilds?.fetch === "function") {
|
||||||
|
try { guild = await remix.client.guilds.fetch(cleanGuildId).catch(() => null); } catch (_) {}
|
||||||
|
}
|
||||||
if (!guild) {
|
if (!guild) {
|
||||||
logger.voice247(`[Rejoin] Bot is not currently in guild ${cleanGuildId} — skipping ${cleanChannelId} (setting kept intact).`);
|
logger.voice247(`[Rejoin] Bot is not currently in guild ${cleanGuildId} — skipping ${cleanChannelId} (setting kept intact).`);
|
||||||
return;
|
return;
|
||||||
@@ -168,7 +173,10 @@ const RejoinManager = {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this._rejoinAttempts.delete(cleanChannelId);
|
this._rejoinAttempts.delete(cleanChannelId);
|
||||||
this.rejoinBackoff?.recordFailure?.(cleanChannelId);
|
/* Only apply backoff cool-down if failure was not caused by a gateway outage */
|
||||||
|
if (this.remix?._gatewayConnected !== false) {
|
||||||
|
this.rejoinBackoff?.recordFailure?.(cleanChannelId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return player;
|
return player;
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -28,38 +28,47 @@ const VoiceStateRouting = {
|
|||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
async _handleVoiceStateUpdate(data) {
|
async _handleVoiceStateUpdate(data, extraState = null) {
|
||||||
const { remix } = this;
|
const { remix } = this;
|
||||||
const client = remix.client;
|
const client = remix.client;
|
||||||
|
|
||||||
const userId = data?.user_id;
|
/* Normalize field names across raw gateway payloads and library VoiceState objects */
|
||||||
|
const rawState = data;
|
||||||
|
const userId = cleanId(rawState?.user_id ?? rawState?.userId ?? rawState?.id ?? rawState?.member?.user?.id ?? rawState?.member?.id);
|
||||||
if (!userId) return;
|
if (!userId) return;
|
||||||
|
|
||||||
const newChannelId = data?.channel_id ?? null;
|
const newChannelId = cleanId(rawState?.channel_id ?? rawState?.channelId ?? rawState?.channel?.id) || null;
|
||||||
const vsuGuildId = data?.guild_id;
|
const vsuGuildId = cleanId(rawState?.guild_id ?? rawState?.guildId ?? rawState?.guild?.id);
|
||||||
const isBot = resolveIsBotUser({
|
|
||||||
|
const botId = cleanId(client.user?.id ?? remix.botId ?? remix.config?.botId ?? client.id ?? "");
|
||||||
|
const isBotUser = Boolean(botId && userId === botId);
|
||||||
|
const isBot = isBotUser || resolveIsBotUser({
|
||||||
userId,
|
userId,
|
||||||
member: data?.member,
|
member: rawState?.member,
|
||||||
guild: client.guilds?.get?.(vsuGuildId),
|
guild: client.guilds?.get?.(vsuGuildId),
|
||||||
client,
|
client,
|
||||||
botId: client.user?.id,
|
botId,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
const prevEntry = this.findPrevVoiceStateEntry(userId, vsuGuildId);
|
const prevEntry = this.findPrevVoiceStateEntry(userId, vsuGuildId);
|
||||||
const prev = prevEntry.value;
|
const prev = prevEntry.value;
|
||||||
const prevSameGuild = prev &&
|
const prevSameGuild = prev &&
|
||||||
cleanId(prev.guildId ?? "") === cleanId(vsuGuildId ?? "");
|
cleanId(prev.guildId ?? "") === cleanId(vsuGuildId ?? "");
|
||||||
const oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null;
|
let oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null;
|
||||||
|
|
||||||
|
|
||||||
this._updatePreviousStates(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prevEntry, prev);
|
|
||||||
this._updateVoiceStateCache(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prev);
|
|
||||||
|
|
||||||
|
if (!oldChannelId && extraState) {
|
||||||
|
oldChannelId = cleanId(extraState?.channel_id ?? extraState?.channelId ?? extraState?.channel?.id) || null;
|
||||||
|
}
|
||||||
|
|
||||||
const { player, playerGuildId, homeChannelId } = this._findAffectedPlayer(vsuGuildId, oldChannelId, newChannelId);
|
const { player, playerGuildId, homeChannelId } = this._findAffectedPlayer(vsuGuildId, oldChannelId, newChannelId);
|
||||||
|
|
||||||
const isBotUser = isBot === true && userId === client.user?.id;
|
/* If this is the bot disconnecting, but oldChannelId was not tracked in _prevVoiceState, resolve it from the player */
|
||||||
|
if (!oldChannelId && isBotUser && player) {
|
||||||
|
oldChannelId = cleanId(player._channelId ?? player._home247Channel ?? "") || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
this._updatePreviousStates(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prevEntry, prev);
|
||||||
|
this._updateVoiceStateCache(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prev);
|
||||||
|
|
||||||
/* Handle server-mute (admin / community mute) on the bot */
|
/* Handle server-mute (admin / community mute) on the bot */
|
||||||
if (isBotUser && player) {
|
if (isBotUser && player) {
|
||||||
@@ -217,6 +226,14 @@ const VoiceStateRouting = {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (guildId) {
|
||||||
|
const cleanG = cleanId(guildId);
|
||||||
|
const player = [...remix.players.playerMap.values()].find(p => !p._destroyed && cleanId(p._guildId) === cleanG);
|
||||||
|
if (player) {
|
||||||
|
return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return { player: null, playerGuildId: null, homeChannelId: null };
|
return { player: null, playerGuildId: null, homeChannelId: null };
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -150,6 +150,10 @@ const Watchdog247 = {
|
|||||||
logger.voice247("[Watchdog247] Boot recovery in progress — skipping sweep.");
|
logger.voice247("[Watchdog247] Boot recovery in progress — skipping sweep.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (remix._gatewayConnected === false) {
|
||||||
|
logger.voice247("[Watchdog247] Gateway is currently disconnected — deferring sweep until connection is restored.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
let healthy = 0, healed = 0, pruned = 0, skipped = 0;
|
let healthy = 0, healed = 0, pruned = 0, skipped = 0;
|
||||||
const savedChannels = [];
|
const savedChannels = [];
|
||||||
@@ -170,9 +174,19 @@ const Watchdog247 = {
|
|||||||
const cleanG = cleanId(guildId);
|
const cleanG = cleanId(guildId);
|
||||||
const cleanCh = cleanId(channelId);
|
const cleanCh = cleanId(channelId);
|
||||||
|
|
||||||
const guild = remix.client?.guilds?.get?.(cleanG);
|
let guild = remix.client?.guilds?.get?.(cleanG);
|
||||||
|
if (!guild && typeof remix.client?.guilds?.fetch === "function") {
|
||||||
|
try { guild = await remix.client.guilds.fetch(cleanG).catch(() => null); } catch (_) {}
|
||||||
|
}
|
||||||
if (!guild) {
|
if (!guild) {
|
||||||
// Bot is not in this guild — keep 24/7 setting intact for future invite, but skip sweep
|
/* If channel itself resolves via REST, the guild is accessible to the bot */
|
||||||
|
const { channel: chCheck } = await this._resolve247Channel(cleanCh);
|
||||||
|
if (chCheck) {
|
||||||
|
guild = chCheck.guild ?? { id: cleanG };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!guild) {
|
||||||
|
/* Bot is not in this guild — keep 24/7 setting intact for future invite, but skip sweep */
|
||||||
skipped++;
|
skipped++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -219,11 +233,12 @@ const Watchdog247 = {
|
|||||||
skipped++;
|
skipped++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (channel && channel.type !== 2) {
|
const isVoice = channel.type === 2 || channel.type === 13 || channel.type === "voice";
|
||||||
|
if (channel && !isVoice) {
|
||||||
if (this._prune247Channel(guildId, channelId)) {
|
if (this._prune247Channel(guildId, channelId)) {
|
||||||
pruned++;
|
pruned++;
|
||||||
remix.cancel247Rejoin?.(channelId);
|
remix.cancel247Rejoin?.(channelId);
|
||||||
logger.voice247(`[Watchdog247] ${channelId} is not a voice channel anymore — pruned.`);
|
logger.voice247(`[Watchdog247] ${channelId} is not a voice channel anymore (type: ${channel.type}) — pruned.`);
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
+195
-12
@@ -35,7 +35,20 @@
|
|||||||
"permission": "الصلاحية `{{$permission}}`",
|
"permission": "الصلاحية `{{$permission}}`",
|
||||||
"optionCount": "{{$count}} خيار/خيارات",
|
"optionCount": "{{$count}} خيار/خيارات",
|
||||||
"commandInspectorAuthor": "مساعدة الأمر • {{prefix}}{{name}}",
|
"commandInspectorAuthor": "مساعدة الأمر • {{prefix}}{{name}}",
|
||||||
"commandInspectorFooter": "اكتب {{prefix}}help لعرض القائمة الكاملة • الفئة: {{category}}"
|
"commandInspectorFooter": "اكتب {{prefix}}help لعرض القائمة الكاملة • الفئة: {{category}}",
|
||||||
|
"tabHome": "الرئيسية",
|
||||||
|
"tabHomeHeader": "الصفحة الرئيسية",
|
||||||
|
"tabMusic": "الموسيقى",
|
||||||
|
"tabMusicHeader": "أوامر الموسيقى",
|
||||||
|
"tabUtil": "الأدوات",
|
||||||
|
"tabUtilHeader": "أوامر الأدوات",
|
||||||
|
"tabSupport": "الدعم",
|
||||||
|
"tabSupportHeader": "معلومات الدعم",
|
||||||
|
"homeContent": "**Remix** هو بوت موسيقى عالي الدقة يعمل على مدار الساعة 24/7 ويدعم YouTube وSpotify وSoundCloud وDeezer والمزيد.\n\n**✨ أبرز المميزات**\n• **صوت Hi-Fi بدقة 48kHz** — مسار بث صوتي نقي للغاية\n• **أكثر من 30 فلتر صوتي** — Bassboost و8D وNightcore وVaporwave ومعادل الصوت\n• **تسوية ديناميكية للصوت** — موازنة مستوى الصوت EBU R128 عبر مختلف المصادر\n• **راديو إنترنت 24/7** — أكثر من 30,000 محطة إذاعية مباشرة حول العالم\n\n**📂 فئات الأوامر**\n🏠 • **الرئيسية** — نظرة عامة سريعة على البوت وحالته\n🎵 • **الموسيقى** — التشغيل، قائمة الانتظار، البحث، الفلاتر ($prefixplay, $prefixskip, $prefixqueue)\n🔧 • **الأدوات** — الإعدادات، الصوت 24/7، الاستجابة، التصويت ($prefixsettings, $prefixping)\nℹ️ • **الدعم** — سيرفر المجتمع والمساعدة\n\n💡 **تلميح:** انقر على إيموجيات التبويب بالأسفل للتبديل بين الأقسام، أو استخدم $prefixhelp <اسم الأمر> لمزيد من التفاصيل.",
|
||||||
|
"supportContent": "هل تحتاج إلى مساعدة، أو ترغب في الإبلاغ عن خطأ، أو اقتراح ميزات جديدة؟\n\n💬 **[انضم إلى سيرفر دعم Remix](https://fluxer.gg/remix)**\n\n**الفريق والمطورون:**\n• **Fantic** — مدير المجتمع\n• **Shadow** — المطور الرئيسي\n• **NoLogicAlan** — المطور الرئيسي\n\nيمكنك أيضاً استخدام $prefixinvite لإضافة Remix إلى سيرفرك.",
|
||||||
|
"noCommands": "_لا توجد أوامر متاحة._",
|
||||||
|
"learnMore": "\nلمعرفة المزيد حول أمر معين، شغّل $prefixhelp <اسم الأمر>!",
|
||||||
|
"subpageTip": "\n\n**تلميح:** استخدم ⬅️ ➡️ للتنقل بين الصفحات."
|
||||||
},
|
},
|
||||||
"invalidFlag": "علامة غير صالحة `$invalidFlag`. لا تتطابق مع أي خيار لهذا الأمر.\n`$previousCmd $invalidFlag`",
|
"invalidFlag": "علامة غير صالحة `$invalidFlag`. لا تتطابق مع أي خيار لهذا الأمر.\n`$previousCmd $invalidFlag`",
|
||||||
"page": {
|
"page": {
|
||||||
@@ -69,7 +82,7 @@
|
|||||||
"remove": "أزل أغنية محددة من قائمة الانتظار.",
|
"remove": "أزل أغنية محددة من قائمة الانتظار.",
|
||||||
"resume": "استئناف التشغيل في قناتك الصوتية.",
|
"resume": "استئناف التشغيل في قناتك الصوتية.",
|
||||||
"search": "اعرض نتائج البحث عن استعلام واختر واحدة لتشغيلها.\nيدعم جميع المزودين — استخدم بادئة مضمنة مثل `sp: أغنية` أو `-p dz`.",
|
"search": "اعرض نتائج البحث عن استعلام واختر واحدة لتشغيلها.\nيدعم جميع المزودين — استخدم بادئة مضمنة مثل `sp: أغنية` أو `-p dz`.",
|
||||||
"servers": "احصل على قائمة بالخوادم الموجود فيها البوت.",
|
"servers": "احصل على قائمة بالمجتمعات الموجود فيها البوت.",
|
||||||
"settings": "تغيير/عرض الإعدادات في الخادم الحالي.",
|
"settings": "تغيير/عرض الإعدادات في الخادم الحالي.",
|
||||||
"shuffle": "أعد ترتيب قائمة الانتظار بشكل عشوائي.",
|
"shuffle": "أعد ترتيب قائمة الانتظار بشكل عشوائي.",
|
||||||
"skip": "تخطي الأغنية التي يتم تشغيلها حالياً.",
|
"skip": "تخطي الأغنية التي يتم تشغيلها حالياً.",
|
||||||
@@ -91,7 +104,13 @@
|
|||||||
"pitch": "تعديل طبقة الصوت (النغمة) للمقطع الصوتي الحالي (0.5× إلى 2.0×).",
|
"pitch": "تعديل طبقة الصوت (النغمة) للمقطع الصوتي الحالي (0.5× إلى 2.0×).",
|
||||||
"previous": "تشغيل الأغنية السابقة من سجل التشغيل.",
|
"previous": "تشغيل الأغنية السابقة من سجل التشغيل.",
|
||||||
"replay": "إعادة تشغيل الأغنية الحالية من البداية.",
|
"replay": "إعادة تشغيل الأغنية الحالية من البداية.",
|
||||||
"skipto": "التخطي مباشرة إلى أغنية معينة في قائمة الانتظار."
|
"skipto": "التخطي مباشرة إلى أغنية معينة في قائمة الانتظار.",
|
||||||
|
"statustest": "اختبار تحديثات قناة الحالة العامة والبطاقات المباشرة والحوادث.",
|
||||||
|
"top": "عرض أكثر الأغاني والفنانين تشغيلاً في هذا السيرفر.",
|
||||||
|
"wrapped": "إنشاء ملخص موسيقى المجتمع وإحصائيات الاستماع.",
|
||||||
|
"mywrapped": "عرض ملخص الموسيقى الشخصي الخاص بك، وأفضل أغانيك، ورتبتك كـ DJ في السيرفر.",
|
||||||
|
"fav": "حفظ المسارات المفضلة وتشغيلها في القنوات الصوتية.",
|
||||||
|
"playlist": "حفظ قائمة الانتظار الحالية أو إدارة قوائم التشغيل المخصصة."
|
||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
"debug": {
|
"debug": {
|
||||||
@@ -190,6 +209,22 @@
|
|||||||
},
|
},
|
||||||
"skipto": {
|
"skipto": {
|
||||||
"position": "رقم الأغنية في قائمة الانتظار للانتقال إليها."
|
"position": "رقم الأغنية في قائمة الانتظار للانتقال إليها."
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"timeframe": "تصفية الإطار الزمني: 24h أو week أو month أو year أو all أو global، أو رقم الصفحة.",
|
||||||
|
"page": "رقم الصفحة للانتقال إليها."
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"scope": "نطاق الملخص: server أو global."
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"user": "المستخدم الذي تريد عرض ملخصه الموسيقي."
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"args": "أمر فرعي أو مسار: play، list، remove، clear، أو اتركه فارغاً للتبديل."
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"args": "أمر فرعي ومعاملات: save، play، list، show، add، remove، delete."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pagination": {
|
"pagination": {
|
||||||
@@ -356,7 +391,10 @@
|
|||||||
"autoLeaveFooter": "إبقاء البوت في القناة الصوتية 24/7 باستخدام {{prefix}}247",
|
"autoLeaveFooter": "إبقاء البوت في القناة الصوتية 24/7 باستخدام {{prefix}}247",
|
||||||
"joinFailedAuthor": "🔊 خطأ في الاتصال الصوتي",
|
"joinFailedAuthor": "🔊 خطأ في الاتصال الصوتي",
|
||||||
"joinFailedTitle": "فشل في الاتصال",
|
"joinFailedTitle": "فشل في الاتصال",
|
||||||
"joinFailedFooter": "تحقق من أذونات القناة الصوتية وأعد المحاولة باستخدام {{prefix}}join"
|
"joinFailedFooter": "تحقق من أذونات القناة الصوتية وأعد المحاولة باستخدام {{prefix}}join",
|
||||||
|
"inactivityWarningTitle": "مغادرة القناة الصوتية قريباً",
|
||||||
|
"inactivityWarningDesc": "الجلسة الصوتية غير نشطة حالياً. سيتم قطع الاتصال من <#{{channel}}> خلال **{{minutes}} دقيقة**.\n\nاستخدم {{prefix}}247 للإبقاء في القناة 24/7!",
|
||||||
|
"inactivityWarningFooter": "قم بتشغيل أغنية باستخدام {{prefix}}play للاستئناف"
|
||||||
},
|
},
|
||||||
"leave": {
|
"leave": {
|
||||||
"noVoiceChannel": "⚠️ يرجى الانضمام إلى قناة صوتية أولاً، أو حدد واحدة: `{{prefix}}leave <#channel>`",
|
"noVoiceChannel": "⚠️ يرجى الانضمام إلى قناة صوتية أولاً، أو حدد واحدة: `{{prefix}}leave <#channel>`",
|
||||||
@@ -540,7 +578,12 @@
|
|||||||
"loadingDirectStream": "🔎 جاري تحميل البث المباشر...",
|
"loadingDirectStream": "🔎 جاري تحميل البث المباشر...",
|
||||||
"resolvingLavalinkStream": "🔎 جاري حل البث عبر Lavalink...",
|
"resolvingLavalinkStream": "🔎 جاري حل البث عبر Lavalink...",
|
||||||
"lastfmPlaybackAuthor": "🎵 تشغيل Last.fm",
|
"lastfmPlaybackAuthor": "🎵 تشغيل Last.fm",
|
||||||
"lastfmSearchAuthor": "🔎 بحث Last.fm"
|
"lastfmSearchAuthor": "🔎 بحث Last.fm",
|
||||||
|
"loadingAttachmentStream": "جارٍ تحميل مرفق وسائط Fluxer...",
|
||||||
|
"sourceAttachment": "مرفق Fluxer",
|
||||||
|
"noQueryTitle": "الأغنية أو المرفق مطلوب",
|
||||||
|
"noQueryDesc": "يرجى تقديم استعلام بحث أو رابط وسائط مباشر أو تحميل ملف صوت/فيديو مع هذا الأمر.",
|
||||||
|
"noQueryFooter": "مشغّل الموسيقى • دعم المرفقات المباشرة"
|
||||||
},
|
},
|
||||||
"playnext": {
|
"playnext": {
|
||||||
"searching": "🔍 جارٍ البحث...",
|
"searching": "🔍 جارٍ البحث...",
|
||||||
@@ -649,14 +692,14 @@
|
|||||||
"cancelOption": "إلغاء"
|
"cancelOption": "إلغاء"
|
||||||
},
|
},
|
||||||
"servers": {
|
"servers": {
|
||||||
"noServers": "_لم يتم العثور على خوادم._",
|
"noServers": "_لم يتم العثور على مجتمعات._",
|
||||||
"title": "🌐 الخوادم ({{count}})",
|
"title": "🌐 المجتمعات ({{count}})",
|
||||||
"pageTitle": "🌐 الخوادم ({{count}}) - صفحة {{page}}/{{total}}",
|
"pageTitle": "🌐 المجتمعات ({{count}}) - صفحة {{page}}/{{total}}",
|
||||||
"listComplete": "اكتملت القائمة",
|
"listComplete": "اكتملت القائمة",
|
||||||
"serversAuthor": "🌐 هيكلية الشبكة",
|
"serversAuthor": "🌐 هيكلية الشبكة",
|
||||||
"serversTitle": "دليل السيرفرات المتصلة",
|
"serversTitle": "دليل المجتمعات المتصلة",
|
||||||
"serversActiveBadge": "{{count}} سيرفر نشط",
|
"serversActiveBadge": "{{count}} مجتمع نشط",
|
||||||
"serversTelemetryFooter": "بيانات السيرفرات في الوقت الفعلي • صفحة {{page}}/{{total}}"
|
"serversTelemetryFooter": "بيانات المجتمعات في الوقت الفعلي • صفحة {{page}}/{{total}}"
|
||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"unknownSetting": "❌ إعداد غير معروف `{{setting}}`.",
|
"unknownSetting": "❌ إعداد غير معروف `{{setting}}`.",
|
||||||
@@ -824,7 +867,7 @@
|
|||||||
"categoryMusic": "🎧 النشاط الموسيقي",
|
"categoryMusic": "🎧 النشاط الموسيقي",
|
||||||
"categoryLastfm": "🎵 Last.fm",
|
"categoryLastfm": "🎵 Last.fm",
|
||||||
"categoryPerformance": "⚡ النظام والشبكة",
|
"categoryPerformance": "⚡ النظام والشبكة",
|
||||||
"servers": "📂 **الخوادم**",
|
"servers": "📂 **المجتمعات**",
|
||||||
"users": "👥 **المستخدمون**",
|
"users": "👥 **المستخدمون**",
|
||||||
"players": "🎧 **المشغّلات**",
|
"players": "🎧 **المشغّلات**",
|
||||||
"playersWithPlaying": "{{total}} ({{playing}} قيد التشغيل)",
|
"playersWithPlaying": "{{total}} ({{playing}} قيد التشغيل)",
|
||||||
@@ -1317,6 +1360,146 @@
|
|||||||
"floodTitle": "تم إسقاط رسائل السجل",
|
"floodTitle": "تم إسقاط رسائل السجل",
|
||||||
"floodDesc": "⚠️ تم إسقاط **{{count}}** رسالة سجل إضافية أثناء الفيضان لحماية قيود معدل واجهة برمجة التطبيقات.",
|
"floodDesc": "⚠️ تم إسقاط **{{count}}** رسالة سجل إضافية أثناء الفيضان لحماية قيود معدل واجهة برمجة التطبيقات.",
|
||||||
"floodFooter": "حارس حد المعدل • ErrorChannel"
|
"floodFooter": "حارس حد المعدل • ErrorChannel"
|
||||||
|
},
|
||||||
|
"statustest": {
|
||||||
|
"author": "Remix · تشخيص قناة الحالة",
|
||||||
|
"disabledAuthor": "مركز حالة Remix",
|
||||||
|
"disabledTitle": "قناة الحالة معطلة",
|
||||||
|
"disabledDesc": "❌ قناة الحالة **معطلة** حالياً أو لا يوجد `channelId` محدد.\n\nقم بتهيئة `statusChannel` في ملف `config.json`:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"معرف_القناة_الخاص_بك\",\n \"mentionRoleId\": \"معرف_الرتبة_الاختياري\",\n \"updateIntervalSeconds\": 300\n}\n```",
|
||||||
|
"refreshedTitle": "✅ تم تحديث البطاقة المباشرة",
|
||||||
|
"refreshedDesc": "تم إرسال تحديث القياس المباشر إلى <#{{channelId}}>.\nمعرف رسالة البطاقة: `{{messageId}}`",
|
||||||
|
"incidentTitle": "🔴 تم إطلاق حادث اختبار",
|
||||||
|
"incidentDesc": "تم نشر انقطاع الحادث لـ **{{target}}** في <#{{channelId}}>.\nقم بتشغيل `{{prefix}}statustest resolve {{target}}` لحله.",
|
||||||
|
"resolvedTitle": "✅ تم حل حادث الاختبار",
|
||||||
|
"resolvedDesc": "تم نشر حل الحادث لـ **{{target}}** في <#{{channelId}}>.",
|
||||||
|
"helpTitle": "أوامر قناة الحالة",
|
||||||
|
"helpDesc": "قناة الحالة **نشطة** في <#{{channelId}}>.\nالبطاقة المباشرة الحالية: `{{cardId}}`\n\n**خيارات الاستخدام:**\n• `{{prefix}}statustest refresh` — فرض تحديث رسالة الحالة المباشرة.\n• `{{prefix}}statustest incident <target>` — إطلاق رسالة انقطاع تجريبية.\n• `{{prefix}}statustest resolve <target>` — حل الانقطاع وتسجيل وقت التوقف.\n\n*الأهداف الصالحة:* `gateway`, `audioNode`, `database`, `dashboard`, `api`"
|
||||||
|
},
|
||||||
|
"statusChannel": {
|
||||||
|
"liveCardTitle": "حالة النظام المباشرة",
|
||||||
|
"liveCardAuthor": "Remix · القياس عن بُعد وحالة النظام",
|
||||||
|
"operationalDesc": "🟢 **جميع الأنظمة تعمل بكفاءة**\nيعمل Remix بسلاسة عبر جميع السيرفرات.",
|
||||||
|
"degradedDesc": "🟡 **انقطاع جزئي**\nبعض الأنظمة الفرعية غير الحرجة تواجه اضطرابات.",
|
||||||
|
"criticalDesc": "🔴 **تم اكتشاف انقطاع كبير**\nإحدى الخدمات الرئيسية أو أكثر غير متصلة حالياً.",
|
||||||
|
"gatewayField": "🏓 زمن استجابة البوابة (Gateway)",
|
||||||
|
"uptimeField": "⏱️ وقت التشغيل",
|
||||||
|
"sessionsField": "🎵 الجلسات النشطة",
|
||||||
|
"ramField": "📟 الذاكرة (RAM)",
|
||||||
|
"cpuField": "⚙️ استهلاك المعالج",
|
||||||
|
"guildsField": "🏰 تواجد المجتمعات",
|
||||||
|
"subsystemsField": "🛡️ صحة الأنظمة الفرعية",
|
||||||
|
"incidentAuthor": "🔴 تم اكتشاف حادث",
|
||||||
|
"incidentTitle": "🔴 {{name}} متوقف حالياً",
|
||||||
|
"incidentDefaultDesc": "تواجه خدمة {{name}} اضطرابات. فريقنا يحقق في المشكلة بنشاط.",
|
||||||
|
"resolvedAuthor": "✅ تم حل الحادث",
|
||||||
|
"resolvedTitle": "✅ عاد {{name}} للعمل مجدداً",
|
||||||
|
"resolvedDefaultDesc": "تمت استعادة الاتصال بـ {{name}} بالكامل والتحقق من استقراره.",
|
||||||
|
"downtimeField": "مدة التوقف",
|
||||||
|
"startedField": "البداية",
|
||||||
|
"resolvedField": "تم الحل",
|
||||||
|
"statusField": "الحالة",
|
||||||
|
"severityField": "مستوى الخطورة",
|
||||||
|
"investigating": "قيد التحقيق",
|
||||||
|
"stable": "مستقر",
|
||||||
|
"operational": "يعمل",
|
||||||
|
"outage": "اضطرابات",
|
||||||
|
"disabled": "معطل"
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"topAuthor": "لوحة المتصدرين في السيرفر",
|
||||||
|
"topTitle": "أكثر الأغاني تشغيلاً ({{timeframe}})",
|
||||||
|
"noData": "لم يتم تشغيل أي أغاني في هذا السيرفر بعد. ابدأ التشغيل بـ {{prefix}}play <أغنية>!",
|
||||||
|
"timeframeWeek": "هذا الأسبوع",
|
||||||
|
"timeframeMonth": "هذا الشهر",
|
||||||
|
"timeframeAll": "كل الأوقات",
|
||||||
|
"topFooter": "تصفية عبر: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all",
|
||||||
|
"plays": "تشغيلات",
|
||||||
|
"globalAuthor": "لوحة المتصدرين العالمية • كل السيرفرات",
|
||||||
|
"globalTitle": "أكثر الأغاني تشغيلاً عبر كل السيرفرات",
|
||||||
|
"globalFooter": "تصفية عبر: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global",
|
||||||
|
"pageFooter": "الصفحة {{page}}/{{totalPages}} • {{timeframe}}",
|
||||||
|
"serverFallbackNote": "ℹ️ _لم يتم تشغيل أي أغانٍ في هذا السيرفر بعد — عرض مخططات الشبكة العالمية:_",
|
||||||
|
"timeframeDay": "آخر 24 ساعة",
|
||||||
|
"timeframeYear": "هذه السنة"
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"wrappedAuthor": "ملخص موسيقى المجتمع",
|
||||||
|
"wrappedTitle": "شخصية السيرفر الموسيقية",
|
||||||
|
"totalStreamed": "إجمالي البث",
|
||||||
|
"tracksQueued": "الأغاني المضافة",
|
||||||
|
"peakHour": "ساعة الذروة للاستماع",
|
||||||
|
"topDJ": "أفضل دي جي في المجتمع",
|
||||||
|
"topSongs": "أفضل الأغاني",
|
||||||
|
"wrappedFooter": "مشغل بواسطة Remix Music • شغل الموسيقى بـ {{prefix}}play",
|
||||||
|
"globalAuthor": "ملخص شبكة ريمكس • كل السيرفرات",
|
||||||
|
"globalTitle": "شخصية الموسيقى العالمية",
|
||||||
|
"activeServers": "المجتمعات النشطة",
|
||||||
|
"globalFooter": "شبكة ريمكس العالمية • اكتب {{prefix}}wrapped لملخص سيرفرك"
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"authorSelf": "ملخص الموسيقى الشخصي الخاص بك",
|
||||||
|
"authorOther": "ملخص الموسيقى الشخصي • {{username}}",
|
||||||
|
"titleSelf": "هويتك الموسيقية في السيرفر",
|
||||||
|
"titleOther": "الهوية الموسيقية لـ {{username}}",
|
||||||
|
"totalStreamed": "إجمالي وقت الاستماع",
|
||||||
|
"tracksQueued": "الأغاني المشغلة",
|
||||||
|
"peakHour": "وقت الذروة في الاستماع",
|
||||||
|
"djRank": "رتبة DJ في المجتمع",
|
||||||
|
"djRankValue": "المركز #{{rank}} من أصل {{total}} DJs",
|
||||||
|
"topArtist": "الفنان المفضل",
|
||||||
|
"topSongs": "أفضل أغانيك الشخصية",
|
||||||
|
"noDataSelf": "لم تقم بتشغيل أي أغانٍ في هذا السيرفر بعد. ابدأ التشغيل بـ {{prefix}}play <أغنية>!",
|
||||||
|
"noDataOther": "لم يقم {{username}} بتشغيل أي أغانٍ في هذا السيرفر بعد.",
|
||||||
|
"globalNotice": "🌐 إحصائيات عالمية • لم يتم تشغيل أغانٍ في هذا السيرفر بعد",
|
||||||
|
"footer": "مشغل بواسطة Remix Music • {{prefix}}top لمخططات السيرفر"
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"notAvailable": "المفضلة الشخصية غير متوفرة (قاعدة البيانات غير متصلة).",
|
||||||
|
"empty": "ليس لديك أي مسارات مفضلة محفوظة بعد! استخدم `{{prefix}}fav` أثناء تشغيل أغنية لحفظها.",
|
||||||
|
"invalidIndex": "رقم المسار غير صالح. يرجى اختيار رقم بين 1 و {{max}}.",
|
||||||
|
"queuedOne": "تمت إضافة المسار المفضل إلى قائمة الانتظار: **[{{title}}]({{url}})**",
|
||||||
|
"queuedAll": "تمت إضافة **{{count}} مسار مفضل** إلى قائمة الانتظار!",
|
||||||
|
"removeUsage": "الاستخدام: `{{prefix}}fav remove <الرقم|العنوان>`",
|
||||||
|
"notFound": "لم يتم العثور على هذا المسار في مفضلتك.",
|
||||||
|
"removed": "تمت إزالة **[{{title}}]({{url}})** من مفضلتك.",
|
||||||
|
"cleared": "تم مسح جميع المسارات (**{{count}} مسار**) من مفضلتك.",
|
||||||
|
"listTitle": "مسارات {{user}} المفضلة",
|
||||||
|
"listFooter": "صفحة {{page}}/{{totalPages}} • {{total}} محفوظ • استخدم {{prefix}}fav play لتشغيل الكل",
|
||||||
|
"limitReached": "لقد وصلت إلى الحد الأقصى وهو {{max}} مسار مفضل.",
|
||||||
|
"added": "⭐ تمت إضافة **[{{title}}]({{url}})** إلى مفضلتك! (المجموع: {{count}})"
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"notAvailable": "قوائم التشغيل الشخصية غير متوفرة (قاعدة البيانات غير متصلة).",
|
||||||
|
"saveUsage": "الاستخدام: `{{prefix}}playlist save <الاسم> [الرابط]`",
|
||||||
|
"playUsage": "الاستخدام: `{{prefix}}playlist play <الاسم>`",
|
||||||
|
"showUsage": "الاستخدام: `{{prefix}}playlist show <الاسم> [الصفحة]`",
|
||||||
|
"addUsage": "الاستخدام: `{{prefix}}playlist add <الاسم> [الرابط]`",
|
||||||
|
"removeUsage": "الاستخدام: `{{prefix}}playlist remove <الاسم> <رقم_المسار>`",
|
||||||
|
"deleteUsage": "الاستخدام: `{{prefix}}playlist delete <الاسم>`",
|
||||||
|
"emptyQueue": "لا يوجد شيء يتم تشغيله أو في قائمة الانتظار لحفظه! ابدأ بتشغيل الموسيقى أولاً باستخدام `{{prefix}}play`.",
|
||||||
|
"limitReached": "لقد وصلت إلى الحد الأقصى وهو {{max}} قائمة تشغيل مخصصة.",
|
||||||
|
"invalidName": "اسم قائمة التشغيل غير صالح. يجب أن يتراوح الاسم بين 1 و 32 حرفاً ولا يحتوي على فواصل مائلة.",
|
||||||
|
"saveFailed": "فشل حفظ قائمة التشغيل. يرجى المحاولة مرة أخرى.",
|
||||||
|
"saved": "💾 تم حفظ **{{count}} مسار** في قائمة التشغيل **{{name}}**! شغلها في أي وقت باستخدام `{{prefix}}playlist play {{name}}`.",
|
||||||
|
"notFound": "لم يتم العثور على قائمة التشغيل **{{name}}**. استخدم `{{prefix}}playlist list` لرؤية قوائمك.",
|
||||||
|
"playlistEmpty": "قائمة التشغيل **{{name}}** فارغة.",
|
||||||
|
"queued": "▶️ تم تحميل قائمة التشغيل **{{name}}** (**{{count}} مسار**) إلى قائمة الانتظار!",
|
||||||
|
"listTitle": "قوائم تشغيل {{user}} المخصصة",
|
||||||
|
"noPlaylists": "ليس لديك أي قوائم تشغيل محفوظة بعد! استخدم `{{prefix}}playlist save <الاسم>` لحفظ قائمة الانتظار الحالية.",
|
||||||
|
"listFooter": "صفحة {{page}}/{{totalPages}} • {{total}}/{{max}} قائمة تشغيل • للتشغيل: {{prefix}}playlist play <الاسم>",
|
||||||
|
"showTitle": "قائمة التشغيل: {{name}}",
|
||||||
|
"showFooter": "صفحة {{page}}/{{totalPages}} • {{total}} مسار في {{name}} • للتشغيل: {{prefix}}playlist play {{name}}",
|
||||||
|
"nothingPlaying": "لا يوجد مسار قيد التشغيل حالياً لإضافته.",
|
||||||
|
"playlistFull": "وصلت قائمة التشغيل هذه إلى الحد الأقصى وهو {{max}} مسار.",
|
||||||
|
"addFailed": "فشل إضافة المسار إلى قائمة التشغيل.",
|
||||||
|
"trackAdded": "تمت إضافة **{{title}}** إلى قائمة التشغيل **{{name}}**! (المجموع: {{count}} مسار)",
|
||||||
|
"invalidIndex": "فهرس المسار غير صالح.",
|
||||||
|
"trackRemoved": "تمت إزالة **{{title}}** من قائمة التشغيل **{{name}}**! (المتبقي: {{count}} مسار)",
|
||||||
|
"deleted": "🗑️ تم حذف قائمة التشغيل **{{name}}**.",
|
||||||
|
"resolving": "🔎 جاري جلب المسارات من **{{source}}**...",
|
||||||
|
"savedFromSource": "💾 تم حفظ **{{count}} مسار(ات)** من **{{source}}** في قائمة **{{name}}**! شغّلها في أي وقت باستخدام `{{prefix}}playlist play {{name}}`.",
|
||||||
|
"noTracksFromSource": "تعذر العثور على أي مسارات قابلة للتشغيل من هذا الرابط.",
|
||||||
|
"tracksAdded": "تمت إضافة **{{addedCount}} مسار(ات)** إلى قائمة **{{name}}**! (الإجمالي: {{count}} مسار)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+195
-12
@@ -35,7 +35,20 @@
|
|||||||
"permission": "مۆڵەت `{{$permission}}`",
|
"permission": "مۆڵەت `{{$permission}}`",
|
||||||
"optionCount": "{{$count}} هەڵبژاردن(ەکان)",
|
"optionCount": "{{$count}} هەڵبژاردن(ەکان)",
|
||||||
"commandInspectorAuthor": "یارمەتیی فەرمان • {{prefix}}{{name}}",
|
"commandInspectorAuthor": "یارمەتیی فەرمان • {{prefix}}{{name}}",
|
||||||
"commandInspectorFooter": "بنوسە {{prefix}}help بۆ هەموو فەرمانەکان • پۆل: {{category}}"
|
"commandInspectorFooter": "بنوسە {{prefix}}help بۆ هەموو فەرمانەکان • پۆل: {{category}}",
|
||||||
|
"tabHome": "سەرەتا",
|
||||||
|
"tabHomeHeader": "لاپەڕەی سەرەتا",
|
||||||
|
"tabMusic": "مۆسیقا",
|
||||||
|
"tabMusicHeader": "فەرمانەکانی مۆسیقا",
|
||||||
|
"tabUtil": "ئامرازەکان",
|
||||||
|
"tabUtilHeader": "فەرمانەکانی ئامراز",
|
||||||
|
"tabSupport": "پشتیوانی",
|
||||||
|
"tabSupportHeader": "زانیاریی پشتیوانی",
|
||||||
|
"homeContent": "**Remix** بۆتێکی مۆسیقای کوالیتی بەرزە کە 24/7 کاردەکات و پشتگیری لە YouTube, Spotify, SoundCloud, Deezer و زیاتر دەکات.\n\n**✨ تایبەتمەندییە سەرەکییەکان**\n• **دەنگی Hi-Fi بە کوالیتی 48kHz** — پەخشی دەنگی زۆر ڕوون\n• **زیاتر لە ٣٠ فلتەری دەنگ** — Bassboost, 8D, Nightcore, Vaporwave, یەکسانکەر\n• **یەکسانسازیی داینامیکی** — هاوسەنگکردنی ئاستی دەنگی EBU R128 لەنێوان سەرچاوەکاندا\n• **ڕادیۆی ئۆنلاینی 24/7** — زیاتر لە ٣٠،٠٠٠ وێستگەی ڕادیۆی ڕاستەوخۆ لە سەرانسەری جیهان\n\n**📂 بەشەکانی فەرمان**\n🏠 • **سەرەتا** — کورتەیەک دەربارەی بۆت و دۆخی ئێستا\n🎵 • **مۆسیقا** — لێدان، ڕیزبەندی، گەڕان، فلتەرەکان ($prefixplay, $prefixskip, $prefixqueue)\n🔧 • **ئامرازەکان** — ڕێکخستنەکان، دەنگی 24/7، پینگ، دەنگدان ($prefixsettings, $prefixping)\nℹ️ • **پشتیوانی** — سێرڤەری کۆمەڵگە و هاوکاری\n\n💡 **ئامۆژگاری:** پەنجە بنێ بە ئیمۆجییەکانی خوارەوە بۆ گۆڕینی بەشەکان، یان $prefixhelp <ناوی فەرمان> بەکاربهێنە بۆ زانیاریی زیاتر.",
|
||||||
|
"supportContent": "پێویستیت بە هاوکارییە، دەتەوێت کێشەیەک ڕابگەیەنیت، یان پێشنیاری تایبەتمەندیی نوێ بکەیت؟\n\n💬 **[بەشداری لە سێرڤەری پشتیوانیی Remix بکە](https://fluxer.gg/remix)**\n\n**تیم و گەشەپێدەران:**\n• **Fantic** — بەڕێوەبەری کۆمەڵگە\n• **Shadow** — گەشەپێدەری سەرەکی\n• **NoLogicAlan** — گەشەپێدەری سەرەکی\n\nدەتوانیت $prefixinvite بەکاربهێنیت بۆ زیادکردنی Remix بۆ سێرڤەرەکەت.",
|
||||||
|
"noCommands": "_هیچ فەرمانێک بەردەست نییە._",
|
||||||
|
"learnMore": "\nبۆ زانینی زیاتر دەربارەی فەرمانێک، $prefixhelp <ناوی فەرمان> لێبدە!",
|
||||||
|
"subpageTip": "\n\n**ئامۆژگاری:** ⬅️ ➡️ بەکاربهێنە بۆ گەڕان لەنێوان لاپەڕەکان."
|
||||||
},
|
},
|
||||||
"invalidFlag": "ئاڵای نادروست `$invalidFlag`. لەگەڵ هیچ هەڵبژاردنێکی ئەم فەرمانە نایگونجێت.\n`$previousCmd $invalidFlag`",
|
"invalidFlag": "ئاڵای نادروست `$invalidFlag`. لەگەڵ هیچ هەڵبژاردنێکی ئەم فەرمانە نایگونجێت.\n`$previousCmd $invalidFlag`",
|
||||||
"page": {
|
"page": {
|
||||||
@@ -69,7 +82,7 @@
|
|||||||
"remove": "گۆرانییەکی دیاریکراو لە ڕیزبەندییەکە دەربهێنە.",
|
"remove": "گۆرانییەکی دیاریکراو لە ڕیزبەندییەکە دەربهێنە.",
|
||||||
"resume": "پەخشکردنەکە لە کەناڵی دەنگیت بەردەوامبکە.",
|
"resume": "پەخشکردنەکە لە کەناڵی دەنگیت بەردەوامبکە.",
|
||||||
"search": "ئەنجامی گەڕان بۆ پرسیارێک نیشان بدە و یەکێکیان هەڵبژێرە بۆ پەخش.\nهەموو دابینکەران پشتگیری دەکرێن — پێشگر بەکاربهێنە وەک `sp: گۆرانی` یان `-p dz`.",
|
"search": "ئەنجامی گەڕان بۆ پرسیارێک نیشان بدە و یەکێکیان هەڵبژێرە بۆ پەخش.\nهەموو دابینکەران پشتگیری دەکرێن — پێشگر بەکاربهێنە وەک `sp: گۆرانی` یان `-p dz`.",
|
||||||
"servers": "لیستی سێرڤەرەکان کە بۆتەکەی تێدایە وەربگرە.",
|
"servers": "لیستی کۆمەڵگەکان کە بۆتەکەی تێدایە وەربگرە.",
|
||||||
"settings": "ڕێکخستنەکان لە سێرڤەری ئێستادا بگۆڕە/وەربگرە.",
|
"settings": "ڕێکخستنەکان لە سێرڤەری ئێستادا بگۆڕە/وەربگرە.",
|
||||||
"shuffle": "ڕیزبەندییەکە بە شێوەیەکی هەڕەمەکی دووبارە ڕیز بکەرەوە.",
|
"shuffle": "ڕیزبەندییەکە بە شێوەیەکی هەڕەمەکی دووبارە ڕیز بکەرەوە.",
|
||||||
"skip": "گۆرانیی ئێستا بتێپەڕێ.",
|
"skip": "گۆرانیی ئێستا بتێپەڕێ.",
|
||||||
@@ -91,7 +104,13 @@
|
|||||||
"pitch": "دەستکاریکردنی تۆن و ئاستی دەنگی تراکی ئێستا (0.5× بۆ 2.0×).",
|
"pitch": "دەستکاریکردنی تۆن و ئاستی دەنگی تراکی ئێستا (0.5× بۆ 2.0×).",
|
||||||
"previous": "لێدانی گۆرانی پێشوو لە مێژووی لێدان.",
|
"previous": "لێدانی گۆرانی پێشوو لە مێژووی لێدان.",
|
||||||
"replay": "دووبارە لێدانی گۆرانیی ئێستا لە سەرەتاوە.",
|
"replay": "دووبارە لێدانی گۆرانیی ئێستا لە سەرەتاوە.",
|
||||||
"skipto": "پەڕینەوەی ڕاستەوخۆ بۆ گۆرانییەکی دیاریکراو لە ڕیزبەندی."
|
"skipto": "پەڕینەوەی ڕاستەوخۆ بۆ گۆرانییەکی دیاریکراو لە ڕیزبەندی.",
|
||||||
|
"statustest": "تاقیکردنەوەی نوێکردنەوەکانی کەناڵی دۆخی گشتی، کارتی ڕاستەوخۆ و ڕووداوەکان.",
|
||||||
|
"top": "بینینی زۆرترین گۆرانییە لێدراوەکان و هونەرمەندە سەرەکییەکان لەم سێرڤەرەدا.",
|
||||||
|
"wrapped": "دروستکردنی پوختەی مۆسیقای کۆمەڵگە و ئامارەکانی گوێگرتن.",
|
||||||
|
"mywrapped": "پوختەی گوێگرتنی مۆسیقای تایبەتی خۆت، باشترین گۆرانییەکان، و پلەی DJی سێرڤەر ببینە.",
|
||||||
|
"fav": "تۆمارکردنی گۆرانییە دڵخوازەکان و لێدانیان لە کەناڵە دەنگییەکان.",
|
||||||
|
"playlist": "پاشەکەوتکردنی ڕیزی ئێستا یان بەڕێوەبردنی لیستە تایبەتەکانت."
|
||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
"debug": {
|
"debug": {
|
||||||
@@ -190,6 +209,22 @@
|
|||||||
},
|
},
|
||||||
"skipto": {
|
"skipto": {
|
||||||
"position": "ژمارەی گۆرانییەکە لە ڕیزبەندی بۆ پەڕینەوە بۆی."
|
"position": "ژمارەی گۆرانییەکە لە ڕیزبەندی بۆ پەڕینەوە بۆی."
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"timeframe": "فلتەرکردنی کات: 24h یان week یان month یان year یان all یان global، یان ژمارەی پەڕە.",
|
||||||
|
"page": "ژمارەی پەڕە بۆ بازدان."
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"scope": "مەودای پوختە: server یان global."
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"user": "ئەو بەکارهێنەرەی دەتەوێت پوختەی مۆسیقاکەی ببینیت."
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"args": "فەرمانی لاوەکی یان تراک: play, list, remove, clear, یان بە بەتاڵی جێی بهێڵە بۆ گۆڕین."
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"args": "فەرمانی لاوەکی و ئارگۆمێنتەکان: save, play, list, show, add, remove, delete."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pagination": {
|
"pagination": {
|
||||||
@@ -356,7 +391,10 @@
|
|||||||
"autoLeaveFooter": "بۆتەکە لە دەنگدا بهێڵەرەوە 24/7 بە {{prefix}}247",
|
"autoLeaveFooter": "بۆتەکە لە دەنگدا بهێڵەرەوە 24/7 بە {{prefix}}247",
|
||||||
"joinFailedAuthor": "🔊 هەڵەی پەیوەستبوونی دەنگ",
|
"joinFailedAuthor": "🔊 هەڵەی پەیوەستبوونی دەنگ",
|
||||||
"joinFailedTitle": "پەیوەستبوون سەرکەوتوو نەبوو",
|
"joinFailedTitle": "پەیوەستبوون سەرکەوتوو نەبوو",
|
||||||
"joinFailedFooter": "مۆڵەتەکانی کەناڵی دەنگی بپشکنە و دووبارە تاقی بکەرەوە بە {{prefix}}join"
|
"joinFailedFooter": "مۆڵەتەکانی کەناڵی دەنگی بپشکنە و دووبارە تاقی بکەرەوە بە {{prefix}}join",
|
||||||
|
"inactivityWarningTitle": "بەمنزیکانە جێهێشتنی کەناڵی دەنگی",
|
||||||
|
"inactivityWarningDesc": "کەناڵی دەنگی لە ئێستادا ناچالاکە. دابڕان لە <#{{channel}}> لە ماوەی **{{minutes}} خولەکدا**.\n\nبۆ مانەوەی ٢٤/٧ فەرمانی {{prefix}}247 بەکاربهێنە!",
|
||||||
|
"inactivityWarningFooter": "گۆرانییەک لێبدە بە {{prefix}}play بۆ بەردەوامبوون"
|
||||||
},
|
},
|
||||||
"leave": {
|
"leave": {
|
||||||
"noVoiceChannel": "⚠️ تکایە سەرەتا بەشداری کەناڵێکی دەنگی بکە، یان یەکێک دیاریبکە: `{{prefix}}leave <#channel>`",
|
"noVoiceChannel": "⚠️ تکایە سەرەتا بەشداری کەناڵێکی دەنگی بکە، یان یەکێک دیاریبکە: `{{prefix}}leave <#channel>`",
|
||||||
@@ -540,7 +578,12 @@
|
|||||||
"loadingDirectStream": "🔎 بارکردنی پەخشی ڕاستەوخۆ...",
|
"loadingDirectStream": "🔎 بارکردنی پەخشی ڕاستەوخۆ...",
|
||||||
"resolvingLavalinkStream": "🔎 شیکارکردنی پەخش لە ڕێگەی Lavalink...",
|
"resolvingLavalinkStream": "🔎 شیکارکردنی پەخش لە ڕێگەی Lavalink...",
|
||||||
"lastfmPlaybackAuthor": "🎵 لێدانی Last.fm",
|
"lastfmPlaybackAuthor": "🎵 لێدانی Last.fm",
|
||||||
"lastfmSearchAuthor": "🔎 گەڕانی Last.fm"
|
"lastfmSearchAuthor": "🔎 گەڕانی Last.fm",
|
||||||
|
"loadingAttachmentStream": "بارکردنی هاوپێچی میدیای Fluxer...",
|
||||||
|
"sourceAttachment": "هاوپێچی Fluxer",
|
||||||
|
"noQueryTitle": "گۆرانی یان هاوپێچ پێویستە",
|
||||||
|
"noQueryDesc": "تکایە گەڕانێک بنووسە، یان بەستەرێکی ڕاستەوخۆی میدیا یان فایلێکی دەنگ/ڤیدیۆ باربکە لەگەڵ ئەم فەرمانەدا.",
|
||||||
|
"noQueryFooter": "لێدەری مۆسیقا • پشتگیری هاوپێچی ڕاستەوخۆ"
|
||||||
},
|
},
|
||||||
"playnext": {
|
"playnext": {
|
||||||
"searching": "🔍 گەڕان...",
|
"searching": "🔍 گەڕان...",
|
||||||
@@ -649,14 +692,14 @@
|
|||||||
"cancelOption": "هەڵوەشاندنەوە"
|
"cancelOption": "هەڵوەشاندنەوە"
|
||||||
},
|
},
|
||||||
"servers": {
|
"servers": {
|
||||||
"noServers": "_هیچ سێرڤەرێک نەدۆزرایەوە._",
|
"noServers": "_هیچ کۆمەڵگەیەک نەدۆزرایەوە._",
|
||||||
"title": "🌐 سێرڤەرەکان ({{count}})",
|
"title": "🌐 کۆمەڵگەکان ({{count}})",
|
||||||
"pageTitle": "🌐 سێرڤەرەکان ({{count}}) - لاپەڕە {{page}}/{{total}}",
|
"pageTitle": "🌐 کۆمەڵگەکان ({{count}}) - لاپەڕە {{page}}/{{total}}",
|
||||||
"listComplete": "لیست تەواو بوو",
|
"listComplete": "لیست تەواو بوو",
|
||||||
"serversAuthor": "🌐 تۆڕی پەیوەستکراو",
|
"serversAuthor": "🌐 تۆڕی پەیوەستکراو",
|
||||||
"serversTitle": "ڕێبەری سێرڤەرە پەیوەستکراوەکان",
|
"serversTitle": "ڕێبەری کۆمەڵگە پەیوەستکراوەکان",
|
||||||
"serversActiveBadge": "{{count}} سێرڤەری چالاک",
|
"serversActiveBadge": "{{count}} کۆمەڵگەی چالاک",
|
||||||
"serversTelemetryFooter": "زانیاری ڕاستەوخۆی سێرڤەرەکان • پەڕەی {{page}}/{{total}}"
|
"serversTelemetryFooter": "زانیاری ڕاستەوخۆی کۆمەڵگەکان • پەڕەی {{page}}/{{total}}"
|
||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"unknownSetting": "❌ ڕێکخستنی نەناسراو `{{setting}}`.",
|
"unknownSetting": "❌ ڕێکخستنی نەناسراو `{{setting}}`.",
|
||||||
@@ -824,7 +867,7 @@
|
|||||||
"categoryMusic": "🎧 چالاکی موزیک",
|
"categoryMusic": "🎧 چالاکی موزیک",
|
||||||
"categoryLastfm": "🎵 Last.fm",
|
"categoryLastfm": "🎵 Last.fm",
|
||||||
"categoryPerformance": "⚡ سیستەم و هێڵ",
|
"categoryPerformance": "⚡ سیستەم و هێڵ",
|
||||||
"servers": "📂 **سێرڤەرەکان**",
|
"servers": "📂 **کۆمەڵگەکان**",
|
||||||
"users": "👥 **بەکارهێنەران**",
|
"users": "👥 **بەکارهێنەران**",
|
||||||
"players": "🎧 **پەخشکەرەکان**",
|
"players": "🎧 **پەخشکەرەکان**",
|
||||||
"playersWithPlaying": "{{total}} ({{playing}} لێدەدرێت)",
|
"playersWithPlaying": "{{total}} ({{playing}} لێدەدرێت)",
|
||||||
@@ -1317,6 +1360,146 @@
|
|||||||
"floodTitle": "پەیامەکانی تۆمار فڕێدران",
|
"floodTitle": "پەیامەکانی تۆمار فڕێدران",
|
||||||
"floodDesc": "⚠️ **{{count}}** پەیامی زیاتری تۆمار لە کاتی قەرەباڵغیدا فڕێدران بۆ پاراستنی سنووری خێرایی API.",
|
"floodDesc": "⚠️ **{{count}}** پەیامی زیاتری تۆمار لە کاتی قەرەباڵغیدا فڕێدران بۆ پاراستنی سنووری خێرایی API.",
|
||||||
"floodFooter": "پارێزەری سنووری خێرایی • ErrorChannel"
|
"floodFooter": "پارێزەری سنووری خێرایی • ErrorChannel"
|
||||||
|
},
|
||||||
|
"statustest": {
|
||||||
|
"author": "Remix · دەستنیشانکردنی کەناڵی دۆخ",
|
||||||
|
"disabledAuthor": "سەنتەری دۆخی Remix",
|
||||||
|
"disabledTitle": "کەناڵی دۆخ ناچالاکە",
|
||||||
|
"disabledDesc": "❌ کەناڵی دۆخ لە ئێستادا **ناچالاکە** یان `channelId` دانەنراوە.\n\nتکایە `statusChannel` لە `config.json` ڕێکبخە:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"ناسنامەی_کەناڵەکەت\",\n \"mentionRoleId\": \"ناسنامەی_ڕۆڵی_ئارەزوومەندانە\",\n \"updateIntervalSeconds\": 300\n}\n```",
|
||||||
|
"refreshedTitle": "✅ کارتی ڕاستەوخۆ نوێکرایەوە",
|
||||||
|
"refreshedDesc": "نوێکردنەوەی تێلیمیتریی ڕاستەوخۆ نێردرا بۆ <#{{channelId}}>.\nناسنامەی پەیامی کارت: `{{messageId}}`",
|
||||||
|
"incidentTitle": "🔴 ڕووداوی تاقیکاری دەستیپێکرد",
|
||||||
|
"incidentDesc": "پچڕانی ڕووداو بۆ **{{target}}** لە <#{{channelId}}> بڵاوکرایەوە.\nفەرمانی `{{prefix}}statustest resolve {{target}}` جێبەجێ بکە بۆ چارەسەرکردنی.",
|
||||||
|
"resolvedTitle": "✅ ڕووداوی تاقیکاری چارەسەرکرا",
|
||||||
|
"resolvedDesc": "چارەسەرکردنی ڕووداو بۆ **{{target}}** لە <#{{channelId}}> بڵاوکرایەوە.",
|
||||||
|
"helpTitle": "فەرمانەکانی کەناڵی دۆخ",
|
||||||
|
"helpDesc": "کەناڵی دۆخ **چالاکە** لە <#{{channelId}}>.\nکارتی ڕاستەوخۆی ئێستا: `{{cardId}}`\n\n**هەڵبژاردەکانی بەکارهێنان:**\n• `{{prefix}}statustest refresh` — نوێکردنەوەی زۆرەملێی پەیامی دۆخی ڕاستەوخۆ.\n• `{{prefix}}statustest incident <target>` — دەستپێکردنی پەیامی پچڕانی تاقیکاری.\n• `{{prefix}}statustest resolve <target>` — چارەسەرکردنی پچڕان و تۆمارکردنی کاتی وەستان.\n\n*ئامانجە دروستەکان:* `gateway`, `audioNode`, `database`, `dashboard`, `api`"
|
||||||
|
},
|
||||||
|
"statusChannel": {
|
||||||
|
"liveCardTitle": "دۆخی ڕاستەوخۆی سیستەم",
|
||||||
|
"liveCardAuthor": "Remix · تێلیمیتری و دۆخی سیستەم",
|
||||||
|
"operationalDesc": "🟢 **هەموو سیستەمەکان کاردەکەن**\nRemix بە شێوەیەکی باش لە هەموو سێرڤەرەکان کاردەکات.",
|
||||||
|
"degradedDesc": "🟡 **پچڕانی بەشەکی**\nهەندێک لە ژێر-سیستەمە لاوەکییەکان تووشی کێشە بوون.",
|
||||||
|
"criticalDesc": "🔴 **پچڕانی گەورە دۆزرایەوە**\nیەک یان چەند خزمەتگوزارییەکی سەرەکی لەسەر هێڵ نین.",
|
||||||
|
"gatewayField": "🏓 دواکەوتنی دەروازە (Gateway)",
|
||||||
|
"uptimeField": "⏱️ کاتی کارکردن",
|
||||||
|
"sessionsField": "🎵 دانیشتنە چالاکەکان",
|
||||||
|
"ramField": "📟 بیرگە (RAM)",
|
||||||
|
"cpuField": "⚙️ بەکارهێنانی CPU",
|
||||||
|
"guildsField": "🏰 کۆمەڵگە بەشداربووەکان",
|
||||||
|
"subsystemsField": "🛡️ تەندروستیی ژێر-سیستەمەکان",
|
||||||
|
"incidentAuthor": "🔴 ڕووداو دۆزرایەوە",
|
||||||
|
"incidentTitle": "🔴 {{name}} لە کار کەوتووە",
|
||||||
|
"incidentDefaultDesc": "{{name}} تووشی پچڕان بووە. تیمەکەمان سەرقاڵی لێکۆڵینەوەیە.",
|
||||||
|
"resolvedAuthor": "✅ ڕووداو چارەسەرکرا",
|
||||||
|
"resolvedTitle": "✅ {{name}} گەڕایەوە سەر هێڵ",
|
||||||
|
"resolvedDefaultDesc": "پەیوەندی لەگەڵ {{name}} بە تەواوی گەڕێندرایەوە و جێگیرکرا.",
|
||||||
|
"downtimeField": "کاتی وەستان",
|
||||||
|
"startedField": "دەستپێکردن",
|
||||||
|
"resolvedField": "چارەسەرکرا",
|
||||||
|
"statusField": "دۆخ",
|
||||||
|
"severityField": "ئاستی مەترسی",
|
||||||
|
"investigating": "لێکۆڵینەوە دەکرێت",
|
||||||
|
"stable": "جێگیرە",
|
||||||
|
"operational": "کاردەکات",
|
||||||
|
"outage": "پچڕان",
|
||||||
|
"disabled": "ناچالاکە"
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"topAuthor": "ڕیزبەندی سەرەکی سێرڤەر",
|
||||||
|
"topTitle": "زۆرترین گۆرانی لێدراو ({{timeframe}})",
|
||||||
|
"noData": "هێشتا هیچ گۆرانییەک لەم سێرڤەرەدا لێنەدراوە. دەستپێبکە بە {{prefix}}play <گۆرانی>!",
|
||||||
|
"timeframeWeek": "ئەم هەفتەیە",
|
||||||
|
"timeframeMonth": "ئەم مانگە",
|
||||||
|
"timeframeAll": "هەموو کاتێک",
|
||||||
|
"topFooter": "فلتەرکردن بە: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all",
|
||||||
|
"plays": "لێدان",
|
||||||
|
"globalAuthor": "ڕیزبەندی جیهانی • هەموو سێرڤەرەکان",
|
||||||
|
"globalTitle": "زۆرترین گۆرانی لێدراو لە هەموو سێرڤەرەکاندا",
|
||||||
|
"globalFooter": "فلتەرکردن بە: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global",
|
||||||
|
"pageFooter": "پەڕەی {{page}}/{{totalPages}} • {{timeframe}}",
|
||||||
|
"serverFallbackNote": "ℹ️ _تا ئێستا هیچ گۆرانییەک لەم سێرڤەرە لێنەدراوە — پیشاندانی ڕیزبەندیی تۆڕی جیهانی:_",
|
||||||
|
"timeframeDay": "٢٤ کاتژمێری ڕابردوو",
|
||||||
|
"timeframeYear": "ئەمساڵ"
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"wrappedAuthor": "پوختەی مۆسیقای کۆمەڵگە",
|
||||||
|
"wrappedTitle": "کەسایەتی مۆسیقی سێرڤەر",
|
||||||
|
"totalStreamed": "کۆی لێدراو",
|
||||||
|
"tracksQueued": "گۆرانییە ڕیزکراوەکان",
|
||||||
|
"peakHour": "کاتژمێری لوتکەی گوێگرتن",
|
||||||
|
"topDJ": "باشترین دیجیی کۆمەڵگە",
|
||||||
|
"topSongs": "باشترین گۆرانییەکان",
|
||||||
|
"wrappedFooter": "بەهێزکراوە لەلایەن Remix Music • مۆسیقا لێبدە بە {{prefix}}play",
|
||||||
|
"globalAuthor": "پوختەی تۆڕی ریمیکس • هەموو سێرڤەرەکان",
|
||||||
|
"globalTitle": "کەسایەتی مۆسیقی جیهانی",
|
||||||
|
"activeServers": "کۆمەڵگە چالاکەکان",
|
||||||
|
"globalFooter": "تۆڕی جیهانی ریمیکس • بنووسە {{prefix}}wrapped بۆ پوختەی سێرڤەرەکەت"
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"authorSelf": "پوختەی مۆسیقای تایبەتی تۆ",
|
||||||
|
"authorOther": "پوختەی مۆسیقای تایبەتی • {{username}}",
|
||||||
|
"titleSelf": "ناسنامەی گوێگرتنی تۆ لە سێرڤەر",
|
||||||
|
"titleOther": "ناسنامەی گوێگرتنی {{username}} لە سێرڤەر",
|
||||||
|
"totalStreamed": "کۆی کاتی پەخشکراو",
|
||||||
|
"tracksQueued": "گۆرانییە داواکراوەکان",
|
||||||
|
"peakHour": "کاتی لوتکەی گوێگرتن",
|
||||||
|
"djRank": "پلەی DJ لە کۆمەڵگە",
|
||||||
|
"djRankValue": "پلەی #{{rank}} لە {{total}} DJ",
|
||||||
|
"topArtist": "هونەرمەندی دڵخواز",
|
||||||
|
"topSongs": "باشترین گۆرانییە تایبەتییەکان",
|
||||||
|
"noDataSelf": "هێشتا هیچ گۆرانییەکت لەم سێرڤەرە داوا نەکردووە. بە {{prefix}}play <گۆرانی> دەست پێبکە!",
|
||||||
|
"noDataOther": "{{username}} تا ئێستا هیچ گۆرانییەکی لەم سێرڤەرە داوا نەکردووە.",
|
||||||
|
"globalNotice": "🌐 ئاماری جیهانی • تا ئێستا هیچ گۆرانییەک لەم سێرڤەرە لێنەدراوە",
|
||||||
|
"footer": "پشتیوانیکراوە لەلایەن Remix Music • {{prefix}}top بۆ ڕیزبەندیی سێرڤەر"
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"notAvailable": "بەشی دڵخوازەکان بەردەست نییە (داتابەیس پەیوەست نەکراوە).",
|
||||||
|
"empty": "هێشتا هیچ گۆرانییەکی دڵخوازت پاشەکەوت نەکردووە! لە کاتی لێدانی گۆرانیدا `{{prefix}}fav` بەکاربهێنە بۆ نیشانەکردنی.",
|
||||||
|
"invalidIndex": "ژمارەی تراک هەڵەیە. تکایە ژمارەیەک لە نێوان 1 و {{max}} هەڵبژێرە.",
|
||||||
|
"queuedOne": "تراکی دڵخواز خرایە ڕیزەوە: **[{{title}}]({{url}})**",
|
||||||
|
"queuedAll": "**{{count}} تراکی دڵخواز** خرانە ڕیزەوە!",
|
||||||
|
"removeUsage": "بەکارهێنان: `{{prefix}}fav remove <ژمارە|ناونیشان>`",
|
||||||
|
"notFound": "ئەو تراکە لە لیستی دڵخوازەکانتدا نەدۆزرایەوە.",
|
||||||
|
"removed": "**[{{title}}]({{url}})** لە دڵخوازەکانت سڕایەوە.",
|
||||||
|
"cleared": "هەموو **{{count}} تراکەکە** لە دڵخوازەکانت سڕانەوە.",
|
||||||
|
"listTitle": "تراکە دڵخوازەکانی {{user}}",
|
||||||
|
"listFooter": "پەڕەی {{page}}/{{totalPages}} • {{total}} پاشەکەوتکراو • {{prefix}}fav play بەکاربهێنە بۆ لێدانی هەمووی",
|
||||||
|
"limitReached": "گەیشتوویتە ئەوپەڕی سنووری {{max}} تراکی دڵخواز.",
|
||||||
|
"added": "⭐ **[{{title}}]({{url}})** بۆ دڵخوازەکانت زیادکرا! (کۆی گشتی: {{count}})"
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"notAvailable": "لیستە کەسییەکان بەردەست نین (داتابەیس پەیوەست نەکراوە).",
|
||||||
|
"saveUsage": "بەکارهێنان: `{{prefix}}playlist save <ناو> [بەستەر]`",
|
||||||
|
"playUsage": "بەکارهێنان: `{{prefix}}playlist play <ناو>`",
|
||||||
|
"showUsage": "بەکارهێنان: `{{prefix}}playlist show <ناو> [پەڕە]`",
|
||||||
|
"addUsage": "بەکارهێنان: `{{prefix}}playlist add <ناو> [بەستەر]`",
|
||||||
|
"removeUsage": "بەکارهێنان: `{{prefix}}playlist remove <ناو> <ژمارەی_تراک>`",
|
||||||
|
"deleteUsage": "بەکارهێنان: `{{prefix}}playlist delete <ناو>`",
|
||||||
|
"emptyQueue": "هیچ گۆرانییەک لێنادرێت یان لە ڕیزدا نییە بۆ پاشەکەوتکردن! سەرەتا بە `{{prefix}}play` گۆرانی لێبدە.",
|
||||||
|
"limitReached": "گەیشتوویتە ئەوپەڕی سنووری {{max}} لیستی کەسی.",
|
||||||
|
"invalidName": "ناوی لیست نادروستە. ناو دەبێت لە نێوان 1 بۆ 32 پیت بێت و هێڵی لاری تێدا نەبێت.",
|
||||||
|
"saveFailed": "پاشەکەوتکردنی لیست سەرکەوتوو نەبوو. تکایە دووبارە هەوڵبدەرەوە.",
|
||||||
|
"saved": "💾 **{{count}} تراک** پاشەکەوت کرا لە لیستی **{{name}}**! دەتوانی لە هەر کاتێکدا بە `{{prefix}}playlist play {{name}}` لێی بدەیتەوە.",
|
||||||
|
"notFound": "لیستی **{{name}}** نەدۆزرایەوە. `{{prefix}}playlist list` بەکاربهێنە بۆ بینینی لیستەکانت.",
|
||||||
|
"playlistEmpty": "لیستی **{{name}}** بەتاڵە.",
|
||||||
|
"queued": "▶️ لیستی **{{name}}** (**{{count}} تراک**) خرایە ناو ڕیزەوە!",
|
||||||
|
"listTitle": "لیستە تایبەتەکانی {{user}}",
|
||||||
|
"noPlaylists": "هێشتا هیچ لیستێکت پاشەکەوت نەکردووە! `{{prefix}}playlist save <ناو>` بەکاربهێنە بۆ پاشەکەوتکردنی ڕیزی ئێستات.",
|
||||||
|
"listFooter": "پەڕەی {{page}}/{{totalPages}} • {{total}}/{{max}} لیست • بۆ لێدان: {{prefix}}playlist play <ناو>",
|
||||||
|
"showTitle": "لیست: {{name}}",
|
||||||
|
"showFooter": "پەڕەی {{page}}/{{totalPages}} • {{total}} تراک لە {{name}} • بۆ لێدان: {{prefix}}playlist play {{name}}",
|
||||||
|
"nothingPlaying": "لە ئێستادا هیچ تراکێک لێنادرێت بۆ ئەوەی زیاد بکرێت.",
|
||||||
|
"playlistFull": "ئەم لیستە گەیشتووەتە ئەوپەڕی ڕادەی {{max}} تراک.",
|
||||||
|
"addFailed": "زیادکردنی تراک بۆ لیست سەرکەوتوو نەبوو.",
|
||||||
|
"trackAdded": "**{{title}}** زیادکرا بۆ لیستی **{{name}}**! (کۆی گشتی: {{count}} تراک)",
|
||||||
|
"invalidIndex": "ژمارەی تراک هەڵەیە.",
|
||||||
|
"trackRemoved": "**{{title}}** لە لیستی **{{name}}** سڕایەوە! ({{count}} تراک ماوەتەوە)",
|
||||||
|
"deleted": "🗑️ لیستی **{{name}}** سڕایەوە.",
|
||||||
|
"resolving": "🔎 هێنانی تراکەکان لە **{{source}}**...",
|
||||||
|
"savedFromSource": "💾 **{{count}} تراک** لە **{{source}}** پاشەکەوت کران بۆ لیستی **{{name}}**! لە هەر کاتێک لێی بدە بە `{{prefix}}playlist play {{name}}`.",
|
||||||
|
"noTracksFromSource": "هیچ تراکێکی شیاوی لێدان لەم بەستەرە نەدۆزرایەوە.",
|
||||||
|
"tracksAdded": "**{{addedCount}} تراک** زیادکران بۆ لیستی **{{name}}**! (سەرجەم: {{count}} تراک)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+195
-12
@@ -35,7 +35,20 @@
|
|||||||
"permission": "Berechtigung `{{$permission}}`",
|
"permission": "Berechtigung `{{$permission}}`",
|
||||||
"optionCount": "{{$count}} Option(en)",
|
"optionCount": "{{$count}} Option(en)",
|
||||||
"commandInspectorAuthor": "Befehlshilfe • {{prefix}}{{name}}",
|
"commandInspectorAuthor": "Befehlshilfe • {{prefix}}{{name}}",
|
||||||
"commandInspectorFooter": "Tippe {{prefix}}help für die komplette Befehlsliste • Kategorie: {{category}}"
|
"commandInspectorFooter": "Tippe {{prefix}}help für die komplette Befehlsliste • Kategorie: {{category}}",
|
||||||
|
"tabHome": "Startseite",
|
||||||
|
"tabHomeHeader": "Startseite",
|
||||||
|
"tabMusic": "Musik",
|
||||||
|
"tabMusicHeader": "Musik-Befehle",
|
||||||
|
"tabUtil": "Werkzeuge",
|
||||||
|
"tabUtilHeader": "Werkzeug-Befehle",
|
||||||
|
"tabSupport": "Hilfe & Support",
|
||||||
|
"tabSupportHeader": "Support-Informationen",
|
||||||
|
"homeContent": "**Remix** ist ein hochauflösender 24/7 Musik-Bot mit Unterstützung für YouTube, Spotify, SoundCloud, Deezer und mehr.\n\n**✨ Hauptmerkmale**\n• **48kHz Hi-Fi-Audio** — Kristallklare Audio-Streaming-Pipeline\n• **30+ Audio-Filter** — Bassboost, 8D, Nightcore, Vaporwave, Equalizer\n• **Dynamische Normalisierung** — EBU R128 Lautstärkeanpassung über alle Musikquellen\n• **24/7 Webradio** — Über 30.000 weltweite Live-Radiosender\n\n**📂 Befehlskategorien**\n🏠 • **Startseite** — Bot-Übersicht & aktueller Status\n🎵 • **Musik** — Wiedergabe, Warteschlange, Suche, Filter ($prefixplay, $prefixskip, $prefixqueue)\n🔧 • **Werkzeuge** — Einstellungen, 24/7 Sprachkanal, Ping, Vote ($prefixsettings, $prefixping)\nℹ️ • **Support** — Community-Server & Hilfestellung\n\n💡 **Tipp:** Klicke unten auf die Reiter-Emojis, um den Bereich zu wechseln, oder nutze $prefixhelp <Befehl> für detaillierte Infos.",
|
||||||
|
"supportContent": "Brauchst du Hilfe, möchtest einen Fehler melden oder neue Funktionen vorschlagen?\n\n💬 **[Remix Support-Server beitreten](https://fluxer.gg/remix)**\n\n**Team & Entwickler:**\n• **Fantic** — Community Manager\n• **Shadow** — Leitender Entwickler\n• **NoLogicAlan** — Leitender Entwickler\n\nDu kannst auch $prefixinvite verwenden, um Remix zu deinem Server hinzuzufügen.",
|
||||||
|
"noCommands": "_Keine Befehle verfügbar._",
|
||||||
|
"learnMore": "\nUm mehr über einen Befehl zu erfahren, führe $prefixhelp <Befehlsname> aus!",
|
||||||
|
"subpageTip": "\n\n**Tipp:** Verwende ⬅️ ➡️, um zwischen den Seiten zu blättern."
|
||||||
},
|
},
|
||||||
"invalidFlag": "Ungültige Flag `$invalidFlag`. Sie stimmt mit keiner Option dieses Befehls überein.\n`$previousCmd $invalidFlag`",
|
"invalidFlag": "Ungültige Flag `$invalidFlag`. Sie stimmt mit keiner Option dieses Befehls überein.\n`$previousCmd $invalidFlag`",
|
||||||
"page": {
|
"page": {
|
||||||
@@ -69,7 +82,7 @@
|
|||||||
"remove": "Entferne einen bestimmten Song aus der Warteschlange.",
|
"remove": "Entferne einen bestimmten Song aus der Warteschlange.",
|
||||||
"resume": "Setze die Wiedergabe in deinem Sprachkanal fort.",
|
"resume": "Setze die Wiedergabe in deinem Sprachkanal fort.",
|
||||||
"search": "Zeige Suchergebnisse für eine Anfrage an und wähle einen zum Abspielen.\nUnterstützt alle Anbieter — nutze Inline-Präfix wie `sp: song` oder `-p dz`.",
|
"search": "Zeige Suchergebnisse für eine Anfrage an und wähle einen zum Abspielen.\nUnterstützt alle Anbieter — nutze Inline-Präfix wie `sp: song` oder `-p dz`.",
|
||||||
"servers": "Rufe eine Liste der Server ab, in denen der Bot ist.",
|
"servers": "Rufe eine Liste der Communities ab, in denen der Bot ist.",
|
||||||
"settings": "Ändere/Rufe Einstellungen im aktuellen Server ab.",
|
"settings": "Ändere/Rufe Einstellungen im aktuellen Server ab.",
|
||||||
"shuffle": "Ordne die Warteschlange zufällig neu.",
|
"shuffle": "Ordne die Warteschlange zufällig neu.",
|
||||||
"skip": "Überspringe den aktuell spielenden Song.",
|
"skip": "Überspringe den aktuell spielenden Song.",
|
||||||
@@ -91,7 +104,13 @@
|
|||||||
"pitch": "Tonhöhe (Pitch) des aktuellen Tracks anpassen (0.5× bis 2.0×).",
|
"pitch": "Tonhöhe (Pitch) des aktuellen Tracks anpassen (0.5× bis 2.0×).",
|
||||||
"previous": "Den vorherigen Titel aus dem Wiedergabeverlauf abspielen.",
|
"previous": "Den vorherigen Titel aus dem Wiedergabeverlauf abspielen.",
|
||||||
"replay": "Den aktuellen Titel von vorne starten.",
|
"replay": "Den aktuellen Titel von vorne starten.",
|
||||||
"skipto": "Direkt zu einem bestimmten Titel in der Warteschlange springen."
|
"skipto": "Direkt zu einem bestimmten Titel in der Warteschlange springen.",
|
||||||
|
"statustest": "Öffentliche Statuskanal-Aktualisierungen, Live-Karten und Vorfälle testen.",
|
||||||
|
"top": "Zeige die meistgespielten Songs und Top-Künstler dieses Servers an.",
|
||||||
|
"wrapped": "Erstelle einen Community-Musikrückblick und Hörstatistiken.",
|
||||||
|
"mywrapped": "Sieh dir deinen persönlichen Musik-Rückblick, Top-Tracks und Server-DJ-Rang an.",
|
||||||
|
"fav": "Lieblingslieder speichern und in Sprachkanälen abspielen.",
|
||||||
|
"playlist": "Aktuelle Warteschlange speichern oder eigene Playlists verwalten."
|
||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
"debug": {
|
"debug": {
|
||||||
@@ -190,6 +209,22 @@
|
|||||||
},
|
},
|
||||||
"skipto": {
|
"skipto": {
|
||||||
"position": "Die Nummer des Titels in der Warteschlange, zu dem gesprungen werden soll."
|
"position": "Die Nummer des Titels in der Warteschlange, zu dem gesprungen werden soll."
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"timeframe": "Zeitraum filtern: 24h, week, month, year, all oder global, oder Seitenzahl.",
|
||||||
|
"page": "Seitennummer, zu der gesprungen werden soll."
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"scope": "Rückblick-Bereich: server oder global."
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"user": "Der Benutzer, dessen Musik-Rückblick du sehen möchtest."
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"args": "Unterbefehl oder Track: play, list, remove, clear oder leer lassen zum Umschalten."
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"args": "Unterbefehl und Argumente: save, play, list, show, add, remove, delete."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pagination": {
|
"pagination": {
|
||||||
@@ -356,7 +391,10 @@
|
|||||||
"autoLeaveFooter": "Halte den Bot rund um die Uhr mit {{prefix}}247 im Sprachkanal",
|
"autoLeaveFooter": "Halte den Bot rund um die Uhr mit {{prefix}}247 im Sprachkanal",
|
||||||
"joinFailedAuthor": "🔊 Sprachverbindungsfehler",
|
"joinFailedAuthor": "🔊 Sprachverbindungsfehler",
|
||||||
"joinFailedTitle": "Verbindung fehlgeschlagen",
|
"joinFailedTitle": "Verbindung fehlgeschlagen",
|
||||||
"joinFailedFooter": "Überprüfe die Kanalberechtigungen und versuche es erneut mit {{prefix}}join"
|
"joinFailedFooter": "Überprüfe die Kanalberechtigungen und versuche es erneut mit {{prefix}}join",
|
||||||
|
"inactivityWarningTitle": "Sprachkanal wird bald verlassen",
|
||||||
|
"inactivityWarningDesc": "Sprachkanal ist derzeit inaktiv. Verbindung zu <#{{channel}}> wird in **{{minutes}} Minute(n)** getrennt.\n\nNutze {{prefix}}247, um mich rund um die Uhr im Sprachkanal zu halten!",
|
||||||
|
"inactivityWarningFooter": "Spiele einen Song mit {{prefix}}play, um fortzufahren"
|
||||||
},
|
},
|
||||||
"leave": {
|
"leave": {
|
||||||
"noVoiceChannel": "⚠️ Bitte trete zuerst einem Sprachkanal bei oder gib einen an: `{{prefix}}leave <#channel>`",
|
"noVoiceChannel": "⚠️ Bitte trete zuerst einem Sprachkanal bei oder gib einen an: `{{prefix}}leave <#channel>`",
|
||||||
@@ -540,7 +578,12 @@
|
|||||||
"loadingDirectStream": "🔎 Direkter Stream wird geladen...",
|
"loadingDirectStream": "🔎 Direkter Stream wird geladen...",
|
||||||
"resolvingLavalinkStream": "🔎 Stream wird über Lavalink aufgelöst...",
|
"resolvingLavalinkStream": "🔎 Stream wird über Lavalink aufgelöst...",
|
||||||
"lastfmPlaybackAuthor": "🎵 Last.fm-Wiedergabe",
|
"lastfmPlaybackAuthor": "🎵 Last.fm-Wiedergabe",
|
||||||
"lastfmSearchAuthor": "🔎 Last.fm-Suche"
|
"lastfmSearchAuthor": "🔎 Last.fm-Suche",
|
||||||
|
"loadingAttachmentStream": "Lade Fluxer-Medienanhang...",
|
||||||
|
"sourceAttachment": "Fluxer-Anhang",
|
||||||
|
"noQueryTitle": "Titel oder Anhang erforderlich",
|
||||||
|
"noQueryDesc": "Bitte gib einen Suchbegriff oder direkten Medienlink an oder lade eine Audio-/Videodatei mit diesem Befehl hoch.",
|
||||||
|
"noQueryFooter": "Musikplayer • Direkte Anhangsunterstützung"
|
||||||
},
|
},
|
||||||
"playnext": {
|
"playnext": {
|
||||||
"searching": "🔍 Suche...",
|
"searching": "🔍 Suche...",
|
||||||
@@ -649,14 +692,14 @@
|
|||||||
"cancelOption": "Abbrechen"
|
"cancelOption": "Abbrechen"
|
||||||
},
|
},
|
||||||
"servers": {
|
"servers": {
|
||||||
"noServers": "_Keine Server gefunden._",
|
"noServers": "_Keine Communities gefunden._",
|
||||||
"title": "🌐 Server ({{count}})",
|
"title": "🌐 Communities ({{count}})",
|
||||||
"pageTitle": "🌐 Server ({{count}}) - Seite {{page}}/{{total}}",
|
"pageTitle": "🌐 Communities ({{count}}) - Seite {{page}}/{{total}}",
|
||||||
"listComplete": "Liste vollständig",
|
"listComplete": "Liste vollständig",
|
||||||
"serversAuthor": "🌐 Netzwerktopologie",
|
"serversAuthor": "🌐 Netzwerktopologie",
|
||||||
"serversTitle": "Verzeichnis verbundener Server",
|
"serversTitle": "Verzeichnis verbundener Communities",
|
||||||
"serversActiveBadge": "{{count}} Server aktiv",
|
"serversActiveBadge": "{{count}} Communities aktiv",
|
||||||
"serversTelemetryFooter": "Echtzeit-Servertelemetrie • Seite {{page}}/{{total}}"
|
"serversTelemetryFooter": "Echtzeit-Communitytelemetrie • Seite {{page}}/{{total}}"
|
||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"unknownSetting": "❌ Unbekannte Einstellung `{{setting}}`.",
|
"unknownSetting": "❌ Unbekannte Einstellung `{{setting}}`.",
|
||||||
@@ -824,7 +867,7 @@
|
|||||||
"categoryMusic": "🎧 Musik-Aktivität",
|
"categoryMusic": "🎧 Musik-Aktivität",
|
||||||
"categoryLastfm": "🎵 Last.fm",
|
"categoryLastfm": "🎵 Last.fm",
|
||||||
"categoryPerformance": "⚡ System & Netzwerk",
|
"categoryPerformance": "⚡ System & Netzwerk",
|
||||||
"servers": "📂 **Server**",
|
"servers": "📂 **Communities**",
|
||||||
"users": "👥 **Benutzer**",
|
"users": "👥 **Benutzer**",
|
||||||
"players": "🎧 **Player**",
|
"players": "🎧 **Player**",
|
||||||
"playersWithPlaying": "{{total}} ({{playing}} aktiv)",
|
"playersWithPlaying": "{{total}} ({{playing}} aktiv)",
|
||||||
@@ -1317,6 +1360,146 @@
|
|||||||
"floodTitle": "Protokollnachrichten verworfen",
|
"floodTitle": "Protokollnachrichten verworfen",
|
||||||
"floodDesc": "⚠️ **{{count}}** zusätzliche Protokollnachricht(en) wurden während einer Flut verworfen, um API-Ratenbegrenzungen zu schützen.",
|
"floodDesc": "⚠️ **{{count}}** zusätzliche Protokollnachricht(en) wurden während einer Flut verworfen, um API-Ratenbegrenzungen zu schützen.",
|
||||||
"floodFooter": "Ratenbegrenzungsschutz • ErrorChannel"
|
"floodFooter": "Ratenbegrenzungsschutz • ErrorChannel"
|
||||||
|
},
|
||||||
|
"statustest": {
|
||||||
|
"author": "Remix · Statuskanal-Diagnose",
|
||||||
|
"disabledAuthor": "Remix Status-Hub",
|
||||||
|
"disabledTitle": "Statuskanal deaktiviert",
|
||||||
|
"disabledDesc": "❌ Der Statuskanal ist derzeit **deaktiviert** oder es fehlt eine `channelId`.\n\nKonfiguriere `statusChannel` in `config.json`:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"DEINE_KANAL_ID\",\n \"mentionRoleId\": \"OPTIONALE_ROLLEN_ID\",\n \"updateIntervalSeconds\": 300\n}\n```",
|
||||||
|
"refreshedTitle": "✅ Live-Karte aktualisiert",
|
||||||
|
"refreshedDesc": "Live-Telemetrie-Update an <#{{channelId}}> gesendet.\nKarten-Nachrichten-ID: `{{messageId}}`",
|
||||||
|
"incidentTitle": "🔴 Test-Vorfall ausgelöst",
|
||||||
|
"incidentDesc": "Vorfallsausfall für **{{target}}** in <#{{channelId}}> veröffentlicht.\nFühre `{{prefix}}statustest resolve {{target}}` aus, um ihn zu beheben.",
|
||||||
|
"resolvedTitle": "✅ Test-Vorfall behoben",
|
||||||
|
"resolvedDesc": "Vorfallsbehebung für **{{target}}** in <#{{channelId}}> veröffentlicht.",
|
||||||
|
"helpTitle": "Statuskanal-Befehle",
|
||||||
|
"helpDesc": "Statuskanal ist **aktiv** in <#{{channelId}}>.\nAktuelle Live-Karte: `{{cardId}}`\n\n**Nutzungsoptionen:**\n• `{{prefix}}statustest refresh` — Live-Status-Embed erzwingen.\n• `{{prefix}}statustest incident <target>` — Test-Ausfall-Embed auslösen.\n• `{{prefix}}statustest resolve <target>` — Ausfall beheben und Ausfallzeit posten.\n\n*Gültige Ziele:* `gateway`, `audioNode`, `database`, `dashboard`, `api`"
|
||||||
|
},
|
||||||
|
"statusChannel": {
|
||||||
|
"liveCardTitle": "Live-Systemstatus",
|
||||||
|
"liveCardAuthor": "Remix · System-Telemetrie & Status",
|
||||||
|
"operationalDesc": "🟢 **Alle Systeme betriebsbereit**\nRemix läuft auf allen Servern reibungslos.",
|
||||||
|
"degradedDesc": "🟡 **Teilausfall**\nEinige unkritische Subsysteme weisen Störungen auf.",
|
||||||
|
"criticalDesc": "🔴 **Schwerer Ausfall festgestellt**\nEin oder mehrere Hauptdienste sind offline.",
|
||||||
|
"gatewayField": "🏓 Gateway-Latenz",
|
||||||
|
"uptimeField": "⏱️ Betriebszeit",
|
||||||
|
"sessionsField": "🎵 Aktive Sitzungen",
|
||||||
|
"ramField": "📟 Arbeitsspeicher (RAM)",
|
||||||
|
"cpuField": "⚙️ CPU-Auslastung",
|
||||||
|
"guildsField": "🏰 Community-Präsenz",
|
||||||
|
"subsystemsField": "🛡️ Subsystem-Status",
|
||||||
|
"incidentAuthor": "🔴 Vorfall festgestellt",
|
||||||
|
"incidentTitle": "🔴 {{name}} ist ausgefallen",
|
||||||
|
"incidentDefaultDesc": "{{name}} weist Störungen auf. Unser Team untersucht den Vorfall.",
|
||||||
|
"resolvedAuthor": "✅ Vorfall behoben",
|
||||||
|
"resolvedTitle": "✅ {{name}} ist wieder online",
|
||||||
|
"resolvedDefaultDesc": "Die Verbindung zu {{name}} wurde vollständig wiederhergestellt und als stabil verifiziert.",
|
||||||
|
"downtimeField": "Ausfallzeit",
|
||||||
|
"startedField": "Begonnen",
|
||||||
|
"resolvedField": "Behoben",
|
||||||
|
"statusField": "Status",
|
||||||
|
"severityField": "Schweregrad",
|
||||||
|
"investigating": "Untersuchung läuft",
|
||||||
|
"stable": "Stabil",
|
||||||
|
"operational": "Betriebsbereit",
|
||||||
|
"outage": "Störungen",
|
||||||
|
"disabled": "Deaktiviert"
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"topAuthor": "Server-Bestenliste",
|
||||||
|
"topTitle": "Meistgespielte Songs ({{timeframe}})",
|
||||||
|
"noData": "Auf diesem Server wurden noch keine Songs gespielt. Starte mit {{prefix}}play <Song>!",
|
||||||
|
"timeframeWeek": "Diese Woche",
|
||||||
|
"timeframeMonth": "Dieser Monat",
|
||||||
|
"timeframeAll": "Gesamte Zeit",
|
||||||
|
"topFooter": "Filtern mit: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all",
|
||||||
|
"plays": "Wiedergaben",
|
||||||
|
"globalAuthor": "Globale Bestenliste • Alle Server",
|
||||||
|
"globalTitle": "Meistgespielte Songs auf allen Servern",
|
||||||
|
"globalFooter": "Filtern mit: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global",
|
||||||
|
"pageFooter": "Seite {{page}}/{{totalPages}} • {{timeframe}}",
|
||||||
|
"serverFallbackNote": "ℹ️ _Noch keine Tracks auf diesem Server gespielt — globale Charts werden angezeigt:_",
|
||||||
|
"timeframeDay": "Letzte 24 Stunden",
|
||||||
|
"timeframeYear": "Dieses Jahr"
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"wrappedAuthor": "Community Music Wrapped",
|
||||||
|
"wrappedTitle": "Musik-Persönlichkeit des Servers",
|
||||||
|
"totalStreamed": "Gesamt gestreamt",
|
||||||
|
"tracksQueued": "Songs in der Warteschlange",
|
||||||
|
"peakHour": "Spitzen-Hörzeit",
|
||||||
|
"topDJ": "Bester Community-DJ",
|
||||||
|
"topSongs": "Top-Songs",
|
||||||
|
"wrappedFooter": "Bereitgestellt von Remix Music • Spiele Musik mit {{prefix}}play",
|
||||||
|
"globalAuthor": "Remix-Netzwerk Wrapped • Alle Server",
|
||||||
|
"globalTitle": "Globale Musik-Persönlichkeit",
|
||||||
|
"activeServers": "Aktive Communities",
|
||||||
|
"globalFooter": "Remix Globales Netzwerk • Tippe {{prefix}}wrapped für deinen Server-Rückblick"
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"authorSelf": "Dein persönlicher Musik-Rückblick",
|
||||||
|
"authorOther": "Persönlicher Musik-Rückblick • {{username}}",
|
||||||
|
"titleSelf": "Deine Server-Höridentität",
|
||||||
|
"titleOther": "Server-Höridentität von {{username}}",
|
||||||
|
"totalStreamed": "Gesamte Streamingzeit",
|
||||||
|
"tracksQueued": "Gespielte Tracks",
|
||||||
|
"peakHour": "Aktivste Hörzeit",
|
||||||
|
"djRank": "Community-DJ-Rang",
|
||||||
|
"djRankValue": "Platz #{{rank}} von {{total}} DJs",
|
||||||
|
"topArtist": "Lieblingskünstler",
|
||||||
|
"topSongs": "Persönliche Top-Songs",
|
||||||
|
"noDataSelf": "Du hast auf diesem Server noch keine Songs abgespielt. Starte mit {{prefix}}play <Song>!",
|
||||||
|
"noDataOther": "{{username}} hat auf diesem Server noch keine Songs abgespielt.",
|
||||||
|
"globalNotice": "🌐 Globale Statistiken • Noch keine Songs auf diesem Server",
|
||||||
|
"footer": "Unterstützt von Remix Music • {{prefix}}top für Server-Charts"
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"notAvailable": "Persönliche Favoriten sind nicht verfügbar (Datenbank getrennt).",
|
||||||
|
"empty": "Du hast noch keine Favoriten gespeichert! Nutze `{{prefix}}fav`, während ein Song läuft, um ihn zu speichern.",
|
||||||
|
"invalidIndex": "Ungültige Titelnummer. Bitte wähle eine Zahl zwischen 1 und {{max}}.",
|
||||||
|
"queuedOne": "Favoritentitel zur Warteschlange hinzugefügt: **[{{title}}]({{url}})**",
|
||||||
|
"queuedAll": "**{{count}} Favoritentitel** zur Warteschlange hinzugefügt!",
|
||||||
|
"removeUsage": "Verwendung: `{{prefix}}fav remove <Nummer|Titel>`",
|
||||||
|
"notFound": "Dieser Titel wurde in deinen Favoriten nicht gefunden.",
|
||||||
|
"removed": "**[{{title}}]({{url}})** aus deinen Favoriten entfernt.",
|
||||||
|
"cleared": "Alle **{{count}} Titel** aus deinen Favoriten gelöscht.",
|
||||||
|
"listTitle": "Favoritentitel von {{user}}",
|
||||||
|
"listFooter": "Seite {{page}}/{{totalPages}} • {{total}} gespeichert • Nutze {{prefix}}fav play, um alle abzuspielen",
|
||||||
|
"limitReached": "Du hast das Limit von {{max}} Favoritentiteln erreicht.",
|
||||||
|
"added": "⭐ **[{{title}}]({{url}})** zu deinen Favoriten hinzugefügt! (Gesamt: {{count}})"
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"notAvailable": "Eigene Playlists sind nicht verfügbar (Datenbank getrennt).",
|
||||||
|
"saveUsage": "Verwendung: `{{prefix}}playlist save <Name> [URL]`",
|
||||||
|
"playUsage": "Verwendung: `{{prefix}}playlist play <Name>`",
|
||||||
|
"showUsage": "Verwendung: `{{prefix}}playlist show <Name> [Seite]`",
|
||||||
|
"addUsage": "Verwendung: `{{prefix}}playlist add <Name> [URL]`",
|
||||||
|
"removeUsage": "Verwendung: `{{prefix}}playlist remove <Name> <Titelnummer>`",
|
||||||
|
"deleteUsage": "Verwendung: `{{prefix}}playlist delete <Name>`",
|
||||||
|
"emptyQueue": "Es wird nichts abgespielt und die Warteschlange ist leer! Starte zuerst Musik mit `{{prefix}}play`.",
|
||||||
|
"limitReached": "Du hast das Limit von {{max}} eigenen Playlists erreicht.",
|
||||||
|
"invalidName": "Ungültiger Playlist-Name. Namen müssen 1–32 Zeichen lang sein und dürfen keine Schrägstriche enthalten.",
|
||||||
|
"saveFailed": "Playlist konnte nicht gespeichert werden. Bitte versuche es erneut.",
|
||||||
|
"saved": "💾 **{{count}} Titel** in Playlist **{{name}}** gespeichert! Spiele sie jederzeit mit `{{prefix}}playlist play {{name}}` ab.",
|
||||||
|
"notFound": "Playlist **{{name}}** wurde nicht gefunden. Nutze `{{prefix}}playlist list`, um deine Playlists zu sehen.",
|
||||||
|
"playlistEmpty": "Playlist **{{name}}** ist leer.",
|
||||||
|
"queued": "▶️ Playlist **{{name}}** (**{{count}} Titel**) in die Warteschlange geladen!",
|
||||||
|
"listTitle": "Eigene Playlists von {{user}}",
|
||||||
|
"noPlaylists": "Du hast noch keine Playlists gespeichert! Nutze `{{prefix}}playlist save <Name>`, um die Warteschlange zu speichern.",
|
||||||
|
"listFooter": "Seite {{page}}/{{totalPages}} • {{total}}/{{max}} Playlists • Abspielen mit: {{prefix}}playlist play <Name>",
|
||||||
|
"showTitle": "Playlist: {{name}}",
|
||||||
|
"showFooter": "Seite {{page}}/{{totalPages}} • {{total}} Titel in {{name}} • Abspielen mit: {{prefix}}playlist play {{name}}",
|
||||||
|
"nothingPlaying": "Aktuell wird kein Song abgespielt, der hinzugefügt werden könnte.",
|
||||||
|
"playlistFull": "Diese Playlist hat das Maximum von {{max}} Titeln erreicht.",
|
||||||
|
"addFailed": "Titel konnte nicht zur Playlist hinzugefügt werden.",
|
||||||
|
"trackAdded": "**{{title}}** zur Playlist **{{name}}** hinzugefügt! (Gesamt: {{count}} Titel)",
|
||||||
|
"invalidIndex": "Ungültiger Titel-Index.",
|
||||||
|
"trackRemoved": "**{{title}}** aus Playlist **{{name}}** entfernt! ({{count}} Titel verbleibend)",
|
||||||
|
"deleted": "🗑️ Playlist **{{name}}** gelöscht.",
|
||||||
|
"resolving": "🔎 Lade Titel von **{{source}}**...",
|
||||||
|
"savedFromSource": "💾 **{{count}} Titel** von **{{source}}** in Playlist **{{name}}** gespeichert! Spiele sie jederzeit mit `{{prefix}}playlist play {{name}}`.",
|
||||||
|
"noTracksFromSource": "Unter diesem Link konnten keine abspielbaren Titel gefunden oder geladen werden.",
|
||||||
|
"tracksAdded": "**{{addedCount}} Titel** zu Playlist **{{name}}** hinzugefügt! (Insgesamt: {{count}} Titel)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+195
-12
@@ -35,7 +35,20 @@
|
|||||||
"permission": "Permission `{{$permission}}`",
|
"permission": "Permission `{{$permission}}`",
|
||||||
"optionCount": "{{$count}} option(s)",
|
"optionCount": "{{$count}} option(s)",
|
||||||
"commandInspectorAuthor": "Command Help • {{prefix}}{{name}}",
|
"commandInspectorAuthor": "Command Help • {{prefix}}{{name}}",
|
||||||
"commandInspectorFooter": "Type {{prefix}}help for full command list • Category: {{category}}"
|
"commandInspectorFooter": "Type {{prefix}}help for full command list • Category: {{category}}",
|
||||||
|
"tabHome": "Home",
|
||||||
|
"tabHomeHeader": "Home Page",
|
||||||
|
"tabMusic": "Music",
|
||||||
|
"tabMusicHeader": "Music Commands",
|
||||||
|
"tabUtil": "Utilities",
|
||||||
|
"tabUtilHeader": "Utility Commands",
|
||||||
|
"tabSupport": "Support",
|
||||||
|
"tabSupportHeader": "Support Info",
|
||||||
|
"homeContent": "**Remix** is a high-fidelity 24/7 music bot supporting YouTube, Spotify, SoundCloud, Deezer, and more.\n\n**✨ Core Highlights**\n• **48kHz Hi-Fi Audio** — Crystal-clear audio stream pipeline\n• **30+ Audio Filters** — Bassboost, 8D, Nightcore, Vaporwave, Equalizer\n• **Dynamic Normalizer** — EBU R128 loudness leveling across music sources\n• **24/7 Web Radio** — Over 30,000 global live radio stations\n\n**📂 Command Categories**\n🏠 • **Home** — Quick bot overview & status\n🎵 • **Music** — Playback, queue, search, filters ($prefixplay, $prefixskip, $prefixqueue)\n🔧 • **Utility** — Settings, 24/7 voice, ping, vote ($prefixsettings, $prefixping)\nℹ️ • **Support** — Community server & assistance\n\n💡 **Tip:** Click the tab emojis below to switch sections, or use $prefixhelp <command> for detailed info.",
|
||||||
|
"supportContent": "Need help, want to report a bug, or suggest new features?\n\n💬 **[Join Remix Support Server](https://fluxer.gg/remix)**\n\n**Team & Maintainers:**\n• **Fantic** — Community Manager\n• **Shadow** — Lead Developer\n• **NoLogicAlan** — Lead Developer\n\nYou can also use $prefixinvite to add Remix to your server.",
|
||||||
|
"noCommands": "_No commands available._",
|
||||||
|
"learnMore": "\nTo learn more about a command, run $prefixhelp <command name>!",
|
||||||
|
"subpageTip": "\n\n**Tip:** Use ⬅️ ➡️ to scroll between pages."
|
||||||
},
|
},
|
||||||
"invalidFlag": "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`",
|
"invalidFlag": "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.",
|
||||||
@@ -70,7 +83,7 @@
|
|||||||
"remove": "Remove a specific song from the queue.",
|
"remove": "Remove a specific song from the queue.",
|
||||||
"resume": "Resume the playback in your voice channel.",
|
"resume": "Resume the playback in your voice channel.",
|
||||||
"search": "Display search results for a query and pick one to play.\nSupports all providers — use inline prefix e.g. `sp: song` or `-p dz`.",
|
"search": "Display search results for a query and pick one to play.\nSupports all providers — use inline prefix e.g. `sp: song` or `-p dz`.",
|
||||||
"servers": "Fetch a list of servers the bot is in.",
|
"servers": "Fetch a list of communities the bot is in.",
|
||||||
"settings": "Change/Get settings in the current server.",
|
"settings": "Change/Get settings in the current server.",
|
||||||
"shuffle": "Re-orders the queue randomly.",
|
"shuffle": "Re-orders the queue randomly.",
|
||||||
"skip": "Skip the current playing song.",
|
"skip": "Skip the current playing song.",
|
||||||
@@ -91,7 +104,13 @@
|
|||||||
"pitch": "Adjust the audio pitch of the current track (0.5× to 2.0×).",
|
"pitch": "Adjust the audio pitch of the current track (0.5× to 2.0×).",
|
||||||
"previous": "Play the previous track from playback history.",
|
"previous": "Play the previous track from playback history.",
|
||||||
"replay": "Restart the current song from the beginning.",
|
"replay": "Restart the current song from the beginning.",
|
||||||
"skipto": "Skip directly to a specific track in the queue."
|
"skipto": "Skip directly to a specific track in the queue.",
|
||||||
|
"statustest": "Test public status channel updates, live cards, and incidents.",
|
||||||
|
"top": "View the most played songs and top artists in this server.",
|
||||||
|
"wrapped": "Generate a community music recap and listening statistics.",
|
||||||
|
"mywrapped": "View your personal music listening recap, top tracks, and server DJ rank.",
|
||||||
|
"fav": "Bookmark your favorite tracks and load them into voice channels.",
|
||||||
|
"playlist": "Save the current queue or manage your personal custom playlists."
|
||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
"debug": {
|
"debug": {
|
||||||
@@ -190,6 +209,22 @@
|
|||||||
},
|
},
|
||||||
"skipto": {
|
"skipto": {
|
||||||
"position": "The track number in the queue to jump to."
|
"position": "The track number in the queue to jump to."
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"timeframe": "Filter timeframe: 24h, week, month, year, all, or global, or page number.",
|
||||||
|
"page": "Page number to jump to."
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"scope": "Recap scope: server or global."
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"user": "The user whose listening recap you want to view."
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"args": "Subcommand or track: play, list, remove, clear, or leave empty to toggle favorite."
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"args": "Subcommand and arguments: save, play, list, show, add, remove, delete."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pagination": {
|
"pagination": {
|
||||||
@@ -359,7 +394,10 @@
|
|||||||
"autoLeaveFooter": "Keep bot in voice 24/7 with {{prefix}}247",
|
"autoLeaveFooter": "Keep bot in voice 24/7 with {{prefix}}247",
|
||||||
"joinFailedAuthor": "🔊 Voice Connection Error",
|
"joinFailedAuthor": "🔊 Voice Connection Error",
|
||||||
"joinFailedTitle": "Failed to Connect",
|
"joinFailedTitle": "Failed to Connect",
|
||||||
"joinFailedFooter": "Check voice channel permissions and retry with {{prefix}}join"
|
"joinFailedFooter": "Check voice channel permissions and retry with {{prefix}}join",
|
||||||
|
"inactivityWarningTitle": "Leaving Voice Soon",
|
||||||
|
"inactivityWarningDesc": "Voice session is currently inactive. Disconnecting from <#{{channel}}> in **{{minutes}} minute(s)**.\n\nUse {{prefix}}247 to keep me in voice 24/7!",
|
||||||
|
"inactivityWarningFooter": "Play a song with {{prefix}}play to resume"
|
||||||
},
|
},
|
||||||
"leave": {
|
"leave": {
|
||||||
"noVoiceChannel": "⚠️ I can't find you in a voice channel. Please join one, or if you're already in one, make sure I have **View Channel** and **Connect** permissions. You can also specify a channel: `{{prefix}}leave <#channel>`",
|
"noVoiceChannel": "⚠️ I can't find you in a voice channel. Please join one, or if you're already in one, make sure I have **View Channel** and **Connect** permissions. You can also specify a channel: `{{prefix}}leave <#channel>`",
|
||||||
@@ -755,7 +793,12 @@
|
|||||||
"loadingDirectStream": "🔎 Loading direct stream...",
|
"loadingDirectStream": "🔎 Loading direct stream...",
|
||||||
"resolvingLavalinkStream": "🔎 Resolving stream via Lavalink...",
|
"resolvingLavalinkStream": "🔎 Resolving stream via Lavalink...",
|
||||||
"lastfmPlaybackAuthor": "🎵 Last.fm Playback",
|
"lastfmPlaybackAuthor": "🎵 Last.fm Playback",
|
||||||
"lastfmSearchAuthor": "🔎 Last.fm Search"
|
"lastfmSearchAuthor": "🔎 Last.fm Search",
|
||||||
|
"loadingAttachmentStream": "Loading Fluxer media attachment...",
|
||||||
|
"sourceAttachment": "Fluxer Attachment",
|
||||||
|
"noQueryTitle": "Song or Attachment Required",
|
||||||
|
"noQueryDesc": "Please provide a search query, a direct media link, or upload an audio/video file with this command.",
|
||||||
|
"noQueryFooter": "Music Player • Direct Attachment Support"
|
||||||
},
|
},
|
||||||
"playnext": {
|
"playnext": {
|
||||||
"searching": "🔍 Searching...",
|
"searching": "🔍 Searching...",
|
||||||
@@ -864,14 +907,14 @@
|
|||||||
"cancelOption": "Cancel"
|
"cancelOption": "Cancel"
|
||||||
},
|
},
|
||||||
"servers": {
|
"servers": {
|
||||||
"noServers": "_No servers found._",
|
"noServers": "_No communities found._",
|
||||||
"title": "🌐 Servers ({{count}})",
|
"title": "🌐 Communities ({{count}})",
|
||||||
"pageTitle": "🌐 Servers ({{count}}) - Page {{page}}/{{total}}",
|
"pageTitle": "🌐 Communities ({{count}}) - Page {{page}}/{{total}}",
|
||||||
"listComplete": "List complete",
|
"listComplete": "List complete",
|
||||||
"serversAuthor": "🌐 Network Topology",
|
"serversAuthor": "🌐 Network Topology",
|
||||||
"serversTitle": "Connected Guild Directory",
|
"serversTitle": "Connected Community Directory",
|
||||||
"serversActiveBadge": "{{count}} Guilds Active",
|
"serversActiveBadge": "{{count}} Communities Active",
|
||||||
"serversTelemetryFooter": "Real-time guild telemetry • Page {{page}}/{{total}}"
|
"serversTelemetryFooter": "Real-time community telemetry • Page {{page}}/{{total}}"
|
||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"unknownSetting": "❌ Unknown setting `{{setting}}`.",
|
"unknownSetting": "❌ Unknown setting `{{setting}}`.",
|
||||||
@@ -1039,7 +1082,7 @@
|
|||||||
"categoryMusic": "🎧 Music Activity",
|
"categoryMusic": "🎧 Music Activity",
|
||||||
"categoryLastfm": "🎵 Last.fm",
|
"categoryLastfm": "🎵 Last.fm",
|
||||||
"categoryPerformance": "⚡ System & Network",
|
"categoryPerformance": "⚡ System & Network",
|
||||||
"servers": "📂 **Servers**",
|
"servers": "📂 **Communities**",
|
||||||
"users": "👥 **Users**",
|
"users": "👥 **Users**",
|
||||||
"players": "🎧 **Players**",
|
"players": "🎧 **Players**",
|
||||||
"playersWithPlaying": "{{total}} ({{playing}} playing)",
|
"playersWithPlaying": "{{total}} ({{playing}} playing)",
|
||||||
@@ -1317,6 +1360,146 @@
|
|||||||
"floodTitle": "Log Messages Dropped",
|
"floodTitle": "Log Messages Dropped",
|
||||||
"floodDesc": "⚠️ **{{count}}** additional log message(s) were dropped during a flood to protect API rate limits.",
|
"floodDesc": "⚠️ **{{count}}** additional log message(s) were dropped during a flood to protect API rate limits.",
|
||||||
"floodFooter": "Rate Limit Guard • ErrorChannel"
|
"floodFooter": "Rate Limit Guard • ErrorChannel"
|
||||||
|
},
|
||||||
|
"statustest": {
|
||||||
|
"author": "Remix · Status Channel Diagnostics",
|
||||||
|
"disabledAuthor": "Remix Status Hub",
|
||||||
|
"disabledTitle": "Status Channel Disabled",
|
||||||
|
"disabledDesc": "❌ The status channel is currently **disabled** or missing a `channelId`.\n\nConfigure `statusChannel` in `config.json`:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"YOUR_CHANNEL_ID\",\n \"mentionRoleId\": \"OPTIONAL_ROLE_ID\",\n \"updateIntervalSeconds\": 300\n}\n```",
|
||||||
|
"refreshedTitle": "✅ Live Card Refreshed",
|
||||||
|
"refreshedDesc": "Dispatched live telemetry update to <#{{channelId}}>.\nCard Message ID: `{{messageId}}`",
|
||||||
|
"incidentTitle": "🔴 Test Incident Triggered",
|
||||||
|
"incidentDesc": "Published incident outage for **{{target}}** in <#{{channelId}}>.\nRun `{{prefix}}statustest resolve {{target}}` to resolve it.",
|
||||||
|
"resolvedTitle": "✅ Test Incident Resolved",
|
||||||
|
"resolvedDesc": "Published incident resolution for **{{target}}** in <#{{channelId}}>.",
|
||||||
|
"helpTitle": "Status Channel Commands",
|
||||||
|
"helpDesc": "Status channel is **active** in <#{{channelId}}>.\nCurrent Live Card: `{{cardId}}`\n\n**Usage Options:**\n• `{{prefix}}statustest refresh` — Force-update the live status embed.\n• `{{prefix}}statustest incident <target>` — Trigger test outage embed.\n• `{{prefix}}statustest resolve <target>` — Resolve outage and post downtime.\n\n*Valid targets:* `gateway`, `audioNode`, `database`, `dashboard`, `api`"
|
||||||
|
},
|
||||||
|
"statusChannel": {
|
||||||
|
"liveCardTitle": "Live System Status",
|
||||||
|
"liveCardAuthor": "Remix · System Telemetry & Status",
|
||||||
|
"operationalDesc": "🟢 **All Systems Operational**\nRemix is running smoothly across all guilds.",
|
||||||
|
"degradedDesc": "🟡 **Partial Outage**\nSome non-critical subsystems are experiencing disruptions.",
|
||||||
|
"criticalDesc": "🔴 **Major Outage Detected**\nOne or more primary services are currently offline.",
|
||||||
|
"gatewayField": "🏓 Gateway Latency",
|
||||||
|
"uptimeField": "⏱️ Uptime",
|
||||||
|
"sessionsField": "🎵 Active Sessions",
|
||||||
|
"ramField": "📟 Memory (RAM)",
|
||||||
|
"cpuField": "⚙️ CPU Utilization",
|
||||||
|
"guildsField": "🏰 Community Footprint",
|
||||||
|
"subsystemsField": "🛡️ Subsystem Health",
|
||||||
|
"incidentAuthor": "🔴 Incident Detected",
|
||||||
|
"incidentTitle": "🔴 {{name}} is down",
|
||||||
|
"incidentDefaultDesc": "{{name}} is experiencing disruptions. Our team is actively investigating the incident.",
|
||||||
|
"resolvedAuthor": "✅ Incident Resolved",
|
||||||
|
"resolvedTitle": "✅ {{name}} is back online",
|
||||||
|
"resolvedDefaultDesc": "{{name}} connectivity has been fully restored and verified stable.",
|
||||||
|
"downtimeField": "Downtime",
|
||||||
|
"startedField": "Started",
|
||||||
|
"resolvedField": "Resolved",
|
||||||
|
"statusField": "Status",
|
||||||
|
"severityField": "Severity",
|
||||||
|
"investigating": "Investigating",
|
||||||
|
"stable": "Stable",
|
||||||
|
"operational": "Operational",
|
||||||
|
"outage": "Disruptions",
|
||||||
|
"disabled": "Disabled"
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"topAuthor": "Server Leaderboard",
|
||||||
|
"topTitle": "Top Played Tracks ({{timeframe}})",
|
||||||
|
"noData": "No tracks have been played in this server yet. Start playing with {{prefix}}play <song>!",
|
||||||
|
"timeframeWeek": "This Week",
|
||||||
|
"timeframeMonth": "This Month",
|
||||||
|
"timeframeAll": "All Time",
|
||||||
|
"topFooter": "Filter with: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all",
|
||||||
|
"plays": "plays",
|
||||||
|
"globalAuthor": "Global Leaderboard • All Servers",
|
||||||
|
"globalTitle": "Top Played Tracks Across All Servers",
|
||||||
|
"globalFooter": "Filter with: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global",
|
||||||
|
"pageFooter": "Page {{page}}/{{totalPages}} • {{timeframe}}",
|
||||||
|
"serverFallbackNote": "ℹ️ _No tracks played in this server yet — showing Global Network charts:_",
|
||||||
|
"timeframeDay": "Past 24 Hours",
|
||||||
|
"timeframeYear": "This Year"
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"wrappedAuthor": "Community Music Wrapped",
|
||||||
|
"wrappedTitle": "Server Music Personality",
|
||||||
|
"totalStreamed": "Total Streamed",
|
||||||
|
"tracksQueued": "Tracks Queued",
|
||||||
|
"peakHour": "Peak Listening Hour",
|
||||||
|
"topDJ": "Top Community DJ",
|
||||||
|
"topSongs": "Top Songs",
|
||||||
|
"wrappedFooter": "Powered by Remix Music • Play music with {{prefix}}play",
|
||||||
|
"globalAuthor": "Remix Network Wrapped • All Servers",
|
||||||
|
"globalTitle": "Global Music Personality",
|
||||||
|
"activeServers": "Active Communities",
|
||||||
|
"globalFooter": "Remix Global Network • Type {{prefix}}wrapped for your server's recap"
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"authorSelf": "Your Personal Music Recap",
|
||||||
|
"authorOther": "Personal Music Recap • {{username}}",
|
||||||
|
"titleSelf": "Your Server Listening Identity",
|
||||||
|
"titleOther": "{{username}}'s Server Listening Identity",
|
||||||
|
"totalStreamed": "Total Streamed",
|
||||||
|
"tracksQueued": "Tracks Queued",
|
||||||
|
"peakHour": "Peak Listening Time",
|
||||||
|
"djRank": "Community DJ Rank",
|
||||||
|
"djRankValue": "#{{rank}} of {{total}} DJs",
|
||||||
|
"topArtist": "Favorite Artist",
|
||||||
|
"topSongs": "Personal Top Songs",
|
||||||
|
"noDataSelf": "You haven't queued any songs in this server yet. Start playing with {{prefix}}play <song>!",
|
||||||
|
"noDataOther": "{{username}} hasn't queued any songs in this server yet.",
|
||||||
|
"globalNotice": "🌐 Global Stats • No songs queued on this server yet",
|
||||||
|
"footer": "Powered by Remix Music • {{prefix}}top for server charts"
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"notAvailable": "Personal favorites are not available (database disconnected).",
|
||||||
|
"empty": "You have no saved favorites yet! Use `{{prefix}}fav` while a song is playing to bookmark it.",
|
||||||
|
"invalidIndex": "Invalid track number. Please choose a number between 1 and {{max}}.",
|
||||||
|
"queuedOne": "Added favorite track to the queue: **[{{title}}]({{url}})**",
|
||||||
|
"queuedAll": "Added **{{count}} favorite track(s)** to the queue!",
|
||||||
|
"removeUsage": "Usage: `{{prefix}}fav remove <number|title>`",
|
||||||
|
"notFound": "Could not find that track in your favorites.",
|
||||||
|
"removed": "Removed **[{{title}}]({{url}})** from your favorites.",
|
||||||
|
"cleared": "Cleared all **{{count}} track(s)** from your favorites.",
|
||||||
|
"listTitle": "{{user}}'s Favorite Tracks",
|
||||||
|
"listFooter": "Page {{page}}/{{totalPages}} • {{total}} saved • Use {{prefix}}fav play to queue all",
|
||||||
|
"limitReached": "You have reached the maximum limit of {{max}} favorite tracks.",
|
||||||
|
"added": "⭐ Added **[{{title}}]({{url}})** to your favorites! (Total: {{count}})"
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"notAvailable": "Personal playlists are not available (database disconnected).",
|
||||||
|
"saveUsage": "Usage: `{{prefix}}playlist save <name> [url]`",
|
||||||
|
"playUsage": "Usage: `{{prefix}}playlist play <name>`",
|
||||||
|
"showUsage": "Usage: `{{prefix}}playlist show <name> [page]`",
|
||||||
|
"addUsage": "Usage: `{{prefix}}playlist add <name> [url]`",
|
||||||
|
"removeUsage": "Usage: `{{prefix}}playlist remove <name> <track_number>`",
|
||||||
|
"deleteUsage": "Usage: `{{prefix}}playlist delete <name>`",
|
||||||
|
"emptyQueue": "There is nothing playing or in the queue to save! Start playing music first with `{{prefix}}play`.",
|
||||||
|
"limitReached": "You have reached the limit of {{max}} custom playlists.",
|
||||||
|
"invalidName": "Invalid playlist name. Names must be 1–32 characters and cannot contain slashes.",
|
||||||
|
"saveFailed": "Failed to save playlist. Please try again.",
|
||||||
|
"saved": "💾 Saved **{{count}} track(s)** to playlist **{{name}}**! Play it anytime with `{{prefix}}playlist play {{name}}`.",
|
||||||
|
"notFound": "Playlist **{{name}}** was not found. Use `{{prefix}}playlist list` to see your playlists.",
|
||||||
|
"playlistEmpty": "Playlist **{{name}}** is empty.",
|
||||||
|
"queued": "▶️ Loaded playlist **{{name}}** (**{{count}} tracks**) into the queue!",
|
||||||
|
"listTitle": "{{user}}'s Custom Playlists",
|
||||||
|
"noPlaylists": "You have no saved playlists yet! Use `{{prefix}}playlist save <name>` to save your current queue.",
|
||||||
|
"listFooter": "Page {{page}}/{{totalPages}} • {{total}}/{{max}} playlists • Play with {{prefix}}playlist play <name>",
|
||||||
|
"showTitle": "Playlist: {{name}}",
|
||||||
|
"showFooter": "Page {{page}}/{{totalPages}} • {{total}} tracks in {{name}} • Play with {{prefix}}playlist play {{name}}",
|
||||||
|
"nothingPlaying": "There is no track currently playing to add.",
|
||||||
|
"playlistFull": "This playlist has reached the maximum cap of {{max}} tracks.",
|
||||||
|
"addFailed": "Failed to add track to playlist.",
|
||||||
|
"trackAdded": "Added **{{title}}** to playlist **{{name}}**! (Total: {{count}} tracks)",
|
||||||
|
"invalidIndex": "Invalid track index.",
|
||||||
|
"trackRemoved": "Removed **{{title}}** from playlist **{{name}}**! ({{count}} tracks remaining)",
|
||||||
|
"deleted": "🗑️ Deleted playlist **{{name}}**.",
|
||||||
|
"resolving": "🔎 Resolving tracks from **{{source}}**...",
|
||||||
|
"savedFromSource": "💾 Saved **{{count}} track(s)** from **{{source}}** to playlist **{{name}}**! Play it anytime with `{{prefix}}playlist play {{name}}`.",
|
||||||
|
"noTracksFromSource": "Could not find or load any playable tracks from that link.",
|
||||||
|
"tracksAdded": "Added **{{addedCount}} track(s)** to playlist **{{name}}**! (Total: {{count}} tracks)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+194
-11
@@ -35,7 +35,20 @@
|
|||||||
"permission": "Permissão `{{$permission}}`",
|
"permission": "Permissão `{{$permission}}`",
|
||||||
"optionCount": "{{$count}} opção(ões)",
|
"optionCount": "{{$count}} opção(ões)",
|
||||||
"commandInspectorAuthor": "Ajuda do Comando • {{prefix}}{{name}}",
|
"commandInspectorAuthor": "Ajuda do Comando • {{prefix}}{{name}}",
|
||||||
"commandInspectorFooter": "Digite {{prefix}}help para ver todos os comandos • Categoria: {{category}}"
|
"commandInspectorFooter": "Digite {{prefix}}help para ver todos os comandos • Categoria: {{category}}",
|
||||||
|
"tabHome": "Início",
|
||||||
|
"tabHomeHeader": "Página Inicial",
|
||||||
|
"tabMusic": "Música",
|
||||||
|
"tabMusicHeader": "Comandos de Música",
|
||||||
|
"tabUtil": "Utilidades",
|
||||||
|
"tabUtilHeader": "Comandos de Utilidade",
|
||||||
|
"tabSupport": "Suporte",
|
||||||
|
"tabSupportHeader": "Informações de Suporte",
|
||||||
|
"homeContent": "**Remix** é um bot de música 24/7 de alta fidelidade com suporte para YouTube, Spotify, SoundCloud, Deezer e muito mais.\n\n**✨ Principais Recursos**\n• **Áudio Hi-Fi de 48kHz** — Pipeline de transmissão de áudio cristalino\n• **30+ Filtros de Áudio** — Bassboost, 8D, Nightcore, Vaporwave, Equalizador\n• **Normalização Dinâmica** — Nivelamento de volume EBU R128 entre fontes de música\n• **Rádio Web 24/7** — Mais de 30.000 estações de rádio ao vivo em todo o mundo\n\n**📂 Categorias de Comandos**\n🏠 • **Início** — Visão geral e status do bot\n🎵 • **Música** — Reprodução, fila, busca, filtros ($prefixplay, $prefixskip, $prefixqueue)\n🔧 • **Utilidades** — Configurações, voz 24/7, ping, voto ($prefixsettings, $prefixping)\nℹ️ • **Suporte** — Servidor comunitário e assistência\n\n💡 **Dica:** Clique nos emojis das abas abaixo para alternar as seções, ou use $prefixhelp <comando> para detalhes.",
|
||||||
|
"supportContent": "Precisa de ajuda, deseja relatar um bug ou sugerir novos recursos?\n\n💬 **[Entrar no Servidor de Suporte do Remix](https://fluxer.gg/remix)**\n\n**Equipe e Desenvolvedores:**\n• **Fantic** — Gerente de Comunidade\n• **Shadow** — Desenvolvedor Principal\n• **NoLogicAlan** — Desenvolvedor Principal\n\nVocê também pode usar $prefixinvite para adicionar o Remix ao seu servidor.",
|
||||||
|
"noCommands": "_Nenhum comando disponível._",
|
||||||
|
"learnMore": "\nPara saber mais sobre um comando, execute $prefixhelp <nome do comando>!",
|
||||||
|
"subpageTip": "\n\n**Dica:** Use ⬅️ ➡️ para navegar entre as páginas."
|
||||||
},
|
},
|
||||||
"invalidFlag": "Flag inválida `$invalidFlag`. Não corresponde a nenhuma opção deste comando.\n`$previousCmd $invalidFlag`",
|
"invalidFlag": "Flag inválida `$invalidFlag`. Não corresponde a nenhuma opção deste comando.\n`$previousCmd $invalidFlag`",
|
||||||
"page": {
|
"page": {
|
||||||
@@ -69,7 +82,7 @@
|
|||||||
"remove": "Remova uma música específica da fila.",
|
"remove": "Remova uma música específica da fila.",
|
||||||
"resume": "Retome a reprodução no seu canal de voz.",
|
"resume": "Retome a reprodução no seu canal de voz.",
|
||||||
"search": "Exiba resultados de busca para uma consulta e escolha uma para tocar.\nSuporta todos os provedores — use prefixo inline como `sp: música` ou `-p dz`.",
|
"search": "Exiba resultados de busca para uma consulta e escolha uma para tocar.\nSuporta todos os provedores — use prefixo inline como `sp: música` ou `-p dz`.",
|
||||||
"servers": "Veja a lista de servidores onde o bot está.",
|
"servers": "Veja a lista de comunidades onde o bot está.",
|
||||||
"settings": "Altere/veja configurações no servidor atual.",
|
"settings": "Altere/veja configurações no servidor atual.",
|
||||||
"shuffle": "Embaralhe a fila aleatoriamente.",
|
"shuffle": "Embaralhe a fila aleatoriamente.",
|
||||||
"skip": "Pule a música que está tocando atualmente.",
|
"skip": "Pule a música que está tocando atualmente.",
|
||||||
@@ -91,7 +104,13 @@
|
|||||||
"pitch": "Ajustar o tom (pitch) do áudio da faixa atual (0.5× a 2.0×).",
|
"pitch": "Ajustar o tom (pitch) do áudio da faixa atual (0.5× a 2.0×).",
|
||||||
"previous": "Tocar a faixa anterior do histórico de reprodução.",
|
"previous": "Tocar a faixa anterior do histórico de reprodução.",
|
||||||
"replay": "Reiniciar a música atual do início.",
|
"replay": "Reiniciar a música atual do início.",
|
||||||
"skipto": "Pular diretamente para uma faixa específica na fila."
|
"skipto": "Pular diretamente para uma faixa específica na fila.",
|
||||||
|
"statustest": "Testar atualizações do canal de status público, cartões ao vivo e incidentes.",
|
||||||
|
"top": "Veja as músicas e os artistas mais tocados neste servidor.",
|
||||||
|
"wrapped": "Gere uma retrospectiva musical e estatísticas da comunidade.",
|
||||||
|
"mywrapped": "Veja sua retrospectiva musical pessoal, melhores faixas e classificação de DJ no servidor.",
|
||||||
|
"fav": "Salve suas músicas favoritas e reproduza-as em canais de voz.",
|
||||||
|
"playlist": "Salve a fila atual ou gerencie suas playlists personalizadas."
|
||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
"debug": {
|
"debug": {
|
||||||
@@ -190,6 +209,22 @@
|
|||||||
},
|
},
|
||||||
"skipto": {
|
"skipto": {
|
||||||
"position": "O número da faixa na fila para onde pular."
|
"position": "O número da faixa na fila para onde pular."
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"timeframe": "Filtrar período: 24h, week, month, year, all ou global, ou número da página.",
|
||||||
|
"page": "Número da página para pular."
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"scope": "Escopo da retrospectiva: server ou global."
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"user": "O usuário cuja retrospectiva musical você deseja ver."
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"args": "Subcomando ou faixa: play, list, remove, clear, ou deixe vazio para alternar."
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"args": "Subcomando e argumentos: save, play, list, show, add, remove, delete."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pagination": {
|
"pagination": {
|
||||||
@@ -356,7 +391,10 @@
|
|||||||
"autoLeaveFooter": "Mantenha o bot no canal de voz 24/7 com {{prefix}}247",
|
"autoLeaveFooter": "Mantenha o bot no canal de voz 24/7 com {{prefix}}247",
|
||||||
"joinFailedAuthor": "🔊 Erro de Conexão de Voz",
|
"joinFailedAuthor": "🔊 Erro de Conexão de Voz",
|
||||||
"joinFailedTitle": "Falha ao Conectar",
|
"joinFailedTitle": "Falha ao Conectar",
|
||||||
"joinFailedFooter": "Verifique as permissões do canal de voz e tente novamente com {{prefix}}join"
|
"joinFailedFooter": "Verifique as permissões do canal de voz e tente novamente com {{prefix}}join",
|
||||||
|
"inactivityWarningTitle": "Saindo do canal de voz em breve",
|
||||||
|
"inactivityWarningDesc": "A sessão de voz está inativa. Desconectando de <#{{channel}}> em **{{minutes}} minuto(s)**.\n\nUse {{prefix}}247 para me manter no canal 24/7!",
|
||||||
|
"inactivityWarningFooter": "Toque uma música com {{prefix}}play para retomar"
|
||||||
},
|
},
|
||||||
"leave": {
|
"leave": {
|
||||||
"noVoiceChannel": "⚠️ Por favor, entre em um canal de voz primeiro ou especifique um: `{{prefix}}leave <#channel>`",
|
"noVoiceChannel": "⚠️ Por favor, entre em um canal de voz primeiro ou especifique um: `{{prefix}}leave <#channel>`",
|
||||||
@@ -540,7 +578,12 @@
|
|||||||
"loadingDirectStream": "🔎 Carregando transmissão direta...",
|
"loadingDirectStream": "🔎 Carregando transmissão direta...",
|
||||||
"resolvingLavalinkStream": "🔎 Resolvendo fluxo via Lavalink...",
|
"resolvingLavalinkStream": "🔎 Resolvendo fluxo via Lavalink...",
|
||||||
"lastfmPlaybackAuthor": "🎵 Reprodução do Last.fm",
|
"lastfmPlaybackAuthor": "🎵 Reprodução do Last.fm",
|
||||||
"lastfmSearchAuthor": "🔎 Pesquisa no Last.fm"
|
"lastfmSearchAuthor": "🔎 Pesquisa no Last.fm",
|
||||||
|
"loadingAttachmentStream": "Carregando anexo de mídia do Fluxer...",
|
||||||
|
"sourceAttachment": "Anexo do Fluxer",
|
||||||
|
"noQueryTitle": "Música ou Anexo Obrigatório",
|
||||||
|
"noQueryDesc": "Por favor, forneça um termo de pesquisa, um link direto de mídia ou envie um arquivo de áudio/vídeo com este comando.",
|
||||||
|
"noQueryFooter": "Reprodutor de Música • Suporte a Anexos Diretos"
|
||||||
},
|
},
|
||||||
"playnext": {
|
"playnext": {
|
||||||
"searching": "🔍 Buscando...",
|
"searching": "🔍 Buscando...",
|
||||||
@@ -649,13 +692,13 @@
|
|||||||
"cancelOption": "Cancelar"
|
"cancelOption": "Cancelar"
|
||||||
},
|
},
|
||||||
"servers": {
|
"servers": {
|
||||||
"noServers": "_Nenhum servidor encontrado._",
|
"noServers": "_Nenhuma comunidade encontrada._",
|
||||||
"title": "🌐 Servidores ({{count}})",
|
"title": "🌐 Comunidades ({{count}})",
|
||||||
"pageTitle": "🌐 Servidores ({{count}}) - Página {{page}}/{{total}}",
|
"pageTitle": "🌐 Comunidades ({{count}}) - Página {{page}}/{{total}}",
|
||||||
"listComplete": "Lista completa",
|
"listComplete": "Lista completa",
|
||||||
"serversAuthor": "🌐 Topologia de Rede",
|
"serversAuthor": "🌐 Topologia de Rede",
|
||||||
"serversTitle": "Diretório de Servidores Conectados",
|
"serversTitle": "Diretório de Comunidades Conectadas",
|
||||||
"serversActiveBadge": "{{count}} Servidores Ativos",
|
"serversActiveBadge": "{{count}} Comunidades Ativas",
|
||||||
"serversTelemetryFooter": "Telemetria em tempo real • Página {{page}}/{{total}}"
|
"serversTelemetryFooter": "Telemetria em tempo real • Página {{page}}/{{total}}"
|
||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
@@ -824,7 +867,7 @@
|
|||||||
"categoryMusic": "🎧 Atividade Musical",
|
"categoryMusic": "🎧 Atividade Musical",
|
||||||
"categoryLastfm": "🎵 Last.fm",
|
"categoryLastfm": "🎵 Last.fm",
|
||||||
"categoryPerformance": "⚡ Sistema e Rede",
|
"categoryPerformance": "⚡ Sistema e Rede",
|
||||||
"servers": "📂 **Servidores**",
|
"servers": "📂 **Comunidades**",
|
||||||
"users": "👥 **Usuários**",
|
"users": "👥 **Usuários**",
|
||||||
"players": "🎧 **Players**",
|
"players": "🎧 **Players**",
|
||||||
"playersWithPlaying": "{{total}} ({{playing}} tocando)",
|
"playersWithPlaying": "{{total}} ({{playing}} tocando)",
|
||||||
@@ -1317,6 +1360,146 @@
|
|||||||
"floodTitle": "Mensagens de Registro Descartadas",
|
"floodTitle": "Mensagens de Registro Descartadas",
|
||||||
"floodDesc": "⚠️ **{{count}}** mensagem(ns) de registro adicionais foram descartadas durante uma inundação para proteger os limites de taxa da API.",
|
"floodDesc": "⚠️ **{{count}}** mensagem(ns) de registro adicionais foram descartadas durante uma inundação para proteger os limites de taxa da API.",
|
||||||
"floodFooter": "Proteção de Limite de Taxa • ErrorChannel"
|
"floodFooter": "Proteção de Limite de Taxa • ErrorChannel"
|
||||||
|
},
|
||||||
|
"statustest": {
|
||||||
|
"author": "Remix · Diagnóstico do Canal de Status",
|
||||||
|
"disabledAuthor": "Remix Status Hub",
|
||||||
|
"disabledTitle": "Canal de Status Desativado",
|
||||||
|
"disabledDesc": "❌ O canal de status está atualmente **desativado** ou sem um `channelId` configurado.\n\nConfigure `statusChannel` em `config.json`:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"SEU_ID_DE_CANAL\",\n \"mentionRoleId\": \"ID_DO_CARGO_OPCIONAL\",\n \"updateIntervalSeconds\": 300\n}\n```",
|
||||||
|
"refreshedTitle": "✅ Cartão ao Vivo Atualizado",
|
||||||
|
"refreshedDesc": "Atualização de telemetria ao vivo enviada para <#{{channelId}}>.\nID da Mensagem do Cartão: `{{messageId}}`",
|
||||||
|
"incidentTitle": "🔴 Incidente de Teste Disparado",
|
||||||
|
"incidentDesc": "Interrupção por incidente publicada para **{{target}}** em <#{{channelId}}>.\nExecute `{{prefix}}statustest resolve {{target}}` para resolver.",
|
||||||
|
"resolvedTitle": "✅ Incidente de Teste Resolvido",
|
||||||
|
"resolvedDesc": "Resolução de incidente publicada para **{{target}}** em <#{{channelId}}>.",
|
||||||
|
"helpTitle": "Comandos do Canal de Status",
|
||||||
|
"helpDesc": "O canal de status está **ativo** em <#{{channelId}}>.\nCartão ao Vivo Atual: `{{cardId}}`\n\n**Opções de Uso:**\n• `{{prefix}}statustest refresh` — Forçar atualização da mensagem de status ao vivo.\n• `{{prefix}}statustest incident <target>` — Disparar mensagem de interrupção de teste.\n• `{{prefix}}statustest resolve <target>` — Resolver interrupção e registrar tempo de inatividade.\n\n*Alvos válidos:* `gateway`, `audioNode`, `database`, `dashboard`, `api`"
|
||||||
|
},
|
||||||
|
"statusChannel": {
|
||||||
|
"liveCardTitle": "Status do Sistema ao Vivo",
|
||||||
|
"liveCardAuthor": "Remix · Telemetria e Status do Sistema",
|
||||||
|
"operationalDesc": "🟢 **Todos os Sistemas Operacionais**\nO Remix está funcionando perfeitamente em todos os servidores.",
|
||||||
|
"degradedDesc": "🟡 **Interrupção Parcial**\nAlguns subsistemas não críticos estão enfrentando instabilidades.",
|
||||||
|
"criticalDesc": "🔴 **Interrupção Crítica Detectada**\nUm ou mais serviços principais estão offline no momento.",
|
||||||
|
"gatewayField": "🏓 Latência do Gateway",
|
||||||
|
"uptimeField": "⏱️ Tempo de Atividade",
|
||||||
|
"sessionsField": "🎵 Sessões Ativas",
|
||||||
|
"ramField": "📟 Memória (RAM)",
|
||||||
|
"cpuField": "⚙️ Uso de CPU",
|
||||||
|
"guildsField": "🏰 Comunidades Conectadas",
|
||||||
|
"subsystemsField": "🛡️ Saúde dos Subsistemas",
|
||||||
|
"incidentAuthor": "🔴 Incidente Detectado",
|
||||||
|
"incidentTitle": "🔴 {{name}} está fora do ar",
|
||||||
|
"incidentDefaultDesc": "{{name}} está enfrentando instabilidades. Nossa equipe está investigando o incidente.",
|
||||||
|
"resolvedAuthor": "✅ Incidente Resolvido",
|
||||||
|
"resolvedTitle": "✅ {{name}} está online novamente",
|
||||||
|
"resolvedDefaultDesc": "A conectividade com {{name}} foi totalmente restabelecida e verificada como estável.",
|
||||||
|
"downtimeField": "Tempo de Inatividade",
|
||||||
|
"startedField": "Iniciado",
|
||||||
|
"resolvedField": "Resolvido",
|
||||||
|
"statusField": "Status",
|
||||||
|
"severityField": "Gravidade",
|
||||||
|
"investigating": "Investigando",
|
||||||
|
"stable": "Estável",
|
||||||
|
"operational": "Operacional",
|
||||||
|
"outage": "Instabilidade",
|
||||||
|
"disabled": "Desativado"
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"topAuthor": "Classificação do Servidor",
|
||||||
|
"topTitle": "Músicas Mais Tocadas ({{timeframe}})",
|
||||||
|
"noData": "Nenhuma música foi tocada neste servidor ainda. Comece com {{prefix}}play <música>!",
|
||||||
|
"timeframeWeek": "Esta Semana",
|
||||||
|
"timeframeMonth": "Este Mês",
|
||||||
|
"timeframeAll": "Todo o Período",
|
||||||
|
"topFooter": "Filtrar com: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all",
|
||||||
|
"plays": "reproduções",
|
||||||
|
"globalAuthor": "Classificação Global • Todos os Servidores",
|
||||||
|
"globalTitle": "Músicas Mais Tocadas em Todos os Servidores",
|
||||||
|
"globalFooter": "Filtrar com: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global",
|
||||||
|
"pageFooter": "Página {{page}}/{{totalPages}} • {{timeframe}}",
|
||||||
|
"serverFallbackNote": "ℹ️ _Nenhuma música tocada neste servidor ainda — exibindo paradas globais da rede:_",
|
||||||
|
"timeframeDay": "Últimas 24 Horas",
|
||||||
|
"timeframeYear": "Este Ano"
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"wrappedAuthor": "Retrospectiva Musical da Comunidade",
|
||||||
|
"wrappedTitle": "Personalidade Musical do Servidor",
|
||||||
|
"totalStreamed": "Total Transmitido",
|
||||||
|
"tracksQueued": "Faixas na Fila",
|
||||||
|
"peakHour": "Horário de Pico",
|
||||||
|
"topDJ": "Principal DJ da Comunidade",
|
||||||
|
"topSongs": "Melhores Músicas",
|
||||||
|
"wrappedFooter": "Desenvolvido por Remix Music • Toque música com {{prefix}}play",
|
||||||
|
"globalAuthor": "Retrospectiva da Rede Remix • Todos os Servidores",
|
||||||
|
"globalTitle": "Personalidade Musical Global",
|
||||||
|
"activeServers": "Comunidades Ativas",
|
||||||
|
"globalFooter": "Rede Global Remix • Digite {{prefix}}wrapped para o resumo do seu servidor"
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"authorSelf": "Sua Retrospectiva Musical Pessoal",
|
||||||
|
"authorOther": "Retrospectiva Musical Pessoal • {{username}}",
|
||||||
|
"titleSelf": "Sua Identidade Musical no Servidor",
|
||||||
|
"titleOther": "Identidade Musical de {{username}} no Servidor",
|
||||||
|
"totalStreamed": "Total Transmitido",
|
||||||
|
"tracksQueued": "Faixas na Fila",
|
||||||
|
"peakHour": "Horário de Pico",
|
||||||
|
"djRank": "Classificação de DJ da Comunidade",
|
||||||
|
"djRankValue": "Top #{{rank}} de {{total}} DJs",
|
||||||
|
"topArtist": "Artista Favorito",
|
||||||
|
"topSongs": "Músicas Mais Tocadas",
|
||||||
|
"noDataSelf": "Você ainda não colocou músicas na fila neste servidor. Comece com {{prefix}}play <música>!",
|
||||||
|
"noDataOther": "{{username}} ainda não colocou músicas na fila neste servidor.",
|
||||||
|
"globalNotice": "🌐 Estatísticas Globais • Nenhuma música tocada neste servidor ainda",
|
||||||
|
"footer": "Desenvolvido por Remix Music • {{prefix}}top para paradas do servidor"
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"notAvailable": "Favoritos pessoais indisponíveis (banco de dados desconectado).",
|
||||||
|
"empty": "Você ainda não possui favoritos salvos! Use `{{prefix}}fav` enquanto uma música toca para favoritá-la.",
|
||||||
|
"invalidIndex": "Número de faixa inválido. Escolha um número entre 1 e {{max}}.",
|
||||||
|
"queuedOne": "Música favorita adicionada à fila: **[{{title}}]({{url}})**",
|
||||||
|
"queuedAll": "**{{count}} música(s) favorita(s)** adicionada(s) à fila!",
|
||||||
|
"removeUsage": "Uso: `{{prefix}}fav remove <número|título>`",
|
||||||
|
"notFound": "Essa música não foi encontrada nos seus favoritos.",
|
||||||
|
"removed": "Removido **[{{title}}]({{url}})** dos seus favoritos.",
|
||||||
|
"cleared": "Todas as **{{count}} música(s)** foram removidas dos seus favoritos.",
|
||||||
|
"listTitle": "Músicas Favoritas de {{user}}",
|
||||||
|
"listFooter": "Página {{page}}/{{totalPages}} • {{total}} salvas • Use {{prefix}}fav play para tocar todas",
|
||||||
|
"limitReached": "Você atingiu o limite máximo de {{max}} músicas favoritas.",
|
||||||
|
"added": "⭐ **[{{title}}]({{url}})** adicionada aos seus favoritos! (Total: {{count}})"
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"notAvailable": "Playlists pessoais indisponíveis (banco de dados desconectado).",
|
||||||
|
"saveUsage": "Uso: `{{prefix}}playlist save <nome> [url]`",
|
||||||
|
"playUsage": "Uso: `{{prefix}}playlist play <nome>`",
|
||||||
|
"showUsage": "Uso: `{{prefix}}playlist show <nome> [página]`",
|
||||||
|
"addUsage": "Uso: `{{prefix}}playlist add <nome> [url]`",
|
||||||
|
"removeUsage": "Uso: `{{prefix}}playlist remove <nome> <número_faixa>`",
|
||||||
|
"deleteUsage": "Uso: `{{prefix}}playlist delete <nome>`",
|
||||||
|
"emptyQueue": "Nada está tocando ou na fila para salvar! Toque alguma música primeiro com `{{prefix}}play`.",
|
||||||
|
"limitReached": "Você atingiu o limite máximo de {{max}} playlists personalizadas.",
|
||||||
|
"invalidName": "Nome de playlist inválido. Deve ter entre 1 e 32 caracteres e não conter barras.",
|
||||||
|
"saveFailed": "Falha ao salvar a playlist. Tente novamente.",
|
||||||
|
"saved": "💾 **{{count}} música(s)** salvas na playlist **{{name}}**! Toque quando quiser com `{{prefix}}playlist play {{name}}`.",
|
||||||
|
"notFound": "Playlist **{{name}}** não encontrada. Use `{{prefix}}playlist list` para ver suas playlists.",
|
||||||
|
"playlistEmpty": "A playlist **{{name}}** está vazia.",
|
||||||
|
"queued": "▶️ Playlist **{{name}}** (**{{count}} faixas**) carregada na fila!",
|
||||||
|
"listTitle": "Playlists Personalizadas de {{user}}",
|
||||||
|
"noPlaylists": "Você ainda não tem playlists salvas! Use `{{prefix}}playlist save <nome>` para salvar a fila atual.",
|
||||||
|
"listFooter": "Página {{page}}/{{totalPages}} • {{total}}/{{max}} playlists • Toque com: {{prefix}}playlist play <nome>",
|
||||||
|
"showTitle": "Playlist: {{name}}",
|
||||||
|
"showFooter": "Página {{page}}/{{totalPages}} • {{total}} faixas em {{name}} • Toque com: {{prefix}}playlist play {{name}}",
|
||||||
|
"nothingPlaying": "Nenhuma música tocando no momento para adicionar.",
|
||||||
|
"playlistFull": "Esta playlist atingiu o limite máximo de {{max}} faixas.",
|
||||||
|
"addFailed": "Falha ao adicionar música à playlist.",
|
||||||
|
"trackAdded": "**{{title}}** adicionada à playlist **{{name}}**! (Total: {{count}} faixas)",
|
||||||
|
"invalidIndex": "Índice de faixa inválido.",
|
||||||
|
"trackRemoved": "**{{title}}** removida da playlist **{{name}}**! ({{count}} faixas restantes)",
|
||||||
|
"deleted": "🗑️ Playlist **{{name}}** excluída.",
|
||||||
|
"resolving": "🔎 Carregando faixas de **{{source}}**...",
|
||||||
|
"savedFromSource": "💾 Salvou **{{count}} faixa(s)** de **{{source}}** na playlist **{{name}}**! Toque a qualquer momento com `{{prefix}}playlist play {{name}}`.",
|
||||||
|
"noTracksFromSource": "Não foi possível encontrar ou carregar faixas reproduzíveis desse link.",
|
||||||
|
"tracksAdded": "Adicionou **{{addedCount}} faixa(s)** à playlist **{{name}}**! (Total: {{count}} faixas)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+195
-12
@@ -35,7 +35,20 @@
|
|||||||
"permission": "İzin `{{$permission}}`",
|
"permission": "İzin `{{$permission}}`",
|
||||||
"optionCount": "{{$count}} seçenek",
|
"optionCount": "{{$count}} seçenek",
|
||||||
"commandInspectorAuthor": "Komut Yardımı • {{prefix}}{{name}}",
|
"commandInspectorAuthor": "Komut Yardımı • {{prefix}}{{name}}",
|
||||||
"commandInspectorFooter": "Tüm komutlar için {{prefix}}help yazın • Kategori: {{category}}"
|
"commandInspectorFooter": "Tüm komutlar için {{prefix}}help yazın • Kategori: {{category}}",
|
||||||
|
"tabHome": "Ana Sayfa",
|
||||||
|
"tabHomeHeader": "Ana Sayfa",
|
||||||
|
"tabMusic": "Müzik",
|
||||||
|
"tabMusicHeader": "Müzik Komutları",
|
||||||
|
"tabUtil": "Araçlar",
|
||||||
|
"tabUtilHeader": "Araç Komutları",
|
||||||
|
"tabSupport": "Destek",
|
||||||
|
"tabSupportHeader": "Destek Bilgisi",
|
||||||
|
"homeContent": "**Remix**, YouTube, Spotify, SoundCloud, Deezer ve daha fazlasını destekleyen yüksek kaliteli 7/24 bir müzik botudur.\n\n**✨ Öne Çıkan Özellikler**\n• **48kHz Hi-Fi Ses** — Kristal netliğinde ses akışı hattı\n• **30+ Ses Filtresi** — Bassboost, 8D, Nightcore, Vaporwave, Ekolayzer\n• **Dinamik Ses Dengeleme** — Müzik kaynakları arasında EBU R128 ses seviyesi dengeleme\n• **7/24 Web Radyosu** — Dünya çapında 30.000'den fazla canlı radyo istasyonu\n\n**📂 Komut Kategorileri**\n🏠 • **Ana Sayfa** — Hızlı bot özeti ve durum\n🎵 • **Müzik** — Çalma, kuyruk, arama, filtreler ($prefixplay, $prefixskip, $prefixqueue)\n🔧 • **Araçlar** — Ayarlar, 7/24 ses, gecikme, oylama ($prefixsettings, $prefixping)\nℹ️ • **Destek** — Topluluk sunucusu ve yardım\n\n💡 **İpucu:** Bölümleri değiştirmek için aşağıdaki sekme emojilerine tıklayın veya ayrıntılı bilgi için $prefixhelp <komut> kullanın.",
|
||||||
|
"supportContent": "Yardıma mı ihtiyacınız var, bir hata mı bildirmek istiyorsunuz veya yeni özellikler mi önermek istiyorsunuz?\n\n💬 **[Remix Destek Sunucusuna Katılın](https://fluxer.gg/remix)**\n\n**Ekip ve Geliştiriciler:**\n• **Fantic** — Topluluk Yöneticisi\n• **Shadow** — Baş Geliştirici\n• **NoLogicAlan** — Baş Geliştirici\n\nRemix'i sunucunuza eklemek için $prefixinvite komutunu da kullanabilirsiniz.",
|
||||||
|
"noCommands": "_Kullanılabilir komut yok._",
|
||||||
|
"learnMore": "\nBir komut hakkında daha fazla bilgi edinmek için $prefixhelp <komut adı> komutunu çalıştırın!",
|
||||||
|
"subpageTip": "\n\n**İpucu:** Sayfalar arasında geçiş yapmak için ⬅️ ➡️ kullanın."
|
||||||
},
|
},
|
||||||
"invalidFlag": "Geçersiz bayrak `$invalidFlag`. Bu komuttaki hiçbir seçenekle eşleşmiyor.\n`$previousCmd $invalidFlag`",
|
"invalidFlag": "Geçersiz bayrak `$invalidFlag`. Bu komuttaki hiçbir seçenekle eşleşmiyor.\n`$previousCmd $invalidFlag`",
|
||||||
"textWrapError": "Hatalı biçimlendirilmiş dize `{{$value}}`: İstenen dizeden sonra kapatma tırnak işareti (`{{$quote}}`) eksik.",
|
"textWrapError": "Hatalı biçimlendirilmiş dize `{{$value}}`: İstenen dizeden sonra kapatma tırnak işareti (`{{$quote}}`) eksik.",
|
||||||
@@ -70,7 +83,7 @@
|
|||||||
"remove": "Kuyruktan belirli bir şarkıyı kaldırın.",
|
"remove": "Kuyruktan belirli bir şarkıyı kaldırın.",
|
||||||
"resume": "Ses kanalınızdaki çalmayı devam ettirin.",
|
"resume": "Ses kanalınızdaki çalmayı devam ettirin.",
|
||||||
"search": "Bir sorgu için arama sonuçlarını görüntüleyin ve çalmak için birini seçin.\nTüm sağlayıcıları destekler — `sp: şarkı` gibi satır içi önek veya `-p dz` kullanın.",
|
"search": "Bir sorgu için arama sonuçlarını görüntüleyin ve çalmak için birini seçin.\nTüm sağlayıcıları destekler — `sp: şarkı` gibi satır içi önek veya `-p dz` kullanın.",
|
||||||
"servers": "Botun bulunduğu sunucuların listesini alın.",
|
"servers": "Botun bulunduğu toplulukların listesini alın.",
|
||||||
"settings": "Mevcut sunucudaki ayarları değiştirin/görüntüleyin.",
|
"settings": "Mevcut sunucudaki ayarları değiştirin/görüntüleyin.",
|
||||||
"shuffle": "Kuyruğu rastgele yeniden sıralar.",
|
"shuffle": "Kuyruğu rastgele yeniden sıralar.",
|
||||||
"skip": "Şu an çalan şarkıyı atlayın.",
|
"skip": "Şu an çalan şarkıyı atlayın.",
|
||||||
@@ -91,7 +104,13 @@
|
|||||||
"vote": "FluxerList üzerinde sunucunuz/botunuz için oylama bilgilerini görüntüleyin veya oy verenleri kontrol edin",
|
"vote": "FluxerList üzerinde sunucunuz/botunuz için oylama bilgilerini görüntüleyin veya oy verenleri kontrol edin",
|
||||||
"previous": "Oynatma geçmişindeki önceki şarkıyı çal.",
|
"previous": "Oynatma geçmişindeki önceki şarkıyı çal.",
|
||||||
"replay": "Çalan şarkıyı baştan başlat.",
|
"replay": "Çalan şarkıyı baştan başlat.",
|
||||||
"skipto": "Kuyruktaki belirli bir şarkıya doğrudan atla."
|
"skipto": "Kuyruktaki belirli bir şarkıya doğrudan atla.",
|
||||||
|
"statustest": "Herkese açık durum kanalı güncellemelerini, canlı kartları ve olayları test edin.",
|
||||||
|
"top": "Bu sunucuda en çok çalınan şarkıları ve en popüler sanatçıları görüntüleyin.",
|
||||||
|
"wrapped": "Bir topluluk müzik özeti ve dinleme istatistikleri oluşturun.",
|
||||||
|
"mywrapped": "Kişisel müzik özetinizi, en çok dinlenen parçalarınızı ve sunucu DJ sıralamanızı görüntüleyin.",
|
||||||
|
"fav": "Favori parçalarınızı kaydedin ve ses kanallarına yükleyin.",
|
||||||
|
"playlist": "Mevcut sırayı kaydedin veya kişisel çalma listelerinizi yönetin."
|
||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
"debug": {
|
"debug": {
|
||||||
@@ -190,6 +209,22 @@
|
|||||||
},
|
},
|
||||||
"skipto": {
|
"skipto": {
|
||||||
"position": "Atlanacak şarkının kuyruktaki sıra numarası."
|
"position": "Atlanacak şarkının kuyruktaki sıra numarası."
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"timeframe": "Zaman aralığını filtrele: 24h, week, month, year, all veya global ya da sayfa numarası.",
|
||||||
|
"page": "Atlanacak sayfa numarası."
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"scope": "Özet kapsamı: server veya global."
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"user": "Müzik özetini görüntülemek istediğiniz kullanıcı."
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"args": "Alt komut veya parça: play, list, remove, clear veya değiştirmek için boş bırakın."
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"args": "Alt komut ve bağımsız değişkenler: save, play, list, show, add, remove, delete."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"pagination": {
|
"pagination": {
|
||||||
@@ -356,7 +391,10 @@
|
|||||||
"autoLeaveFooter": "Botu {{prefix}}247 ile 7/24 seste tutun",
|
"autoLeaveFooter": "Botu {{prefix}}247 ile 7/24 seste tutun",
|
||||||
"joinFailedAuthor": "🔊 Ses Bağlantısı Hatası",
|
"joinFailedAuthor": "🔊 Ses Bağlantısı Hatası",
|
||||||
"joinFailedTitle": "Bağlantı Başarısız",
|
"joinFailedTitle": "Bağlantı Başarısız",
|
||||||
"joinFailedFooter": "Ses kanalı izinlerini kontrol edin ve {{prefix}}join ile tekrar deneyin"
|
"joinFailedFooter": "Ses kanalı izinlerini kontrol edin ve {{prefix}}join ile tekrar deneyin",
|
||||||
|
"inactivityWarningTitle": "Yakında Ses Kanalından Ayrılıyor",
|
||||||
|
"inactivityWarningDesc": "Ses oturumu şu anda etkin değil. **{{minutes}} dakika** içinde <#{{channel}}> kanalından bağlantı kesilecek.\n\nBeni 7/24 seste tutmak için {{prefix}}247 kullanın!",
|
||||||
|
"inactivityWarningFooter": "Devam etmek için {{prefix}}play ile bir şarkı çalın"
|
||||||
},
|
},
|
||||||
"leave": {
|
"leave": {
|
||||||
"noVoiceChannel": "⚠️ Lütfen önce bir ses kanalına katılın veya bir tane belirtin: `{{prefix}}leave <#kanal>`",
|
"noVoiceChannel": "⚠️ Lütfen önce bir ses kanalına katılın veya bir tane belirtin: `{{prefix}}leave <#kanal>`",
|
||||||
@@ -744,7 +782,12 @@
|
|||||||
"loadingDirectStream": "🔎 Doğrudan akış yükleniyor...",
|
"loadingDirectStream": "🔎 Doğrudan akış yükleniyor...",
|
||||||
"resolvingLavalinkStream": "🔎 Lavalink üzerinden akış çözülüyor...",
|
"resolvingLavalinkStream": "🔎 Lavalink üzerinden akış çözülüyor...",
|
||||||
"lastfmPlaybackAuthor": "🎵 Last.fm Çalma",
|
"lastfmPlaybackAuthor": "🎵 Last.fm Çalma",
|
||||||
"lastfmSearchAuthor": "🔎 Last.fm Arama"
|
"lastfmSearchAuthor": "🔎 Last.fm Arama",
|
||||||
|
"loadingAttachmentStream": "Fluxer medya eki yükleniyor...",
|
||||||
|
"sourceAttachment": "Fluxer Eki",
|
||||||
|
"noQueryTitle": "Şarkı veya Ek Gerekli",
|
||||||
|
"noQueryDesc": "Lütfen bir arama sorgusu, doğrudan medya bağlantısı girin veya bu komutla bir ses/video dosyası yükleyin.",
|
||||||
|
"noQueryFooter": "Müzik Çalar • Doğrudan Ek Desteği"
|
||||||
},
|
},
|
||||||
"playnext": {
|
"playnext": {
|
||||||
"searching": "🔍 Aranıyor...",
|
"searching": "🔍 Aranıyor...",
|
||||||
@@ -853,14 +896,14 @@
|
|||||||
"cancelOption": "İptal"
|
"cancelOption": "İptal"
|
||||||
},
|
},
|
||||||
"servers": {
|
"servers": {
|
||||||
"noServers": "_Sunucu bulunamadı._",
|
"noServers": "_Topluluk bulunamadı._",
|
||||||
"title": "🌐 Sunucular ({{count}})",
|
"title": "🌐 Topluluklar ({{count}})",
|
||||||
"pageTitle": "🌐 Sunucular ({{count}}) - Sayfa {{page}}/{{total}}",
|
"pageTitle": "🌐 Topluluklar ({{count}}) - Sayfa {{page}}/{{total}}",
|
||||||
"listComplete": "Liste tamamlandı",
|
"listComplete": "Liste tamamlandı",
|
||||||
"serversAuthor": "🌐 Ağ Topolojisi",
|
"serversAuthor": "🌐 Ağ Topolojisi",
|
||||||
"serversTitle": "Bağlı Sunucu Rehberi",
|
"serversTitle": "Bağlı Topluluk Rehberi",
|
||||||
"serversActiveBadge": "{{count}} Aktif Sunucu",
|
"serversActiveBadge": "{{count}} Aktif Topluluk",
|
||||||
"serversTelemetryFooter": "Gerçek zamanlı sunucu telemetrisi • Sayfa {{page}}/{{total}}"
|
"serversTelemetryFooter": "Gerçek zamanlı topluluk telemetrisi • Sayfa {{page}}/{{total}}"
|
||||||
},
|
},
|
||||||
"settings": {
|
"settings": {
|
||||||
"unknownSetting": "❌ Bilinmeyen ayar `{{setting}}`.",
|
"unknownSetting": "❌ Bilinmeyen ayar `{{setting}}`.",
|
||||||
@@ -1028,7 +1071,7 @@
|
|||||||
"categoryMusic": "🎧 Müzik Aktivitesi",
|
"categoryMusic": "🎧 Müzik Aktivitesi",
|
||||||
"categoryLastfm": "🎵 Last.fm",
|
"categoryLastfm": "🎵 Last.fm",
|
||||||
"categoryPerformance": "⚡ Sistem ve Ağ",
|
"categoryPerformance": "⚡ Sistem ve Ağ",
|
||||||
"servers": "📂 **Sunucular**",
|
"servers": "📂 **Topluluklar**",
|
||||||
"users": "👥 **Kullanıcılar**",
|
"users": "👥 **Kullanıcılar**",
|
||||||
"players": "🎧 **Oynatıcılar**",
|
"players": "🎧 **Oynatıcılar**",
|
||||||
"playersWithPlaying": "{{total}} ({{playing}} çalıyor)",
|
"playersWithPlaying": "{{total}} ({{playing}} çalıyor)",
|
||||||
@@ -1317,6 +1360,146 @@
|
|||||||
"floodTitle": "Günlük Mesajları Düşürüldü",
|
"floodTitle": "Günlük Mesajları Düşürüldü",
|
||||||
"floodDesc": "⚠️ API hız limitlerini korumak için taşkın sırasında fazladan **{{count}}** günlük mesajı düşürüldü.",
|
"floodDesc": "⚠️ API hız limitlerini korumak için taşkın sırasında fazladan **{{count}}** günlük mesajı düşürüldü.",
|
||||||
"floodFooter": "Hız Limiti Koruması • ErrorChannel"
|
"floodFooter": "Hız Limiti Koruması • ErrorChannel"
|
||||||
|
},
|
||||||
|
"statustest": {
|
||||||
|
"author": "Remix · Durum Kanalı Tanılama",
|
||||||
|
"disabledAuthor": "Remix Durum Merkezi",
|
||||||
|
"disabledTitle": "Durum Kanalı Devre Dışı",
|
||||||
|
"disabledDesc": "❌ Durum kanalı şu anda **devre dışı** veya `channelId` eksik.\n\n`config.json` içinde `statusChannel` öğesini yapılandırın:\n```json\n\"statusChannel\": {\n \"enabled\": true,\n \"channelId\": \"KANAL_ID_NIZ\",\n \"mentionRoleId\": \"ISTEGE_BAGLI_ROL_ID\",\n \"updateIntervalSeconds\": 300\n}\n```",
|
||||||
|
"refreshedTitle": "✅ Canlı Kart Yenilendi",
|
||||||
|
"refreshedDesc": "<#{{channelId}}> kanalına canlı telemetri güncellemesi gönderildi.\nKart Mesaj Kimliği: `{{messageId}}`",
|
||||||
|
"incidentTitle": "🔴 Test Olayı Tetiklendi",
|
||||||
|
"incidentDesc": "<#{{channelId}}> kanalında **{{target}}** için kesinti olayı yayınlandı.\nÇözmek için `{{prefix}}statustest resolve {{target}}` komutunu çalıştırın.",
|
||||||
|
"resolvedTitle": "✅ Test Olayı Çözüldü",
|
||||||
|
"resolvedDesc": "<#{{channelId}}> kanalında **{{target}}** için olay çözümü yayınlandı.",
|
||||||
|
"helpTitle": "Durum Kanalı Komutları",
|
||||||
|
"helpDesc": "Durum kanalı <#{{channelId}}> üzerinde **aktif**.\nGeçerli Canlı Kart: `{{cardId}}`\n\n**Kullanım Seçenekleri:**\n• `{{prefix}}statustest refresh` — Canlı durum iletisini zorla güncelle.\n• `{{prefix}}statustest incident <target>` — Test kesinti iletisi tetikle.\n• `{{prefix}}statustest resolve <target>` — Kesintiyi çöz ve kesinti süresini paylaş.\n\n*Geçerli hedefler:* `gateway`, `audioNode`, `database`, `dashboard`, `api`"
|
||||||
|
},
|
||||||
|
"statusChannel": {
|
||||||
|
"liveCardTitle": "Canlı Sistem Durumu",
|
||||||
|
"liveCardAuthor": "Remix · Sistem Telemetrisi ve Durumu",
|
||||||
|
"operationalDesc": "🟢 **Tüm Sistemler Çalışıyor**\nRemix tüm sunucularda sorunsuz çalışıyor.",
|
||||||
|
"degradedDesc": "🟡 **Kısmi Kesinti**\nBazı kritik olmayan alt sistemlerde aksamalar yaşanıyor.",
|
||||||
|
"criticalDesc": "🔴 **Büyük Kesinti Tespit Edildi**\nBir veya daha fazla ana servis şu anda çevrimdışı.",
|
||||||
|
"gatewayField": "🏓 Ağ Geçidi Gecikmesi",
|
||||||
|
"uptimeField": "⏱️ Çalışma Süresi",
|
||||||
|
"sessionsField": "🎵 Aktif Oturumlar",
|
||||||
|
"ramField": "📟 Bellek (RAM)",
|
||||||
|
"cpuField": "⚙️ CPU Kullanımı",
|
||||||
|
"guildsField": "🏰 Topluluk Varlığı",
|
||||||
|
"subsystemsField": "🛡️ Alt Sistem Sağlığı",
|
||||||
|
"incidentAuthor": "🔴 Olay Tespit Edildi",
|
||||||
|
"incidentTitle": "🔴 {{name}} çöktü",
|
||||||
|
"incidentDefaultDesc": "{{name}} kesinti yaşıyor. Ekibimiz olayı aktif olarak inceliyor.",
|
||||||
|
"resolvedAuthor": "✅ Olay Çözüldü",
|
||||||
|
"resolvedTitle": "✅ {{name}} tekrar çevrimiçi",
|
||||||
|
"resolvedDefaultDesc": "{{name}} bağlantısı tamamen geri yüklendi ve kararlı olduğu doğrulandı.",
|
||||||
|
"downtimeField": "Kesinti Süresi",
|
||||||
|
"startedField": "Başlangıç",
|
||||||
|
"resolvedField": "Çözüldü",
|
||||||
|
"statusField": "Durum",
|
||||||
|
"severityField": "Önem Derecesi",
|
||||||
|
"investigating": "İnceleniyor",
|
||||||
|
"stable": "Kararlı",
|
||||||
|
"operational": "Çalışıyor",
|
||||||
|
"outage": "Aksama",
|
||||||
|
"disabled": "Devre Dışı"
|
||||||
|
},
|
||||||
|
"top": {
|
||||||
|
"topAuthor": "Sunucu Lider Tablosu",
|
||||||
|
"topTitle": "En Çok Çalınan Şarkılar ({{timeframe}})",
|
||||||
|
"noData": "Bu sunucuda henüz hiç şarkı çalınmadı. {{prefix}}play <şarkı> ile çalmaya başlayın!",
|
||||||
|
"timeframeWeek": "Bu Hafta",
|
||||||
|
"timeframeMonth": "Bu Ay",
|
||||||
|
"timeframeAll": "Tüm Zamanlar",
|
||||||
|
"topFooter": "Şununla filtrele: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all",
|
||||||
|
"plays": "çalma",
|
||||||
|
"globalAuthor": "Küresel Lider Tablosu • Tüm Sunucular",
|
||||||
|
"globalTitle": "Tüm Sunucularda En Çok Çalınan Şarkılar",
|
||||||
|
"globalFooter": "Şununla filtrele: {{prefix}}top 24h • {{prefix}}top week • {{prefix}}top month • {{prefix}}top year • {{prefix}}top all • {{prefix}}top global",
|
||||||
|
"pageFooter": "Sayfa {{page}}/{{totalPages}} • {{timeframe}}",
|
||||||
|
"serverFallbackNote": "ℹ️ _Bu sunucuda henüz şarkı çalınmadı — Küresel Ağ listeleri gösteriliyor:_",
|
||||||
|
"timeframeDay": "Son 24 Saat",
|
||||||
|
"timeframeYear": "Bu Yıl"
|
||||||
|
},
|
||||||
|
"wrapped": {
|
||||||
|
"wrappedAuthor": "Topluluk Müzik Özeti",
|
||||||
|
"wrappedTitle": "Sunucunun Müzik Kişiliği",
|
||||||
|
"totalStreamed": "Toplam Akış",
|
||||||
|
"tracksQueued": "Kuyruğa Eklenen Şarkılar",
|
||||||
|
"peakHour": "En Çok Dinlenen Saat",
|
||||||
|
"topDJ": "En İyi Topluluk DJ'i",
|
||||||
|
"topSongs": "En İyi Şarkılar",
|
||||||
|
"wrappedFooter": "Remix Music ile güçlendirilmiştir • {{prefix}}play ile müzik çalın",
|
||||||
|
"globalAuthor": "Remix Ağı Özeti • Tüm Sunucular",
|
||||||
|
"globalTitle": "Küresel Müzik Kişiliği",
|
||||||
|
"activeServers": "Aktif Topluluklar",
|
||||||
|
"globalFooter": "Remix Küresel Ağı • Sunucunuzun özeti için {{prefix}}wrapped yazın"
|
||||||
|
},
|
||||||
|
"mywrapped": {
|
||||||
|
"authorSelf": "Kişisel Müzik Özetiniz",
|
||||||
|
"authorOther": "Kişisel Müzik Özeti • {{username}}",
|
||||||
|
"titleSelf": "Sunucu Dinleme Kimliğiniz",
|
||||||
|
"titleOther": "{{username}} Kullanıcısının Sunucu Dinleme Kimliği",
|
||||||
|
"totalStreamed": "Toplam Yayınlanan",
|
||||||
|
"tracksQueued": "Sıraya Eklenen Parçalar",
|
||||||
|
"peakHour": "En Çok Dinlenen Saat",
|
||||||
|
"djRank": "Topluluk DJ Sıralaması",
|
||||||
|
"djRankValue": "{{total}} DJ arasından #{{rank}}.",
|
||||||
|
"topArtist": "En Sevilen Sanatçı",
|
||||||
|
"topSongs": "Kişisel En İyi Şarkılar",
|
||||||
|
"noDataSelf": "Bu sunucuda henüz şarkı çalmadınız. {{prefix}}play <şarkı> ile başlayın!",
|
||||||
|
"noDataOther": "{{username}} bu sunucuda henüz şarkı çalmadı.",
|
||||||
|
"globalNotice": "🌐 Küresel İstatistikler • Bu sunucuda henüz şarkı çalınmadı",
|
||||||
|
"footer": "Remix Music tarafından desteklenmektedir • Sunucu listeleri için {{prefix}}top"
|
||||||
|
},
|
||||||
|
"fav": {
|
||||||
|
"notAvailable": "Kişisel favoriler kullanılamıyor (veritabanı bağlantısı kesildi).",
|
||||||
|
"empty": "Henüz kayıtlı favoriniz yok! Çalmakta olan bir şarkıyı favorilere eklemek için `{{prefix}}fav` kullanın.",
|
||||||
|
"invalidIndex": "Geçersiz parça numarası. Lütfen 1 ile {{max}} arasında bir sayı seçin.",
|
||||||
|
"queuedOne": "Favori parça sıraya eklendi: **[{{title}}]({{url}})**",
|
||||||
|
"queuedAll": "**{{count}} favori parça** sıraya eklendi!",
|
||||||
|
"removeUsage": "Kullanım: `{{prefix}}fav remove <numara|başlık>`",
|
||||||
|
"notFound": "Bu parça favorilerinizde bulunamadı.",
|
||||||
|
"removed": "**[{{title}}]({{url}})** favorilerinizden kaldırıldı.",
|
||||||
|
"cleared": "Tüm **{{count}} parça** favorilerinizden temizlendi.",
|
||||||
|
"listTitle": "{{user}} kullanıcısının Favori Parçaları",
|
||||||
|
"listFooter": "Sayfa {{page}}/{{totalPages}} • {{total}} kayıtlı • Hepsini çalmak için {{prefix}}fav play kullanın",
|
||||||
|
"limitReached": "Maksimum {{max}} favori parça sınırına ulaştınız.",
|
||||||
|
"added": "⭐ **[{{title}}]({{url}})** favorilerinize eklendi! (Toplam: {{count}})"
|
||||||
|
},
|
||||||
|
"playlist": {
|
||||||
|
"notAvailable": "Kişisel çalma listeleri kullanılamıyor (veritabanı bağlantısı kesildi).",
|
||||||
|
"saveUsage": "Kullanım: `{{prefix}}playlist save <isim> [url]`",
|
||||||
|
"playUsage": "Kullanım: `{{prefix}}playlist play <isim>`",
|
||||||
|
"showUsage": "Kullanım: `{{prefix}}playlist show <isim> [sayfa]`",
|
||||||
|
"addUsage": "Kullanım: `{{prefix}}playlist add <isim> [url]`",
|
||||||
|
"removeUsage": "Kullanım: `{{prefix}}playlist remove <isim> <parça_numarası>`",
|
||||||
|
"deleteUsage": "Kullanım: `{{prefix}}playlist delete <isim>`",
|
||||||
|
"emptyQueue": "Kaydedilecek hiçbir şey çalmıyor veya sırada parça yok! Önce `{{prefix}}play` ile müzik başlatın.",
|
||||||
|
"limitReached": "Maksimum {{max}} özel çalma listesi sınırına ulaştınız.",
|
||||||
|
"invalidName": "Geçersiz çalma listesi adı. İsimler 1-32 karakter olmalı ve eğik çizgi içermemelidir.",
|
||||||
|
"saveFailed": "Çalma listesi kaydedilemedi. Lütfen tekrar deneyin.",
|
||||||
|
"saved": "💾 **{{count}} parça** **{{name}}** listesine kaydedildi! `{{prefix}}playlist play {{name}}` ile dilediğiniz zaman çalın.",
|
||||||
|
"notFound": "**{{name}}** isimli çalma listesi bulunamadı. Listelerinizi görmek için `{{prefix}}playlist list` kullanın.",
|
||||||
|
"playlistEmpty": "**{{name}}** çalma listesi boş.",
|
||||||
|
"queued": "▶️ **{{name}}** listesinden **{{count}} parça** sıraya yüklendi!",
|
||||||
|
"listTitle": "{{user}} kullanıcısının Özel Çalma Listeleri",
|
||||||
|
"noPlaylists": "Henüz kayıtlı çalma listeniz yok! Mevcut sırayı kaydetmek için `{{prefix}}playlist save <isim>` kullanın.",
|
||||||
|
"listFooter": "Sayfa {{page}}/{{totalPages}} • {{total}}/{{max}} liste • Çalmak için: {{prefix}}playlist play <isim>",
|
||||||
|
"showTitle": "Çalma Listesi: {{name}}",
|
||||||
|
"showFooter": "Sayfa {{page}}/{{totalPages}} • {{name}} içinde {{total}} parça • Çalmak için: {{prefix}}playlist play {{name}}",
|
||||||
|
"nothingPlaying": "Eklemek için şu anda çalan bir parça yok.",
|
||||||
|
"playlistFull": "Bu çalma listesi maksimum {{max}} parça sınırına ulaştı.",
|
||||||
|
"addFailed": "Parça çalma listesine eklenemedi.",
|
||||||
|
"trackAdded": "**{{title}}**, **{{name}}** listesine eklendi! (Toplam: {{count}} parça)",
|
||||||
|
"invalidIndex": "Geçersiz parça indeksi.",
|
||||||
|
"trackRemoved": "**{{title}}**, **{{name}}** listesinden kaldırıldı! ({{count}} parça kaldı)",
|
||||||
|
"deleted": "🗑️ **{{name}}** çalma listesi silindi.",
|
||||||
|
"resolving": "🔎 Parçalar **{{source}}** üzerinden yükleniyor...",
|
||||||
|
"savedFromSource": "💾 **{{source}}** kaynağından **{{count}} parça** **{{name}}** çalma listesine kaydedildi! `{{prefix}}playlist play {{name}}` ile istediğiniz zaman oynatın.",
|
||||||
|
"noTracksFromSource": "Bu bağlantıdan çalınabilir hiçbir parça bulunamadı veya yüklenemedi.",
|
||||||
|
"tracksAdded": "**{{name}}** çalma listesine **{{addedCount}} parça** eklendi! (Toplam: {{count}} parça)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user