mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
Compare commits
152
Commits
2f51b7e1d7
..
main
| 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 | ||
|
|
91e7812c30 | ||
|
|
c007bb93f8 | ||
|
|
bf376c8861 | ||
|
|
3b9620012f | ||
|
|
c0c95610ac | ||
|
|
dfe77d86b9 | ||
|
|
5dc286e364 | ||
|
|
e33fbb2fdb | ||
|
|
53d0990ebe | ||
|
|
5d29301b38 | ||
|
|
edcdd4ddef | ||
|
|
e8171dce26 | ||
|
|
885db461ce | ||
|
|
36b27d466b | ||
|
|
63433816c4 | ||
|
|
8689dee50a | ||
|
|
4c3c04bd7d | ||
|
|
8874ed1ec6 | ||
|
|
2494bf79d6 | ||
|
|
b7f20fcb02 | ||
|
|
53e3a7e4de | ||
|
|
af2c725b54 | ||
|
|
618ecb1a0b | ||
|
|
a780ec22c8 | ||
|
|
70f124294d | ||
|
|
5714f7b2c8 | ||
|
|
a467611e37 | ||
|
|
ec441ea20a | ||
|
|
c1dbda2068 | ||
|
|
7bd80e62f7 | ||
|
|
1e02478fb6 | ||
|
|
3e30cdc6a3 | ||
|
|
e9d0a0b54b | ||
|
|
c9cf813e6a | ||
|
|
e31c77e0d8 | ||
|
|
64e69275a4 | ||
|
|
d6c233c311 | ||
|
|
af23db1255 | ||
|
|
784458f387 | ||
|
|
ee1b9be917 | ||
|
|
351336ea19 | ||
|
|
90a53f047f | ||
|
|
665be29a16 | ||
|
|
08e5d363fc | ||
|
|
04aece8af3 | ||
|
|
fa5bc68f16 | ||
|
|
cf278ed68c | ||
|
|
f2bfff59b5 | ||
|
|
355f6b1129 | ||
|
|
3115f94629 | ||
|
|
87accdacba | ||
|
|
e9a58f422a | ||
|
|
6439f07204 | ||
|
|
2932f9110e | ||
|
|
fbe052b9da | ||
|
|
0a2bbc75d8 | ||
|
|
5b4d1b0aa3 | ||
|
|
b068e3e95c | ||
|
|
4dd9f2ade6 | ||
|
|
7c5f783855 | ||
|
|
f54764d58d | ||
|
|
500b0de4c8 | ||
|
|
4bc2a98bab | ||
|
|
952924cdd5 | ||
|
|
5129ee5ecc | ||
|
|
6e1722b723 | ||
|
|
02b85bad5a | ||
|
|
15a84cce69 | ||
|
|
93f12487d3 | ||
|
|
64f5782d53 | ||
|
|
4f769f832f | ||
|
|
09054d37a8 | ||
|
|
0e3087c7b5 | ||
|
|
824d989f34 | ||
|
|
b4bb6c26e5 | ||
|
|
068bb02bdb | ||
|
|
93bb92b109 | ||
|
|
8c743b96fa | ||
|
|
97fe282bb3 |
No files matched your search
@@ -8,4 +8,3 @@ download/
|
|||||||
config.json
|
config.json
|
||||||
docker/config.json
|
docker/config.json
|
||||||
docker/.env
|
docker/.env
|
||||||
scripts/
|
|
||||||
@@ -4,35 +4,8 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches: [ "main" ]
|
branches: [ "main" ]
|
||||||
|
|
||||||
# Two quick pushes must not race each other's rollout.
|
|
||||||
concurrency:
|
|
||||||
group: deploy-main
|
|
||||||
cancel-in-progress: false
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# Nothing is built or deployed unless the project still parses, links and has complete translations.
|
|
||||||
check:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: read
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Set up Node.js
|
|
||||||
uses: actions/setup-node@v4
|
|
||||||
with:
|
|
||||||
node-version: "22"
|
|
||||||
|
|
||||||
- name: Install dependencies
|
|
||||||
run: npm install
|
|
||||||
|
|
||||||
- name: Syntax, module-link, JSON and translation check
|
|
||||||
run: npm run check
|
|
||||||
|
|
||||||
build-and-push:
|
build-and-push:
|
||||||
needs: check
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
@@ -57,7 +30,6 @@ jobs:
|
|||||||
tags: |
|
tags: |
|
||||||
type=raw,value=latest
|
type=raw,value=latest
|
||||||
type=ref,event=branch
|
type=ref,event=branch
|
||||||
type=sha,format=long
|
|
||||||
|
|
||||||
- name: Build and push Docker image
|
- name: Build and push Docker image
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v5
|
||||||
@@ -67,8 +39,6 @@ jobs:
|
|||||||
push: true
|
push: true
|
||||||
tags: ${{ steps.meta.outputs.tags }}
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
labels: ${{ steps.meta.outputs.labels }}
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
build-args: |
|
|
||||||
GIT_SHA=${{ github.sha }}
|
|
||||||
|
|
||||||
- name: Set up kubectl
|
- name: Set up kubectl
|
||||||
uses: azure/setup-kubectl@v4
|
uses: azure/setup-kubectl@v4
|
||||||
@@ -76,16 +46,16 @@ jobs:
|
|||||||
version: "latest"
|
version: "latest"
|
||||||
|
|
||||||
- name: Configure kubeconfig
|
- name: Configure kubeconfig
|
||||||
env:
|
|
||||||
KUBE_CONFIG: ${{ secrets.KUBE_CONFIG }}
|
|
||||||
run: |
|
run: |
|
||||||
if [ -z "$KUBE_CONFIG" ]; then
|
if [ -z "${{ secrets.KUBE_CONFIG }}" ]; then
|
||||||
echo "::error::KUBE_CONFIG secret is not set. Add it under Settings > Secrets and variables > Actions."
|
echo "::error::KUBE_CONFIG secret is not set. Add it under Settings > Secrets and variables > Actions."
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
mkdir -p "$HOME/.kube"
|
mkdir -p "$HOME/.kube"
|
||||||
echo "$KUBE_CONFIG" | base64 --decode > "$HOME/.kube/config"
|
echo "${{ secrets.KUBE_CONFIG }}" | base64 --decode > "$HOME/.kube/config"
|
||||||
chmod 600 "$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
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
# @fluxerjs/sharding@3.0.0 pins an exact @fluxerjs/core peer that conflicts with ^3.1.0.
|
# @fluxerjs/sharding@3.0.0 pins an exact @fluxerjs/core peer that conflicts with ^3.2.0.
|
||||||
# The Dockerfile already passes this flag; this makes a plain `npm install` work too.
|
# The Dockerfile already passes this flag; this makes a plain `npm install` work too.
|
||||||
legacy-peer-deps=true
|
legacy-peer-deps=true
|
||||||
@@ -7,639 +7,263 @@
|
|||||||
<h1 align="center">Remix</h1>
|
<h1 align="center">Remix</h1>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<strong>A premium, high-quality, and open-source music bot for Fluxer.</strong>
|
<strong>A modern, high-performance, and open-source music bot for Fluxer.</strong>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://web.fluxer.app/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208">Invite to Server</a> ·
|
<a href="https://fluxer.com/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208">Invite Remix</a> ·
|
||||||
<a href="https://fluxer.gg/Remix">Report a Bug</a> ·
|
<a href="https://fluxer.gg/remix">Join Support Server</a> ·
|
||||||
<a href="https://fluxer.gg/Remix">Request a Feature</a>
|
<a href="https://github.com/remix-bot/fluxer/issues">Report an Issue</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License">
|
<img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License">
|
||||||
<img src="https://img.shields.io/badge/Node.js-%3E%3D22.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/ESM-Modules-yellow.svg" alt="ESM">
|
<img src="https://img.shields.io/badge/Voice-LiveKit%20%2B%20NodeLink-orange.svg" alt="Audio Engine">
|
||||||
<img src="https://img.shields.io/badge/Audio-lavalink--client%20%2B%20NodeLink-orange.svg" alt="lavalink-client">
|
<img src="https://img.shields.io/badge/Database-MySQL-4479A1.svg" alt="Database">
|
||||||
<img src="https://img.shields.io/badge/Voice-%40fluxerjs%2Fvoice%20(LiveKit)-9b59b6.svg" alt="@fluxerjs/voice">
|
<img src="https://img.shields.io/badge/Languages-8%20Locales-9b59b6.svg" alt="Localization">
|
||||||
<img src="https://img.shields.io/badge/Database-MySQL-4479A1.svg" alt="MySQL">
|
|
||||||
<img src="https://img.shields.io/badge/Maintained%3F-Yes-green.svg" alt="Maintained">
|
<img src="https://img.shields.io/badge/Maintained%3F-Yes-green.svg" alt="Maintained">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Table of Contents
|
## 🌟 Overview
|
||||||
|
|
||||||
- [About The Project](#-about-the-project)
|
**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.
|
||||||
- [How Audio Playback Works](#-how-audio-playback-works)
|
|
||||||
- [Features](#-features)
|
We believe essential music features should never be locked behind a paywall — **every feature on Remix is 100% free and open-source.**
|
||||||
- [Getting Started (Users)](#-getting-started-users)
|
|
||||||
- [Commands](#-commands)
|
|
||||||
- [Self-Hosting](#-self-hosting-the-bot)
|
|
||||||
- [Prerequisites](#prerequisites)
|
|
||||||
- [Installation](#installation)
|
|
||||||
- [Database Setup](#-database-setup)
|
|
||||||
- [Dashboard Setup (Optional)](#-dashboard-setup-optional)
|
|
||||||
- [Configuration Reference](#-configuration-reference)
|
|
||||||
- [Project Architecture](#-project-architecture)
|
|
||||||
- [The Layered Codebase](#-the-layered-codebase)
|
|
||||||
- [Localization](#-localization)
|
|
||||||
- [Scripts](#-npm-scripts)
|
|
||||||
- [Credits](#-credits--license)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## About The Project
|
## ⚡ Highlights & Features
|
||||||
|
|
||||||
Remix is a free and open-source music bot for [Fluxer](https://fluxer.app), built with [`@fluxerjs/core`](https://github.com/fluxerjs/core) for the Fluxer API and [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) for LiveKit voice connections. Track search and streaming are handled by [`lavalink-client`](https://www.npmjs.com/package/lavalink-client) talking to a [NodeLink](https://github.com/PerformanC/NodeLink) audio node (Lavalink-compatible), and the bot publishes Opus audio to LiveKit as a participant — with a custom WebM/Opus pipeline (zero-re-encode passthrough and remux where possible).
|
* 🎵 **Low-Latency Zero-Re-Encode Audio** — Direct WebM/Opus streaming pipeline published over LiveKit with instant start times and zero CPU re-encoding overhead.
|
||||||
|
* 🔎 **Universal Music Search** — Seamless search and playback across YouTube, YouTube Music, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bandcamp, Bilibili, plus direct HTTP/HTTPS and radio streams.
|
||||||
We believe music features shouldn't be locked behind paywalls — **all commands on Remix are 100% free and always will be.**
|
* 🔄 **24/7 Voice Persistence** — Keeps the bot in designated voice channels around the clock with exponential backoff recovery, boot rejoin, and state restore across restarts.
|
||||||
|
* ⏪ **Playback History & `%previous`** — Dedicated 20-track circular playback history ring buffer to step backward (`%previous`, `%undo`) without lost tracks.
|
||||||
### Fluxer.js 3.0
|
* ⏸️ **Smart Auto-Pause & Mute Protection** — Automatically pauses playback when voice channels empty (auto-resuming when members return) or when server-muted by administrators.
|
||||||
|
* 🔁 **Instant Track Replay** — Restart the current song from 0:00 with `%replay` (or `%restart`) without re-fetching network streams.
|
||||||
Remix runs on **`@fluxerjs/core` / `@fluxerjs/util` / `@fluxerjs/voice` 3.0.0** plus **`@fluxerjs/sharding` 3.0.0** (see the [changelog](https://fluxer.js.org/changelog/)). The v3 DX overhaul required only five code-level changes in this codebase — everything else (event names, gateway opcodes, permission flags, the voice/LiveKit API, `EmbedBuilder`, message `reply`/`edit`/`react`, the raw `VOICE_STATE_UPDATE` / `VoiceStatesSync` payloads this bot tracks) is unchanged between 2.2 and 3.0:
|
* 🎛️ **Audio Filters & DSP Studio** — Real-time audio transformations: Bassboost (low/medium/hard), Nightcore, Vaporwave, 8D audio, and fine-grained `%speed` & `%pitch` tuning.
|
||||||
|
* 📊 **Loudness Normalization** — Built-in EBU R128 / ReplayGain leveling (`%normalize`) to eliminate volume jumps between quiet acoustic songs and loud EDM tracks.
|
||||||
1. `package.json` — the three `@fluxerjs/*` ranges moved from `^2.2.0` to `^3.0.0` (a `^2.2.0` range will not install 3.0).
|
* 📈 **Comprehensive Last.fm Suite** — Real-time scrobbling, loved tracks synchronization, artist crowns, server leaderboards, profile cards, and automated similar-track autoplay.
|
||||||
2. `src/core/Bot.mjs` — the `Client` `presence` option now uses the normalized v3 shape (`customStatus`/`emojiName`/`emojiId`) instead of the 2.2 wire format (`custom_status`); the deprecated no-op `suppressIntentWarning` option was dropped.
|
* 📑 **Massive Playlist Ingestion** — Asynchronous chunked ingestion for large Spotify and SoundCloud playlists (>100 tracks) with instant playback start on song #1.
|
||||||
3. `src/voice/gateway/GatewayHandler.mjs` — the presence-rotation sender wraps its `client.ws` access in a try/catch, because 3.0 exposes `client.ws` as a getter that throws when the gateway is not connected (2.2 exposed a plain optional). The rotation payload itself stays in wire format because it sends opcode 3 straight to the shard.
|
* 🌐 **Full 8-Language Localization** — English, Arabic, Kurdish (Sorani), Turkish, German, Brazilian Portuguese, Simplified Chinese, and Traditional Chinese.
|
||||||
4. `src/ui/MessageHandler.mjs` — `joinChannel()` checks `channel.isGuild?.()` first (the new ChannelType-based guard) and keeps the legacy `"guildId" in channel` check as a fallback for stub objects.
|
* 💾 **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.
|
||||||
5. `src/utils/ShardingUtils.mjs` (new) — 3.0 removed the WebSocketManager's `shards` Map property in favour of `getShards()`/`getShard()` methods, which had silently disabled the bot's raw-socket listeners (they no-op'd behind their existing guards). All five readers — Bot.mjs's WS error handlers, GatewayHandler's raw listener and presence sender, LavalinkManager's payload routing and raw listener — now go through version-agnostic helpers that also make them shard-aware (see below).
|
* 📊 **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.
|
||||||
Two 3.0 library-level notes that need no code change here: the WS manager no longer emits `shardCreate` (the bot's 5-second handler re-arm loop covers re-attachment), and `Guild.description` was removed from the core structures (the dashboard serializer already null-guards it, so server descriptions simply render empty). Passing `intents` or `suppressIntentWarning` inside `config["fluxer.js"]` is still accepted — both are documented deprecated no-ops in 3.0.
|
|
||||||
|
|
||||||
### Sharding (optional)
|
|
||||||
|
|
||||||
`@fluxerjs/sharding` 3.0.0 (beta) is wired in as an **opt-in** layer — the default single-process boot (`npm start` / `node index.mjs`) is byte-for-byte unchanged, and none of the sharding code paths activate unless the process was actually forked by the manager (it sets `FLUXER_SHARD_IDS` *and* provides an IPC channel; manually exporting the variables does nothing).
|
|
||||||
|
|
||||||
- **Supervisor:** `node shard.mjs` (or `npm run shard`) forks one child per shard slice, each running the ordinary `index.mjs` boot. The manager owns the shared per-IP IDENTIFY budget so children can never collectively exceed the gateway limit, respawns dead children, and exposes `broadcastEval` / `fetchClientValues` / `respawnAll`.
|
|
||||||
- **Child side:** `src/core/Bot.mjs` attaches the library's `ShardClientUtil` before `login()` (it applies the shard slice to the client options) and calls `notifyReady()` after login so the supervisor's spawn promise resolves. A failed attach under a manager is fatal by design — without its slice the child would identify as shard 0 like every other child and thrash the gateway sessions.
|
|
||||||
- **Guild→shard routing:** opcode-4 voice payloads from LavalinkManager now target `shardIdForGuildId(guildId)` instead of hardcoded shard 0, presence updates fan out to every gateway shard in the process, and raw-socket listeners attach to *all* local shard sockets. Unsharded, every one of these degrades to exactly the previous shard-0 behavior.
|
|
||||||
|
|
||||||
Configuration (config.json, all optional — defaults shown):
|
|
||||||
|
|
||||||
```json
|
|
||||||
"sharding": { "totalShards": 1, "shardsPerProcess": 1, "respawn": true,
|
|
||||||
"spawnTimeout": 30000, "spawnDelay": 5000 }
|
|
||||||
```
|
|
||||||
|
|
||||||
`FLUXER_TOTAL_SHARDS` / `FLUXER_SHARDS_PER_PROCESS` env vars override the config (useful in Docker, where you switch the container command to `node shard.mjs`). Prefer an explicit `totalShards` — Fluxer's `/gateway/bot` always reports `shards: 1`, so there is no reliable `"auto"`.
|
|
||||||
|
|
||||||
Beta caveats worth knowing: DMs and guild-less events only reach shard 0 (library limitation); each child opens its own MySQL/Redis/Lavalink connections and its own dashboard RPC subscription, so the dashboard is currently single-process-first — guilds on other shards won't be reachable from it, and concurrent `storage/stats.json` writes across children can race. The stock `node index.mjs` deployment has none of these issues.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## How Audio Playback Works
|
## 🚀 Getting Started
|
||||||
|
|
||||||
Understanding the pipeline helps when debugging or contributing:
|
### Invite to Your 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.
|
||||||
%play → LavalinkManager.search() ──► NodeLink (track resolution only)
|
3. Type `%play <song title or URL>` to start listening!
|
||||||
→ Player queue → FluxerAudioBridge.play(voiceConnection, track)
|
|
||||||
├─ /v4/trackstream → direct WebM/Opus passthrough (no re-encode)
|
|
||||||
├─ /v4/loadstream → magic-byte sniffing:
|
|
||||||
│ • WebM (1A45DFA3) → passthrough to LiveKit
|
|
||||||
│ • OggS → OggDemuxer → WebMOpusMuxer (remux, no re-encode)
|
|
||||||
│ • raw PCM → OpusEncoder (opusscript)
|
|
||||||
│ → WebMOpusMuxer → LiveKit
|
|
||||||
└─ conn.play() → @fluxerjs/voice LiveKit connection (bot publishes audio
|
|
||||||
as a LiveKit participant)
|
|
||||||
```
|
|
||||||
|
|
||||||
A few things worth knowing:
|
|
||||||
|
|
||||||
- **No Lavalink players are created.** NodeLink is used for search and its REST stream/lyrics endpoints (`/v4/loadstream`, `/v4/trackstream`, `/v4/loadlyrics`); playback itself is pure LiveKit publishing.
|
|
||||||
- **Seek / pause / resume** work by stopping the current stream and re-requesting it at an offset from NodeLink.
|
|
||||||
- **Filters** (bassboost, nightcore, etc.) are applied server-side by NodeLink, so they take effect on the next track that starts.
|
|
||||||
- **Volume** is applied client-side by the LiveKit connection (1–200).
|
|
||||||
- Radio metadata (StreamTitle) is read with **ffprobe** (`ffprobe-static`).
|
|
||||||
- **Bilibili playback (fully anonymous — no cookies)** — `%play https://www.bilibili.com/video/BV…` (b23.tv short links and `?p=` parts included) resolves the video through Bilibili's web API and feeds it to the node through a signed localhost proxy that attaches the Referer/User-Agent headers Bilibili's CDN requires. Multi-part videos queue like a playlist. Requests use Bilibili's WBI-signed endpoints (derived anonymously from the nav payload), which survive the HTTP 412 risk-control blocks that reject plain unsigned API calls on many hosting IPs; on any WBI failure the bot automatically retries through the legacy unsigned endpoints. Playurl calls carry the anonymous `try_look=1` flag and prefer the best DASH audio stream (~130–170 kbps AAC) — real DASH audio works without login — falling back to the html5 progressive mp4 for videos without DASH audio, and multi-segment progressive streams are served back-to-back through the proxy's concatenating mode with Range/seek support. The bot generates and manages its Bilibili device fingerprint (buvid3/buvid4/b_nut) automatically and retries once with a fresh fingerprint when risk control interferes. The proxy binds `127.0.0.1` by default — set `bilibili.advertiseHost` (and `bind: "0.0.0.0"`) when your node runs on another machine.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Features
|
## 📖 Command Reference
|
||||||
|
|
||||||
- **High-quality audio playback** — NodeLink streaming with a zero-re-encode WebM/Opus pipeline, published over LiveKit
|
The default prefix is `%`. Server administrators can customize the prefix at any time using `%settings set prefix <new_prefix>`.
|
||||||
- **Multi-source search** — YouTube, YT Music, Spotify, SoundCloud, Deezer, Apple Music, Tidal, Bandcamp and 40+ more provider prefixes, plus direct URLs and Bilibili videos
|
|
||||||
- **24/7 mode** — keep the bot in a voice channel permanently, with staggered auto-rejoin on boot and rejoin retries on connection loss
|
|
||||||
- **Interactive emoji player** — reaction-based control panel with live progress, lyrics viewer, and a filter submenu
|
|
||||||
- **Lyrics** — synced lyrics via NodeLink
|
|
||||||
- **Radio stations** — built-in support for custom radio streams with keyword-based search
|
|
||||||
- **Last.fm integration** — account linking, scrobbling, now-playing, play loved/top/recent/albums, whoknows, crowns, compare, leaderboards, and profiles
|
|
||||||
- **Autoplay** — automatically play similar tracks when the queue ends (powered by Last.fm)
|
|
||||||
- **Seek** — jump to a specific position in the current track
|
|
||||||
- **Track options** — set custom start/end times per track, great for album compilations and hidden tracks
|
|
||||||
- **Queue move** — reorder tracks by moving them to a different position
|
|
||||||
- **Audio filters** — bassboost, speed, nightcore and more (applied server-side by NodeLink)
|
|
||||||
- **Server settings** — per-guild configuration (prefix, volume, locale, 24/7 channels, …) stored in MySQL
|
|
||||||
- **Dashboard backend** — optional Redis-RPC backend that an external web frontend uses to monitor players and control playback remotely
|
|
||||||
- **Multi-language support** — English, Arabic, German, Kurdish (Sorani), and Brazilian Portuguese
|
|
||||||
- **Configurable logging** — granular control over which log categories appear in the console
|
|
||||||
- **Graceful shutdown** — destroys players and closes MySQL/Redis/NodeLink sessions cleanly on SIGINT/SIGTERM/SIGUSR2
|
|
||||||
- **Module system** — pluggable module architecture for extending bot functionality (`storage/modules.json`)
|
|
||||||
|
|
||||||
---
|
### 🎵 Playback & Controls
|
||||||
|
|
||||||
## Getting Started (Users)
|
| Command | Aliases | Description | Example |
|
||||||
|
|
||||||
Want to use Remix in your server right away?
|
|
||||||
|
|
||||||
1. **[Invite Remix](https://web.fluxer.app/oauth2/authorize?client_id=1478084469635211806&scope=bot&permissions=3206208)** to your Fluxer server.
|
|
||||||
2. Join a voice channel.
|
|
||||||
3. Use the `%help` command to see everything the bot can do, or jump straight in with `%play <song name>`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Commands
|
|
||||||
|
|
||||||
Below is the complete list of Remix's commands. The default prefix is `%`.
|
|
||||||
|
|
||||||
### Music
|
|
||||||
|
|
||||||
| Command | Description | Usage | Aliases |
|
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `play` | Play a song from a URL, search query, or playlist | `%play Never Gonna Give You Up` / `%play lastfm:loved` | `p` |
|
| `play` | `p` | Play a track, search query, or playlist | `%play Blinding Lights` |
|
||||||
| `playnext` | Add a song/playlist to the *top* of the queue | `%playnext query: text` | `pn` |
|
| `playnext` | `pn` | Insert a song at the very top of the queue | `%playnext Starboy` |
|
||||||
| `pause` | Pause the current playback | `%pause` | |
|
| `pause` | — | Pause audio playback | `%pause` |
|
||||||
| `resume` | Resume the paused playback | `%resume` | |
|
| `resume` | — | Resume paused playback | `%resume` |
|
||||||
| `skip` | Skip the currently playing song | `%skip` | `s` |
|
| `skip` | `s` | Skip to the next track (vote-skip in busy rooms) | `%skip` |
|
||||||
| `np` | Show the currently playing song | `%np` | `current`, `nowplaying` |
|
| `previous` | `prev`, `back`, `undo` | Play the previous song from history | `%previous` |
|
||||||
| `list` | View the upcoming queue | `%list` | `queue`, `q` |
|
| `replay` | `restart` | Restart the currently playing song from 0:00 | `%replay` |
|
||||||
| `loop` | Toggle loop mode (song or queue) | `%loop queue` | |
|
| `seek` | — | Jump to a specific timestamp in the track | `%seek 1:45` |
|
||||||
| `shuffle` | Randomize the queue order | `%shuffle` | |
|
| `np` | `current`, `nowplaying` | Show detailed now-playing track card | `%np` |
|
||||||
| `remove` | Remove a specific song by its queue index | `%remove 3` | |
|
| `volume` | `v`, `vol` | Adjust playback volume (1–200%) | `%volume 85` |
|
||||||
| `clear` | Clear the entire queue | `%clear` | `c` |
|
| `volumedefault` | `vd` | Set default volume for the server | `%volumedefault 75` |
|
||||||
| `volume` | Change the playback volume (1–200) | `%volume 50` | `v`, `vol` |
|
| `autoplay` | `ap` | Toggle similar-track autoplay when queue ends | `%autoplay on` |
|
||||||
| `volumedefault` | Set the default volume for the server | `%volumedefault 80` | `vd` |
|
| `normalize` | `norm`, `replaygain` | Toggle dynamic loudness normalization | `%normalize on` |
|
||||||
| `search` | Search for a track and pick from results | `%search query` | |
|
|
||||||
| `lyrics` | Display synced lyrics from NodeLink | `%lyrics` | `lyric`, `ly` |
|
|
||||||
| `thumbnail` | Get the thumbnail of the current track | `%thumbnail` | `thumb` |
|
|
||||||
| `radio` | Play a built-in or custom radio station | `%radio` | `r` |
|
|
||||||
| `filter` | Manage audio filters (bass, speed, nightcore, etc.) | `%filter bass 50` | `filters`, `fx`, `effect` |
|
|
||||||
| `player` | Create an interactive emoji control panel with live progress | `%player` | |
|
|
||||||
| `join` | Make the bot join a specific voice channel | `%join 123456789` | |
|
|
||||||
| `leave` | Make the bot leave the current voice channel | `%leave` | `l`, `stop` |
|
|
||||||
| `forceleave` | Force the bot to leave any channel (requires Manage Channels) | `%forceleave` | `fl` |
|
|
||||||
| `seek` | Seek to a specific position in the current track | `%seek 1:30` / `%seek 90` | |
|
|
||||||
| `move` | Move a track from one position to another in the queue | `%move 2 5` | `mv`, `m` |
|
|
||||||
| `autoplay` | Toggle autoplay — automatically play similar tracks when queue ends | `%autoplay` | `ap` |
|
|
||||||
| `trackopt` | Set custom start/end times for tracks | `%trackopt set 0:30 3:45` | `to` |
|
|
||||||
|
|
||||||
### Utility
|
### 📑 Queue Management
|
||||||
|
|
||||||
| Command | Description | Usage | Aliases |
|
| Command | Aliases | Description | Example |
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `settings` | View or change server settings (requires Manage Server) | `%settings set` | `prefix`, `pfx`, `247` |
|
| `list` | `queue`, `q` | Display interactive paginated queue | `%list` |
|
||||||
| `stats` | Display bot stats (uptime, ping, player count, stored scrobbles) | `%stats` | `info` |
|
| `skipto` | `jump`, `jumpto` | Skip directly to track #X in the queue | `%skipto 4` |
|
||||||
| `invite` | Get the bot invite link | `%invite` | `addbot`, `remix` |
|
| `shuffle` | — | Randomize the order of queued tracks | `%shuffle` |
|
||||||
| `support` | Get an invite to the support server | `%support` | `server` |
|
| `move` | `mv`, `m` | Move a song from one position to another | `%move 4 1` |
|
||||||
| `lastfm` | Link Last.fm, toggle scrobbling, view profile, love/unlove tracks, top artists, play tracks, leaderboard | `%lastfm link` / `%lastfm love` / `%lastfm artists` / `%lastfm lb` | `lf`, `lfm` |
|
| `remove` | — | Remove a track or range from the queue | `%remove 3` / `%remove 5-8` |
|
||||||
| `vote` | Check FluxerList voters for the bot | `%vote` | |
|
| `clear` | `c` | Clear upcoming tracks or a range | `%clear` / `%clear 2 10` |
|
||||||
| `reload` | Reload commands or modules at runtime (owner) | `%reload` | |
|
| `loop` | — | Toggle repeat mode (`song`, `queue`, or `off`) | `%loop queue` |
|
||||||
| `servers` | List servers the bot is in (owner) | `%servers` | |
|
| `trackopt` | `to` | Configure custom start/end timestamps | `%trackopt set 0:30 3:15` |
|
||||||
| `eval` | Evaluate JavaScript (owner only) | `%eval 1+1` | |
|
|
||||||
| `debug` | Debug voice connections and player state (owner) | `%debug voice` | |
|
|
||||||
| `test` | Show voice channel user counts (owner) | `%test` | |
|
|
||||||
|
|
||||||
## Self-Hosting The Bot
|
### 💾 Personal Playlists & Favorites
|
||||||
|
|
||||||
If you prefer to host Remix yourself, please note: **You must make it clear that your bot is an instance of Remix.** Change the bot's name and give credit in the bot's profile (e.g., *"Powered by [Remix](https://github.com/remix-bot/fluxer)"*).
|
| Command | Aliases | Description | Example |
|
||||||
|
|
||||||
### Quick Start with Docker (Recommended)
|
|
||||||
|
|
||||||
The fastest way to self-host Remix is with Docker. Everything — the bot, MySQL, Redis, and NodeLink — runs in containers with a single command. All Docker files live in the `docker/` folder.
|
|
||||||
|
|
||||||
1. **Clone and configure:**
|
|
||||||
```bash
|
|
||||||
git clone https://github.com/remix-bot/fluxer.git
|
|
||||||
cd fluxer/docker
|
|
||||||
cp config_example.json config.json
|
|
||||||
cp .env.example .env # optional — compose has working defaults
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Edit `config.json`** — fill in your bot token, MySQL credentials (defaults match the compose MySQL service), NodeLink details (defaults match the compose NodeLink service), and your owner IDs. Spotify/Deezer/Apple Music credentials are configured on the **NodeLink side** (`NODELINK_*` environment variables on the `nodelink` service in `docker/docker-compose.yml`; see NodeLink's docs), not in the bot config.
|
|
||||||
|
|
||||||
3. **Edit `.env`** (optional) — MySQL passwords, the NodeLink password (`NODELINK_PASSWORD`, required; use the same value in `config.json`), and timezone.
|
|
||||||
|
|
||||||
4. **Start everything:**
|
|
||||||
```bash
|
|
||||||
docker compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
5. **Check logs:**
|
|
||||||
```bash
|
|
||||||
docker compose logs -f bot
|
|
||||||
```
|
|
||||||
|
|
||||||
That's it. The bot will start, connect to MySQL (Last.fm and track-options tables are auto-created), connect to NodeLink, and log in to Fluxer.
|
|
||||||
|
|
||||||
#### Docker file structure
|
|
||||||
|
|
||||||
```
|
|
||||||
docker/
|
|
||||||
├── Dockerfile # Multi-stage build (Node 22 + tini, non-root user, healthcheck)
|
|
||||||
├── docker-entrypoint.sh # Writes config.json from CONFIG_JSON env var on first boot
|
|
||||||
├── docker-compose.yml # bot + MySQL + Redis + NodeLink
|
|
||||||
├── .env.example # Compose env template (MySQL creds, ports, TZ)
|
|
||||||
├── config_example.json # Docker-friendly config template
|
|
||||||
├── config.json # You create this (gitignored)
|
|
||||||
├── .env # You create this (gitignored)
|
|
||||||
└── healthcheck.mjs # container healthcheck (reads the bot's heartbeat file)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Docker services
|
|
||||||
|
|
||||||
| Service | Container | Port | Purpose |
|
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `bot` | remix-bot | none (the bot runs no HTTP server) | The Remix bot (+ optional dashboard backend) |
|
| `fav` | `favorite`, `favorites`, `bookmark` | Save or remove playing track from personal favorites, list, or play | `%fav` / `%fav play` / `%fav list` |
|
||||||
| `mysql` | remix-mysql | — | Settings, Last.fm users, and track options storage |
|
| `playlist` | `pl`, `playlists` | Save active queue as a named playlist, play, list, or manage personal playlists | `%playlist save chill` / `%playlist play chill` / `%playlist list` |
|
||||||
| `redis` | remix-redis | — | Dashboard RPC pub/sub (optional) |
|
|
||||||
| `nodelink` | remix-nodelink | internal only (3000), built from the official NodeLink repo | Lavalink-compatible audio node |
|
|
||||||
|
|
||||||
#### Useful Docker commands
|
### 🎛️ Audio Effects & Filters
|
||||||
|
|
||||||
```bash
|
| Command | Aliases | Description | Example |
|
||||||
# Run from the docker/ folder
|
|
||||||
cd docker
|
|
||||||
|
|
||||||
# Start all services
|
|
||||||
docker compose up -d
|
|
||||||
|
|
||||||
# View live bot logs
|
|
||||||
docker compose logs -f bot
|
|
||||||
|
|
||||||
# Restart the bot
|
|
||||||
docker compose restart bot
|
|
||||||
|
|
||||||
# Stop everything
|
|
||||||
docker compose down
|
|
||||||
|
|
||||||
# Stop and delete data volumes (full reset)
|
|
||||||
docker compose down -v
|
|
||||||
|
|
||||||
# Rebuild after code changes
|
|
||||||
docker compose up -d --build bot
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Using `CONFIG_JSON` env var instead of a mounted file
|
|
||||||
|
|
||||||
If you prefer to keep your config in an environment variable (useful for CI/CD or secret managers), set `CONFIG_JSON` in your `.env`:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
CONFIG_JSON={"token":"YOUR_TOKEN","mysql":{"host":"mysql","port":3306,"user":"remix","password":"remix_pw","database":"remix"},"nodelink":{"host":"nodelink","port":3000,"password":"change-me-nodelink"}}
|
|
||||||
```
|
|
||||||
|
|
||||||
The entrypoint will write it to `/app/config.json` on first boot if no config file is mounted.
|
|
||||||
|
|
||||||
### Manual Installation (Without Docker)
|
|
||||||
|
|
||||||
#### Prerequisites
|
|
||||||
|
|
||||||
- **Node.js** >= 22.13.0
|
|
||||||
- **MySQL** 8.0+ with JSON column support
|
|
||||||
- **[NodeLink](https://github.com/PerformanC/NodeLink)** instance (Lavalink-compatible audio node)
|
|
||||||
- **Redis** (optional — required only for the dashboard backend)
|
|
||||||
|
|
||||||
### Installation
|
|
||||||
|
|
||||||
1. **Clone the repository:**
|
|
||||||
```bash
|
|
||||||
git clone https://github.com/remix-bot/fluxer.git
|
|
||||||
cd fluxer
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Install dependencies:**
|
|
||||||
```bash
|
|
||||||
npm install
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Configure the bot:**
|
|
||||||
```bash
|
|
||||||
cp config_example.json config.json
|
|
||||||
```
|
|
||||||
Open `config.json` and fill in the required values:
|
|
||||||
- `token` — your Fluxer bot token
|
|
||||||
- `mysql` — your MySQL connection details (host, port, user, password, database)
|
|
||||||
- `prefix` — the command prefix (default: `%`)
|
|
||||||
- `nodelink` — your NodeLink instance connection details
|
|
||||||
- `lastfm` — (optional) Last.fm API credentials for scrobbling/autoplay features
|
|
||||||
- `owners` — array of Fluxer user IDs with owner-only command access
|
|
||||||
|
|
||||||
4. **Set up the database:** *(See [Database Setup](#-database-setup) below)*
|
|
||||||
|
|
||||||
5. **Start the bot:**
|
|
||||||
```bash
|
|
||||||
npm start
|
|
||||||
```
|
|
||||||
|
|
||||||
For development with inspector:
|
|
||||||
```bash
|
|
||||||
npm run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
### Database Setup
|
|
||||||
|
|
||||||
Remix requires a MySQL database to store per-guild settings and user data.
|
|
||||||
|
|
||||||
1. Create a dedicated database for Remix:
|
|
||||||
```sql
|
|
||||||
CREATE DATABASE remix;
|
|
||||||
```
|
|
||||||
|
|
||||||
2. Enter your MySQL connection details into `config.json`:
|
|
||||||
```json
|
|
||||||
"mysql": {
|
|
||||||
"host": "localhost",
|
|
||||||
"port": 3306,
|
|
||||||
"user": "remix",
|
|
||||||
"password": "your-password",
|
|
||||||
"database": "remix"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
3. Create the required `settings` table:
|
|
||||||
```sql
|
|
||||||
CREATE TABLE `settings` (
|
|
||||||
`id` varchar(70) NOT NULL,
|
|
||||||
`data` json NOT NULL
|
|
||||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
|
|
||||||
```
|
|
||||||
|
|
||||||
4. Everything else is **auto-created on startup** if missing:
|
|
||||||
- `track_options` — per-user per-track start/end times (`%trackopt`)
|
|
||||||
- `lastfm_users` — Last.fm session keys and scrobble opt-ins
|
|
||||||
- `lastfm_stats` — stored scrobble/link counts
|
|
||||||
|
|
||||||
5. *(Optional)* If you need to clone or repair the settings table across bot IDs, run:
|
|
||||||
```bash
|
|
||||||
npm run migrate
|
|
||||||
```
|
|
||||||
|
|
||||||
### Dashboard Setup (Optional)
|
|
||||||
|
|
||||||
Remix ships the **backend half** of a web dashboard: a Redis-RPC service that an external frontend project talks to. There is no HTTP server or web UI in this repository.
|
|
||||||
|
|
||||||
1. Enable it in `config.json`:
|
|
||||||
```json
|
|
||||||
"dashboard": {
|
|
||||||
"enabled": true,
|
|
||||||
"redis": { "url": "redis://localhost:6379" }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
2. How it works:
|
|
||||||
- The bot listens on Redis pub/sub channels (`request` / `response` / `info`) and answers JSON-RPC style requests with an `id` for correlation.
|
|
||||||
- Supported requests: `fetchPlayers`, `user`, `sharedServers`, `server`, `allServers`, `commands`, and `function` (remote actions: `join`, `pausePlayback`, `resumePlayback`, `skip`, `volume`, `addToQueue`, `voiceState`, `leave`, `testConnection`).
|
|
||||||
- Player updates are broadcast (debounced) on per-bot/per-player Redis channels so the frontend can render live state.
|
|
||||||
- **Login flow:** the external frontend writes login codes into the MySQL `login_codes` table; the bot verifies them with bcrypt hashes and marks them verified. Player control additionally requires the user to be in the same voice channel (owners are exempt).
|
|
||||||
|
|
||||||
3. **Security note:** the RPC channel has **no shared secret** — anything that can publish to your Redis can invoke the remote actions. Keep Redis network-isolated (as the Docker setup does) and don't expose it publicly.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Configuration Reference
|
|
||||||
|
|
||||||
Key configuration options in `config.json`:
|
|
||||||
|
|
||||||
| Option | Type | Default | Description |
|
|
||||||
| :--- | :--- | :--- | :--- |
|
| :--- | :--- | :--- | :--- |
|
||||||
| `token` | string | — | **Required.** Fluxer bot token |
|
| `filter` | `fx`, `effect` | Interactive filter picker menu | `%filter` |
|
||||||
| `prefix` | string | `%` | Default command prefix |
|
| `bassboost` | `bb`, `bass` | Apply bass boost (`low`, `medium`, `hard`, `off`) | `%bassboost medium` |
|
||||||
| `embedColor` | string | `0xe9196c` | Hex color for embed messages |
|
| `speed` | `rate`, `tempo` | Adjust playback speed multiplier (0.5×–2.0×) | `%speed 1.2` |
|
||||||
| `owners` | string[] | `[]` | User IDs with owner privileges |
|
| `pitch` | `semitone`, `tune` | Adjust pitch multiplier (0.5×–2.0×) | `%pitch 1.15` |
|
||||||
| `playerAFKTimeout` | number | `60000` | Inactivity timeout in ms before the player panel session ends |
|
|
||||||
| `customStatsFooter` | string | — | Custom text shown in the `%stats` embed footer |
|
|
||||||
| `presenceInterval` | number | `30000` | Interval in ms for rotating bot presence status |
|
|
||||||
| `presenceContents` | array | `[]` | Presence status messages to cycle through (strings or objects with `text`/`emoji_name`/`emoji_id`/`activity`) |
|
|
||||||
| `mysql` | object | — | **Required.** MySQL connection settings |
|
|
||||||
| `nodelink` | object | — | NodeLink connection (`host`, `port`, `password`, `requestTimeout`) |
|
|
||||||
| `lastfm` | object | — | Last.fm integration (`apiKey`, `apiSecret`, `scrobbleThreshold`, `scrobbleMinMs`) |
|
|
||||||
| `fluxerlist` | object | — | FluxerList integration (`apiKey`, `serverId`, `botId`, `serverSlug`, `botSlug`) |
|
|
||||||
| `dashboard` | object | — | Dashboard backend: `enabled`, `redis.url` |
|
|
||||||
| `radio` | array | `[]` | Custom radio station definitions |
|
|
||||||
| `logging` | object | — | Per-category log toggles: `enabled`, `warn`, and 14 categories (`player`, `inactivity`, `aloneCheck`, `voiceState`, `voice247`, `voice`, `mediaplayer`, `commands`, `guild`, `recovery`, `settings`, `lavalink`, `dashboard`, `redis`) |
|
|
||||||
| `timers` | object | — | Timing values in ms: `inactivityTimeout`, `aloneCheckInterval`, `aloneCheckDebounce`, `rejoin247Delay`, `leave247RejoinDelay`, `playerUpdateInterval`, `searchSessionTimeout`, `playerSessionTimeout`, `intentionalLeaveTTL` |
|
|
||||||
| `fluxer.js` | object | — | Fluxer.js REST options (`timeout`, `retries`) |
|
|
||||||
|
|
||||||
---
|
### 📊 Last.fm Suite
|
||||||
|
|
||||||
## Project Architecture
|
| Command | Aliases | Description | Example |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `lastfm` | `lf`, `lfm` | Main Last.fm hub | `%lastfm` |
|
||||||
|
| `lastfm link` | — | Link your Last.fm username | `%lastfm link your_user` |
|
||||||
|
| `lastfm love` | — | Love/unlove the currently playing track | `%lastfm love` |
|
||||||
|
| `lastfm whoknows` | `wk` | See who in the server listens to an artist | `%lastfm whoknows Queen` |
|
||||||
|
| `lastfm crowns` | — | View artist crown holders in the server | `%lastfm crowns` |
|
||||||
|
| `lastfm top` | — | View your top tracks, artists, or albums | `%lastfm top artists` |
|
||||||
|
| `lastfm lb` | — | View server-wide scrobble leaderboard | `%lastfm lb` |
|
||||||
|
|
||||||
```
|
### 🏆 Leaderboards & Community Stats
|
||||||
fluxer/
|
|
||||||
├── index.mjs # Entry point — creates the Remix instance, process-level
|
|
||||||
│ # error guards, and signal-based graceful shutdown
|
|
||||||
├── shard.mjs # OPTIONAL sharding supervisor (@fluxerjs/sharding) — forks
|
|
||||||
│ # one child process per shard slice, each running index.mjs
|
|
||||||
├── config_example.json # Configuration template
|
|
||||||
├── package.json
|
|
||||||
├── commands/ # 37 command entry files (one per command); the three
|
|
||||||
│ │ # largest (lastfm, settings, debug) are split into action-family
|
|
||||||
│ │ # modules inside commands/<name>/ subdirectories
|
|
||||||
│ ├── lastfm/ # lastfm action families (account, playback, listening,
|
|
||||||
│ │ # whoknows, info, tags, discovery, help, shared)
|
|
||||||
│ ├── settings/ # settings helpers (utils, channels247, setters)
|
|
||||||
│ └── debug/ # debug helpers (consts, gateway, rejoin, voiceDiagnostic)
|
|
||||||
├── settings/ # Settings system entry points (re-export, migrate, validators)
|
|
||||||
├── storage/ # Runtime data: defaults, modules.json, locales
|
|
||||||
├── docker/ # Docker self-hosting (Dockerfile, compose, entrypoint,
|
|
||||||
│ # config templates, .env.example)
|
|
||||||
└── src/
|
|
||||||
├── core/ # Bot composition
|
|
||||||
│ ├── Bot.mjs # Remix class — boot sequence, service wiring, alone-check,
|
|
||||||
│ │ # presence rotation, WebSocket error guards
|
|
||||||
│ ├── BotVoiceMixin.mjs # Voice-channel resolution, 24/7 player spawning with
|
|
||||||
│ │ # announcements, programmatic leave, shared servers
|
|
||||||
│ ├── Logger.mjs # Structured logger with per-category control
|
|
||||||
│ └── Locale.mjs # i18n translation engine
|
|
||||||
├── commands/ # Command framework layer
|
|
||||||
│ ├── index.mjs # Public surface (re-exports)
|
|
||||||
│ ├── CommandBuilder.mjs # Fluent builder + permission requirements
|
|
||||||
│ ├── Option.mjs # Typed options + flags with validation
|
|
||||||
│ ├── CommandHandler.mjs # Dispatcher: parsing, cooldowns, permission checks
|
|
||||||
│ ├── CommandLoader.mjs # Dynamic command loading + run-handler binding
|
|
||||||
│ ├── HelpHandler.mjs # Text help generation (usage/aliases/options)
|
|
||||||
│ └── PrefixManager.mjs # Per-guild prefix resolution
|
|
||||||
├── ui/ # Message/embed layer
|
|
||||||
│ ├── index.mjs # Public surface (re-exports)
|
|
||||||
│ ├── MessageHandler.mjs # Reply/send/edit embeds, reaction + message observers,
|
|
||||||
│ │ # permission checks, pagination entry
|
|
||||||
│ ├── Wrappers.mjs # Message & Channel wrappers
|
|
||||||
│ ├── Paginators.mjs # PageBuilder, RichPaginator (tabbed), QueuePaginator
|
|
||||||
│ ├── HelpCommand.mjs # Rich tabbed help command (Home/Music/Utilities/Support)
|
|
||||||
│ ├── Permissions.mjs # Required/critical/optional bot permission catalog
|
|
||||||
│ └── Embeds.mjs # Global embed color + message-shape helpers
|
|
||||||
├── voice/ # Gateway & voice-state layer
|
|
||||||
│ ├── VoiceStateCache.mjs # Dual LRU voice-state caches (humans / bots)
|
|
||||||
│ ├── VoiceStateResolver.mjs # Voice-state normalization + humans-in-channel check
|
|
||||||
│ └── gateway/
|
|
||||||
│ ├── index.mjs # Public surface
|
|
||||||
│ ├── GatewayHandler.mjs # Raw WS dispatch, presence rotation, boot recovery
|
|
||||||
│ ├── VoiceStateRouting.mjs # Voice-state update handling, inactivity triggers
|
|
||||||
│ ├── GuildSync.mjs # Guild seeding (cache + REST), guild delete
|
|
||||||
│ └── RejoinManager.mjs # 24/7 rejoin scheduling with retries
|
|
||||||
├── music/ # Player + audio engine layer
|
|
||||||
│ ├── PlayerManager.mjs # Player lifecycle & registry, getPlayer/initPlayer
|
|
||||||
│ ├── PlayerEventsMixin.mjs # Per-player event wiring, scrobbles, broadcasts
|
|
||||||
│ ├── PlayerLifecycleMixin.mjs# Voice checks, prompts, joins, leaves
|
|
||||||
│ ├── LavalinkManager.mjs # lavalink-client wrapper (NodeLink mode)
|
|
||||||
│ ├── probe.mjs # ffprobe wrapper for radio stream metadata
|
|
||||||
│ ├── providers.mjs # 45+ audio source provider definitions
|
|
||||||
│ ├── player/
|
|
||||||
│ │ ├── index.mjs # Public surface (default export: Player)
|
|
||||||
│ │ ├── Player.mjs # Core state machine: join/leave/destroy, controls, 24/7
|
|
||||||
│ │ ├── Queue.mjs # Queue data structure with loop modes + events
|
|
||||||
│ │ ├── PlaybackMixin.mjs # playNext pipeline, track-end timers, lyrics
|
|
||||||
│ │ ├── SearchMixin.mjs # Lavalink search, fallbacks, radio/external builders
|
|
||||||
│ │ └── DisplayMixin.mjs # Now-playing, queue listing, announcements
|
|
||||||
│ └── audio/
|
|
||||||
│ ├── index.mjs # Public surface
|
|
||||||
│ ├── FluxerAudioBridge.mjs # NodeLink streams → LiveKit publishing core
|
|
||||||
│ ├── StreamPipeline.mjs # Magic-byte sniffing, remux, Opus encode
|
|
||||||
│ ├── HttpStreams.mjs # Redirect-following HTTP JSON/stream helpers
|
|
||||||
│ └── WebMOpusMuxer.mjs # Streaming EBML/Matroska muxer (Opus → WebM)
|
|
||||||
├── services/ # Integrations
|
|
||||||
│ ├── FluxerListManager.mjs # FluxerList voters API client (TTL cache)
|
|
||||||
│ ├── TrackOptionsManager.mjs # Per-user per-track start/end times (MySQL + LRU)
|
|
||||||
│ └── lastfm/
|
|
||||||
│ ├── index.mjs # Public surface
|
|
||||||
│ ├── LastFmManager.mjs # Base: config, MySQL pool, shared helpers
|
|
||||||
│ ├── UserStoreMixin.mjs # Linking, sessions, scrobble opt-ins
|
|
||||||
│ ├── ScrobblingMixin.mjs # Scrobble + now-playing
|
|
||||||
│ ├── TrackQueriesMixin.mjs # Track/artist/album/tag/geo/chart queries
|
|
||||||
│ ├── UserQueriesMixin.mjs # User tops, charts, playlists, play categories
|
|
||||||
│ ├── ServerStatsMixin.mjs # Whoknows, crowns, leaderboards, affinity
|
|
||||||
│ ├── constants.mjs # Signed API-call plumbing
|
|
||||||
│ └── urlUtils.mjs # lastfm:// URL parsing
|
|
||||||
├── db/ # Persistence
|
|
||||||
│ ├── Settings.mjs # SettingsManager / ServerSettings / RemoteSettingsManager
|
|
||||||
│ │ # (MySQL-backed, debounced JSON_SET writes)
|
|
||||||
│ └── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers
|
|
||||||
├── utils/ # Cross-layer primitives (leaf layer)
|
|
||||||
│ ├── mixins.mjs # applyMixins — god-class splitting helper
|
|
||||||
│ ├── ShardingUtils.mjs # Shard-aware gateway helpers (2.2/3.0 compatible,
|
|
||||||
│ │ # guild→shard routing, local shard enumeration)
|
|
||||||
│ ├── Utils.mjs # Formatting, validation, ID cleaning
|
|
||||||
│ ├── API.mjs # REST call helpers (status/error wrapping)
|
|
||||||
│ ├── UI.mjs # Shared UI constants (colors)
|
|
||||||
│ └── Helpers247.mjs # 24/7 channel-mode helpers
|
|
||||||
└── dashboard/ # Dashboard backend
|
|
||||||
├── index.mjs # Public surface
|
|
||||||
├── Dashboard.mjs # Redis RPC routing, player/user broadcasts
|
|
||||||
├── RpcHandlersMixin.mjs# Request handlers + authorization checks
|
|
||||||
├── Serializers.mjs # Channel/user/player/command serializers (statics)
|
|
||||||
└── RedisHandler.mjs # Redis pub/sub RPC transport with reconnect handling
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
| 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` |
|
||||||
|
|
||||||
## The Layered Codebase
|
### ⚙️ Server & Voice Settings
|
||||||
|
|
||||||
The rewrite organises the codebase into strict layers with one-way dependencies
|
| Command | Aliases | Description | Example |
|
||||||
(no layer reaches *down* past another):
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `settings` | `247`, `prefix` | View or configure server preferences | `%settings get` |
|
||||||
|
| `join` | `connect` | Connect bot to your voice channel | `%join` |
|
||||||
|
| `leave` | `stop`, `disconnect` | Disconnect bot from voice | `%leave` |
|
||||||
|
| `forceleave` | `fl` | Force disconnect from any channel (Admin) | `%forceleave` |
|
||||||
|
| `radio` | `r` | Browse and play internet radio streams | `%radio list` |
|
||||||
|
| `lyrics` | `ly` | Search or display synced lyrics | `%lyrics` |
|
||||||
|
| `thumbnail` | `thumb` | View high-resolution track thumbnail | `%thumbnail` |
|
||||||
|
| `player` | — | Spawn interactive reaction controller | `%player` |
|
||||||
|
|
||||||
```
|
### 🛠️ Utilities & Diagnostics
|
||||||
index.mjs
|
|
||||||
└── core/ ──────────────► composition root: wires every layer together
|
|
||||||
├── commands/ ─────► command framework (parsing, cooldowns, help)
|
|
||||||
│ └── ui/ ─────► message/embed primitives used by the framework
|
|
||||||
├── ui/ ──── message wrappers, paginators, permissions
|
|
||||||
├── voice/ ──── gateway events, voice-state caches, 24/7 rejoin
|
|
||||||
├── music/ ──── players, queue, audio engine, Lavalink client
|
|
||||||
├── services/ ──── Last.fm, FluxerList, track options
|
|
||||||
├── db/ ──── MySQL settings + dashboard database pool
|
|
||||||
└── dashboard/ ──── Redis-RPC backend
|
|
||||||
```
|
|
||||||
|
|
||||||
**God classes were eliminated.** The five largest modules (Player, PlayerManager,
|
| Command | Aliases | Description |
|
||||||
GatewayHandler, FluxerAudioBridge, LastFmManager, Dashboard) are each split into a
|
|
||||||
small base class plus **concern mixins** — one file per responsibility, applied onto
|
|
||||||
the class at load time via `src/utils/mixins.mjs` (`applyMixins`). All methods keep
|
|
||||||
the same names, so callers (including your own command files and modules) are
|
|
||||||
unaffected.
|
|
||||||
|
|
||||||
**Big commands are grouped the same way.** The three commands that outgrew a
|
|
||||||
single file (`lastfm` 2.5k lines, `settings` 705, `debug` 669) keep their entry
|
|
||||||
file at `commands/<name>.mjs` (same path the loader, `%reload` and help system
|
|
||||||
reference) and move their implementation into `commands/<name>/` — one module per
|
|
||||||
action family, dispatched by the entry's `run()` via per-module action sets:
|
|
||||||
|
|
||||||
```js
|
|
||||||
// commands/lastfm.mjs (entry) — dispatch
|
|
||||||
if (ACCOUNT_ACTIONS.has(action))
|
|
||||||
return runAccountActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action);
|
|
||||||
```
|
|
||||||
|
|
||||||
The loader only reads top-level `*.mjs` files, so the subdirectories are invisible
|
|
||||||
to command discovery; case bodies and helpers were moved verbatim (verified by
|
|
||||||
per-command runtime parity harnesses under `scripts/`), and every entry file keeps
|
|
||||||
its original exports (`playLastFmCategory` is still importable from
|
|
||||||
`commands/lastfm.mjs`). `commands/player.mjs` intentionally stays single-file: it
|
|
||||||
is one cohesive interactive UI flow (a single 500-line `run()` closure) with no
|
|
||||||
seams that could be split without rewriting behavior.
|
|
||||||
|
|
||||||
**Public surfaces are barrels.** Each layer folder has an `index.mjs` that
|
|
||||||
re-exports its public API, so imports stay short and implementation files can move
|
|
||||||
without touching consumers:
|
|
||||||
|
|
||||||
```js
|
|
||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
|
||||||
import { Message, getGlobalColor } from "../src/ui/index.mjs";
|
|
||||||
import Player from "../src/music/player/index.mjs";
|
|
||||||
import { LastFmManager } from "../src/services/lastfm/index.mjs";
|
|
||||||
```
|
|
||||||
|
|
||||||
**Compatibility is drop-in:** `config.json` keys, the MySQL schema, the Redis RPC
|
|
||||||
protocol, command names/aliases, locale files, and the Docker entrypoint
|
|
||||||
(`node index.mjs` at the repository root) are all unchanged from the previous
|
|
||||||
single-layer layout.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Localization
|
|
||||||
|
|
||||||
Remix supports multiple languages out of the box. The locale system loads JSON translation files from `storage/locales/bot/` and serves the appropriate language based on each guild's `locale` setting.
|
|
||||||
|
|
||||||
Currently supported languages:
|
|
||||||
|
|
||||||
| Code | Language |
|
|
||||||
| :--- | :--- |
|
|
||||||
| `en` | English (default) |
|
|
||||||
| `ar-SA` | Arabic |
|
|
||||||
| `de-DE` | German |
|
|
||||||
| `ckb` | Kurdish (Sorani) |
|
|
||||||
| `pt-BR` | Brazilian Portuguese |
|
|
||||||
| `tr` | Turkish |
|
|
||||||
|
|
||||||
To add a new language, place a JSON file in `storage/locales/bot/` following the same key structure as `en.json`, then set the locale per guild with `%settings set locale <code>`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## npm Scripts
|
|
||||||
|
|
||||||
| Script | Command | Description |
|
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `npm start` | `node index.mjs` | Start the bot (single process — default) |
|
| `ping` | `latency` | View gateway latency and WebSocket round-trip |
|
||||||
| `npm run shard` | `node shard.mjs` | Start under the sharding supervisor (optional) |
|
| `stats` | `info`, `botinfo` | View bot uptime, RAM usage, active players, and servers |
|
||||||
| `npm run dev` | `node --inspect index.mjs --trace-warnings` | Start with Node.js inspector |
|
| `invite` | `addbot` | Get bot invite link |
|
||||||
| `npm run migrate` | `node settings/migrate.mjs` | Clone/repair the remote settings table |
|
| `support` | `server` | Get official support community link |
|
||||||
|
| `vote` | — | View and support bot voters on FluxerList |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Credits & License
|
## 🐳 Self-Hosting (Docker Setup)
|
||||||
|
|
||||||
**Development:**
|
The recommended way to run Remix is via Docker Compose. It bundles the bot, MySQL 8.4, Redis, and NodeLink into lightweight, automated containers.
|
||||||
- [ShadowLp174](https://github.com/ShadowLp174) — Lead developer
|
|
||||||
- [NoLogicAlan](https://github.com/NoLogicAlan) — Lead developer
|
|
||||||
- [Fantic](https://github.com/fanticwastaken) — Community Manager
|
|
||||||
|
|
||||||
**Powered by:**
|
### 1. Clone & Configure
|
||||||
- [`@fluxerjs/core`](https://github.com/fluxerjs/core) — Fluxer API client
|
```bash
|
||||||
- [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) — LiveKit voice connections and playback
|
git clone https://github.com/remix-bot/fluxer.git
|
||||||
- [`lavalink-client`](https://www.npmjs.com/package/lavalink-client) — Lavalink/NodeLink client (search + streaming)
|
cd fluxer/docker
|
||||||
- [`NodeLink`](https://github.com/PerformanC/NodeLink) — Lavalink-compatible audio node
|
cp config_example.json config.json
|
||||||
- [`prism-media`](https://github.com/discordjs/prism-media) — Opus encoding and stream demuxing
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Edit Configuration
|
||||||
|
Open `docker/config.json` and insert your bot token:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"token": "YOUR_FLUXER_BOT_TOKEN",
|
||||||
|
"instanceUrl": null,
|
||||||
|
"prefix": "%",
|
||||||
|
"owners": ["YOUR_USER_ID"],
|
||||||
|
"mysql": {
|
||||||
|
"host": "mysql",
|
||||||
|
"port": 3306,
|
||||||
|
"user": "remix",
|
||||||
|
"password": "remix_pw",
|
||||||
|
"database": "remix"
|
||||||
|
},
|
||||||
|
"nodelink": {
|
||||||
|
"host": "nodelink",
|
||||||
|
"port": 3000,
|
||||||
|
"password": "youshallnotpass"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
> [!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
|
||||||
|
```bash
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Monitor Live Logs
|
||||||
|
```bash
|
||||||
|
docker compose logs -f bot
|
||||||
|
```
|
||||||
|
|
||||||
|
*To stop the stack:* `docker compose down`
|
||||||
|
*To update code and rebuild:* `docker compose up -d --build bot`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🏗️ Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
User (%play) ──► Command Handler ──► LavalinkManager (NodeLink Search)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Queue Engine (History + Lossless Navigation)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
FluxerAudioBridge (In-Process Opus / WebM)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
LiveKit Voice Connection (@fluxerjs/voice)
|
||||||
|
```
|
||||||
|
|
||||||
|
* **Zero Re-Encode Pipeline:** Audio tracks from NodeLink stream as native WebM/Opus straight into LiveKit voice rooms.
|
||||||
|
* **In-Process Seeks:** Byte-level cluster/page seeking (`StreamPositioner`) eliminates FFmpeg subprocess requirements.
|
||||||
|
* **Safe HTTP Execution:** All direct stream URLs pass through DNS verification and private-network IP filters (`SafeHttp`) to prevent SSRF vulnerabilities.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🌍 Supported Languages
|
||||||
|
|
||||||
|
Remix automatically adapts to each server's configured locale (`%settings set locale <code>`):
|
||||||
|
|
||||||
|
| Flag | Code | Language | Native Name |
|
||||||
|
| :---:| :---: | :--- | :--- |
|
||||||
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/bcbcbdfb-8bbf-4fcf-a778-5d324ad47c9f" />| `en` | English | English (Default) |
|
||||||
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/2e3cc42a-47e5-4d6e-9b99-c6f5534cee87" />| `ar-SA` | Arabic | العربية |
|
||||||
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/44bc9ba4-0bee-4141-96b6-d144e4c5089a" />| `ckb` | Central Kurdish (Sorani) | کوردیی ناوەندی |
|
||||||
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/6dddb041-52ec-4dca-ab37-22d1ef3cc78d" />| `tr` | Turkish | Türkçe |
|
||||||
|
|<img width="40" height="40" alt="image" src="https://github.com/user-attachments/assets/558a97e5-579e-4bca-8cbb-a684a5678a1a" />| `de-DE` | German | Deutsch |
|
||||||
|
|<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 | 繁體中文 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 👥 Credits & Team
|
||||||
|
|
||||||
|
* **[ShadowLp174](https://github.com/ShadowLp174)** — Lead Developer
|
||||||
|
* **[NoLogicAlan](https://github.com/NoLogicAlan)** — Lead Developer
|
||||||
|
* **[Fantic](https://github.com/fanticwastaken)** — Community Manager
|
||||||
|
|
||||||
|
**Core Libraries:**
|
||||||
|
* [`@fluxerjs/core`](https://github.com/fluxerjs/core) & [`@fluxerjs/voice`](https://github.com/fluxerjs/voice) — Fluxer API & LiveKit voice
|
||||||
|
* [`NodeLink`](https://github.com/PerformanC/NodeLink) — High-performance audio node
|
||||||
|
* [`lavalink-client`](https://www.npmjs.com/package/lavalink-client) — Audio client & search interface
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
© 2026 Remix. Code licensed under the <a href="LICENSE">MIT License</a>.<br>
|
© 2026 Remix. Licensed under the <a href="LICENSE">MIT License</a>.<br>
|
||||||
<em>The Remix name, logo, and branding are proprietary and may not be reused.</em>
|
<em>The Remix name, logo, and branding are proprietary and may not be reused.</em>
|
||||||
</p>
|
</p>
|
||||||
+390
-95
@@ -5,7 +5,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 { getGlobalColor } from "../src/ui/index.mjs";
|
|
||||||
import { logger } from "../src/core/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the autoplay command. */
|
/** @type {CommandBuilder} @description Command definition for the autoplay command. */
|
||||||
@@ -16,16 +15,212 @@ 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). */
|
||||||
|
const MAX_TAG_CHECKS = 16;
|
||||||
|
/** Last.fm tag weights are 0-100 relative to the top tag; ignore the long tail. */
|
||||||
|
const TAG_MIN_COUNT = 30;
|
||||||
|
/** Number of genre tags kept per artist. */
|
||||||
|
const TAG_KEEP = 6;
|
||||||
|
const TAG_CACHE_MAX = 500;
|
||||||
|
const TAG_CACHE_TTL_MS = 6 * 60 * 60_000;
|
||||||
|
/** Cap on remembered autoplay-picked video IDs per player. */
|
||||||
|
const PICKED_VIDS_MAX = 100;
|
||||||
|
|
||||||
|
/** Last.fm tags that say nothing about genre (normalised form). */
|
||||||
|
const NOISE_TAGS = new Set([
|
||||||
|
"seenlive", "favorites", "favourites", "favorite", "favourite", "love", "awesome", "beautiful",
|
||||||
|
"malevocalists", "femalevocalists", "malevocalist", "femalevocalist", "good", "amazing", "best",
|
||||||
|
"cool", "music", "songs", "underrated", "allsongs", "mymusic",
|
||||||
|
]);
|
||||||
|
/** Broad tags that many unrelated genres share — never enough on their own to match. */
|
||||||
|
const WEAK_TAGS = new Set([
|
||||||
|
"pop", "rock", "electronic", "dance", "alternative", "indie", "hiphop", "rap", "rnb",
|
||||||
|
"electropop", "metal", "popmusic",
|
||||||
|
]);
|
||||||
|
|
||||||
|
/** artist (normalised) -> { tags: Set<string>, ts } */
|
||||||
|
const tagCache = new Map();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalise a tag/artist string for comparison ("K-Pop" and "kpop" become "kpop").
|
||||||
|
* @param {string} s - Raw string.
|
||||||
|
* @returns {string} Lower-case letters and digits only.
|
||||||
|
*/
|
||||||
|
function norm(s) {
|
||||||
|
return String(s ?? "").toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]/gu, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Strip YouTube channel decorations from an artist name.
|
||||||
|
* @param {string} s - Raw artist/channel name.
|
||||||
|
* @returns {string} Cleaned artist name.
|
||||||
|
*/
|
||||||
|
function cleanArtist(s) {
|
||||||
|
return String(s ?? "")
|
||||||
|
.replace(/\s*-\s*topic$/i, "")
|
||||||
|
.replace(/\s*vevo$/i, "")
|
||||||
|
.replace(/\s*official$/i, "")
|
||||||
|
.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Best-effort artist name of an internal track object.
|
||||||
|
* @param {object|null} t - Track.
|
||||||
|
* @returns {string|null} Artist name, or null.
|
||||||
|
*/
|
||||||
|
function artistOf(t) {
|
||||||
|
let a = t?.lastfm?.artist ?? t?.requestedArtist ?? t?.artist ?? t?.artists?.[0]?.name ?? t?.author?.name ?? null;
|
||||||
|
if (a && typeof a !== "string") a = a.name ?? null;
|
||||||
|
a = a ? cleanArtist(a) : null;
|
||||||
|
return a || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Best-effort title of an internal track object.
|
||||||
|
* @param {object|null} t - Track.
|
||||||
|
* @returns {string|null} Title, or null.
|
||||||
|
*/
|
||||||
|
function titleOf(t) {
|
||||||
|
return t?.lastfm?.name ?? t?.requestedTitle ?? t?.title ?? t?.name ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether two artist names refer to the same artist ("TWICE" vs "TWICE Japan").
|
||||||
|
* @param {string|null} a - First name.
|
||||||
|
* @param {string|null} b - Second name.
|
||||||
|
* @returns {boolean} True if they match.
|
||||||
|
*/
|
||||||
|
function artistMatches(a, b) {
|
||||||
|
const x = norm(a), y = norm(b);
|
||||||
|
if (!x || !y) return false;
|
||||||
|
if (x === y) return true;
|
||||||
|
const [short, long] = x.length <= y.length ? [x, y] : [y, x];
|
||||||
|
return short.length >= 3 && long.includes(short);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fisher-Yates shuffle (copy).
|
||||||
|
* @template T
|
||||||
|
* @param {T[]} arr - Input array.
|
||||||
|
* @returns {T[]} Shuffled copy.
|
||||||
|
*/
|
||||||
|
function shuffle(arr) {
|
||||||
|
const a = [...arr];
|
||||||
|
for (let i = a.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(Math.random() * (i + 1));
|
||||||
|
[a[i], a[j]] = [a[j], a[i]];
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether the genre tags of an artist are already cached (a lookup would be free).
|
||||||
|
* @param {string} artist - Artist name.
|
||||||
|
* @returns {boolean} True if cached and fresh.
|
||||||
|
*/
|
||||||
|
function hasFreshTags(artist) {
|
||||||
|
const hit = tagCache.get(norm(artist));
|
||||||
|
return !!hit && Date.now() - hit.ts < TAG_CACHE_TTL_MS;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Genre tags for an artist from Last.fm: top tags with real weight, minus
|
||||||
|
* noise ("seen live", decades, ...). Cached across players.
|
||||||
|
* @param {object} lf - Last.fm manager (enabled).
|
||||||
|
* @param {string} artist - Artist name.
|
||||||
|
* @returns {Promise<Set<string>>} Normalised genre tags (empty if unknown).
|
||||||
|
*/
|
||||||
|
async function getGenreTags(lf, artist) {
|
||||||
|
const key = norm(artist);
|
||||||
|
if (!key) return new Set();
|
||||||
|
const hit = tagCache.get(key);
|
||||||
|
if (hit && Date.now() - hit.ts < TAG_CACHE_TTL_MS) return hit.tags;
|
||||||
|
|
||||||
|
const tags = new Set();
|
||||||
|
try {
|
||||||
|
const list = await lf.getArtistTopTags(cleanArtist(artist), 12);
|
||||||
|
for (const t of list) {
|
||||||
|
if ((t.count ?? 0) < TAG_MIN_COUNT) continue;
|
||||||
|
const n = norm(t.name);
|
||||||
|
if (!n || NOISE_TAGS.has(n) || /^(?:19|20)?\d{2}s?$/.test(n)) continue;
|
||||||
|
tags.add(n);
|
||||||
|
if (tags.size >= TAG_KEEP) break;
|
||||||
|
}
|
||||||
|
} catch (e) { logger.warn("[Autoplay] Tag lookup failed:", e?.message); }
|
||||||
|
|
||||||
|
if (tags.size) {
|
||||||
|
if (tagCache.size >= TAG_CACHE_MAX) tagCache.delete(tagCache.keys().next().value);
|
||||||
|
tagCache.set(key, { tags, ts: Date.now() });
|
||||||
|
}
|
||||||
|
return tags;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Do a candidate's tags share the seed's genre? Broad tags ("pop", "rock")
|
||||||
|
* only count when the seed has nothing more specific.
|
||||||
|
* @param {Set<string>} seedTags - Genre tags of the seed artist.
|
||||||
|
* @param {Set<string>} candTags - Genre tags of the candidate artist.
|
||||||
|
* @returns {boolean} True if the genres overlap.
|
||||||
|
*/
|
||||||
|
function genreOverlaps(seedTags, candTags) {
|
||||||
|
const strong = [...seedTags].filter(t => !WEAK_TAGS.has(t));
|
||||||
|
const need = strong.length ? strong : [...seedTags];
|
||||||
|
return need.some(t => candTags.has(t));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Track whether the player's last track was picked by autoplay, and keep the
|
||||||
|
* "seed" (the most recent track a human chose) up to date. Recommendations are
|
||||||
|
* always built from the seed, never from a previous autoplay pick, so a single
|
||||||
|
* off-genre result can no longer snowball into a different genre.
|
||||||
|
* @param {object} p - The player instance.
|
||||||
|
* @param {object|null} lastTrack - The track that just finished.
|
||||||
|
* @returns {boolean} True if lastTrack was itself an autoplay pick.
|
||||||
|
*/
|
||||||
|
function updateSeed(p, lastTrack) {
|
||||||
|
if (!lastTrack) return false;
|
||||||
|
const vid = extractVideoId(lastTrack);
|
||||||
|
const picked = !!lastTrack._autoplayPicked || (!!vid && !!p._autoplayPickedVids?.has(vid));
|
||||||
|
if (picked) return true;
|
||||||
|
|
||||||
|
const key = vid ?? `${norm(artistOf(lastTrack))}|${norm(titleOf(lastTrack))}`;
|
||||||
|
if (!p._autoplaySeed || p._autoplaySeedKey !== key) {
|
||||||
|
p._autoplaySeed = lastTrack;
|
||||||
|
p._autoplaySeedKey = key;
|
||||||
|
p._autoplaySeedTags = null;
|
||||||
|
p._autoplayMixPools?.clear();
|
||||||
|
p._autoplayPreferredPoolVid = null;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark a track as chosen by autoplay (so it is never mistaken for a seed).
|
||||||
|
* @param {object} p - The player instance.
|
||||||
|
* @param {object} track - The picked track.
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
function markPicked(p, track) {
|
||||||
|
track._autoplayPicked = true;
|
||||||
|
const vid = extractVideoId(track);
|
||||||
|
if (!vid) return;
|
||||||
|
const set = p._autoplayPickedVids ?? new Set();
|
||||||
|
p._autoplayPickedVids = set;
|
||||||
|
set.delete(vid);
|
||||||
|
set.add(vid);
|
||||||
|
if (set.size > PICKED_VIDS_MAX) set.delete(set.values().next().value);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Extract a YouTube video ID from a track's videoId field or URL.
|
* Extract a YouTube video ID from a track's videoId field or URL.
|
||||||
@@ -60,27 +255,33 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Take a random acceptable candidate from a cached mix pool, if one exists and
|
* Take an acceptable candidate from a cached mix pool, if one exists and is
|
||||||
* is fresh. Candidates already picked are excluded via the autoplay history.
|
* fresh. Candidates already played are excluded via the autoplay history;
|
||||||
|
* candidates failing the genre guard are dropped from the pool.
|
||||||
* @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.
|
||||||
* @returns {object|null} An acceptable track from the pool, or null.
|
* @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.
|
||||||
*/
|
*/
|
||||||
function takeFromPool(p, videoId) {
|
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);
|
||||||
@@ -89,12 +290,16 @@ function takeFromPool(p, videoId) {
|
|||||||
pools.delete(videoId);
|
pools.delete(videoId);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
const ok = pool.tracks.filter(t => isCandidateOk(p, t));
|
const ok = shuffle(pool.tracks.filter(t => isCandidateOk(p, t, allowOldHistory)));
|
||||||
if (!ok.length) {
|
const rejected = new Set();
|
||||||
pools.delete(videoId);
|
let found = null;
|
||||||
return null;
|
for (const t of ok) {
|
||||||
|
if (!guard || await guard(t)) { found = t; break; }
|
||||||
|
rejected.add(t);
|
||||||
}
|
}
|
||||||
return ok[Math.floor(Math.random() * Math.min(PICK_POOL, ok.length))];
|
if (rejected.size) pool.tracks = pool.tracks.filter(t => !rejected.has(t));
|
||||||
|
if (!found && !pool.tracks.some(t => isCandidateOk(p, t, allowOldHistory))) pools.delete(videoId);
|
||||||
|
return found;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -119,101 +324,176 @@ 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));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve a query via the player's Lavalink search and return a random acceptable
|
* Search and return the first acceptable result that passes every check.
|
||||||
* candidate from the top results.
|
|
||||||
* @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.
|
||||||
* @param {string} provider - Provider shorthand key ("yt", "ytm", ...).
|
* @param {(t: object) => (boolean|Promise<boolean>)} accept - Extra acceptance test (artist/genre).
|
||||||
* @returns {Promise<object|null>} An acceptable track, or null.
|
* @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.
|
||||||
*/
|
*/
|
||||||
async function pickFromQuery(p, query, provider = "ytm") {
|
async function searchAccepted(p, query, accept, provider = "ytm", allowOldHistory = false) {
|
||||||
const ok = await resolveCandidates(p, query, provider);
|
const found = await resolveCandidates(p, query, provider, allowOldHistory);
|
||||||
if (!ok.length) return null;
|
for (const t of shuffle(found.slice(0, PICK_POOL))) {
|
||||||
return ok[Math.floor(Math.random() * Math.min(PICK_POOL, ok.length))];
|
if (await accept(t)) return t;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* Choose the next track. Anchored to the seed while allowing smooth progression
|
||||||
|
* and infinite fallback so playback never halts after a handful of tracks.
|
||||||
* @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.
|
||||||
* @returns {Promise<object|null>} The chosen track, or null if all strategies failed.
|
* @returns {Promise<object|null>} The chosen track, or null if all strategies failed.
|
||||||
*/
|
*/
|
||||||
async function pickAutoplayTrack(p, ctx, lastTrack) {
|
export async function pickAutoplayTrack(p, ctx, lastTrack) {
|
||||||
const artist = lastTrack?.lastfm?.artist ?? lastTrack?.requestedArtist ?? lastTrack?.artist
|
const lastWasPicked = updateSeed(p, lastTrack);
|
||||||
?? lastTrack?.artists?.[0]?.name ?? lastTrack?.author?.name ?? null;
|
const seed = p._autoplaySeed ?? lastTrack;
|
||||||
const name = lastTrack?.lastfm?.name ?? lastTrack?.requestedTitle ?? lastTrack?.title ?? lastTrack?.name ?? null;
|
const seedArtist = artistOf(seed);
|
||||||
const videoId = extractVideoId(lastTrack);
|
const seedName = titleOf(seed);
|
||||||
|
const seedVid = extractVideoId(seed);
|
||||||
|
const lastVid = extractVideoId(lastTrack);
|
||||||
|
const lf = ctx?.lastfm?.enabled ? ctx.lastfm : null;
|
||||||
|
|
||||||
if (p._autoplayPreferredPoolVid) {
|
let seedTags = p._autoplaySeedTags ?? null;
|
||||||
const pooled = takeFromPool(p, p._autoplayPreferredPoolVid);
|
if (!seedTags && lf && seedArtist) {
|
||||||
if (pooled) return pooled;
|
const t = await getGenreTags(lf, seedArtist);
|
||||||
p._autoplayPreferredPoolVid = null;
|
if (t.size) { seedTags = t; p._autoplaySeedTags = t; }
|
||||||
}
|
}
|
||||||
|
|
||||||
if (videoId) {
|
const budget = { left: MAX_TAG_CHECKS };
|
||||||
const cached = takeFromPool(p, videoId);
|
/** True if candidate matches genre tags or tag budget is exhausted. */
|
||||||
if (cached) {
|
const genreOk = async (t) => {
|
||||||
p._autoplayPreferredPoolVid = videoId;
|
if (!lf || !seedTags?.size) return true;
|
||||||
return cached;
|
const ca = artistOf(t);
|
||||||
|
if (!ca) return true;
|
||||||
|
if (artistMatches(ca, seedArtist)) return true;
|
||||||
|
if (!hasFreshTags(ca)) {
|
||||||
|
if (budget.left <= 0) return true;
|
||||||
|
budget.left--;
|
||||||
}
|
}
|
||||||
|
return genreOverlaps(seedTags, await getGenreTags(lf, ca));
|
||||||
|
};
|
||||||
|
|
||||||
|
const finish = (track) => {
|
||||||
|
p._autoplayPreferredPoolVid = null;
|
||||||
|
return track;
|
||||||
|
};
|
||||||
|
|
||||||
|
/* Check pre-resolved mix pools first */
|
||||||
|
const vidsToCheck = [seedVid, lastVid].filter(Boolean);
|
||||||
|
for (const v of vidsToCheck) {
|
||||||
|
const pooled = await takeFromPool(p, v, genreOk);
|
||||||
|
if (pooled) { p._autoplayPreferredPoolVid = v; return pooled; }
|
||||||
}
|
}
|
||||||
|
|
||||||
const lf = ctx?.lastfm;
|
const tryLastfmSimilar = async () => {
|
||||||
if (lf?.enabled && artist && name) {
|
const bases = [seed];
|
||||||
try {
|
if (lastTrack && (artistOf(lastTrack) !== seedArtist || titleOf(lastTrack) !== seedName)) {
|
||||||
const similar = await lf.getSimilarTracks(artist, name, 10);
|
bases.push(lastTrack);
|
||||||
for (let i = 0; i < Math.min(4, similar.length); i++) {
|
}
|
||||||
const pick = similar[Math.floor(Math.random() * Math.min(3, similar.length))];
|
for (const base of bases) {
|
||||||
const track = await pickFromQuery(p, `${pick.name} ${pick.artist}`.trim(), "ytm");
|
const bArtist = artistOf(base), bName = titleOf(base);
|
||||||
if (track) {
|
if (!bArtist || !bName) continue;
|
||||||
p._autoplayPreferredPoolVid = null;
|
try {
|
||||||
return track;
|
const similar = await lf.getSimilarTracks(bArtist, bName, 30);
|
||||||
|
const picks = shuffle(similar.slice(0, 15)).slice(0, 5);
|
||||||
|
for (const pick of picks) {
|
||||||
|
const track = await searchAccepted(
|
||||||
|
p, `${pick.name} ${pick.artist}`.trim(),
|
||||||
|
async (t) => artistMatches(artistOf(t), pick.artist) && await genreOk(t),
|
||||||
|
);
|
||||||
|
if (track) return track;
|
||||||
}
|
}
|
||||||
}
|
} catch (e) { logger.warn("[Autoplay] Last.fm similar-tracks strategy failed:", e?.message); }
|
||||||
} catch (e) { logger.warn("[Autoplay] Last.fm strategy failed:", e?.message); }
|
}
|
||||||
}
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
if (artist) {
|
const tryLastfmArtists = async () => {
|
||||||
try {
|
const artists = [seedArtist, artistOf(lastTrack)].filter(Boolean);
|
||||||
const track = await pickFromQuery(p, `${artist} songs`, "ytm");
|
for (const aName of artists) {
|
||||||
if (track) {
|
try {
|
||||||
p._autoplayPreferredPoolVid = null;
|
const similar = await lf.getSimilarArtists(aName, 12);
|
||||||
return track;
|
for (const a of shuffle(similar.filter(x => x.name)).slice(0, 4)) {
|
||||||
}
|
const track = await searchAccepted(
|
||||||
} catch (e) { logger.warn("[Autoplay] Artist strategy failed:", e?.message); }
|
p, `${a.name} songs`,
|
||||||
}
|
async (t) => artistMatches(artistOf(t), a.name) && await genreOk(t),
|
||||||
if (name) {
|
);
|
||||||
try {
|
if (track) return track;
|
||||||
const track = await pickFromQuery(p, `${name}`, "ytm");
|
}
|
||||||
if (track) {
|
} catch (e) { logger.warn("[Autoplay] Last.fm similar-artists strategy failed:", e?.message); }
|
||||||
p._autoplayPreferredPoolVid = null;
|
}
|
||||||
return track;
|
return null;
|
||||||
}
|
};
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (videoId) {
|
const trySameArtist = async () => {
|
||||||
try {
|
const artists = [seedArtist, artistOf(lastTrack)].filter(Boolean);
|
||||||
const mixUrl = `https://www.youtube.com/watch?v=${videoId}&list=RD${videoId}`;
|
for (const a of artists) {
|
||||||
const candidates = await resolveCandidates(p, mixUrl, "yt");
|
try {
|
||||||
if (candidates.length) {
|
const track = await searchAccepted(p, `${a} songs`, (t) => artistMatches(artistOf(t), a));
|
||||||
storePool(p, videoId, candidates);
|
if (track) return track;
|
||||||
p._autoplayPreferredPoolVid = videoId;
|
const trackHits = await searchAccepted(p, `${a} top tracks`, (t) => artistMatches(artistOf(t), a));
|
||||||
return candidates[Math.floor(Math.random() * Math.min(PICK_POOL, candidates.length))];
|
if (trackHits) return trackHits;
|
||||||
}
|
} catch (e) { logger.warn("[Autoplay] Artist strategy failed:", e?.message); }
|
||||||
} catch (e) { logger.warn("[Autoplay] Mix strategy failed:", e?.message); }
|
}
|
||||||
}
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const tryMix = async () => {
|
||||||
|
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 {
|
||||||
|
for (const v of vidsToCheck) {
|
||||||
|
const pooled = await takeFromPool(p, v, null, true);
|
||||||
|
if (pooled) return pooled;
|
||||||
|
}
|
||||||
|
const q = lastTrack ? `${artistOf(lastTrack) || seedArtist} radio` : `${seedArtist} music`;
|
||||||
|
const fallbackTrack = await searchAccepted(p, q, () => true, "ytm", true);
|
||||||
|
if (fallbackTrack) return fallbackTrack;
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
|
||||||
|
const order = lf
|
||||||
|
? [tryLastfmSimilar, tryLastfmArtists, trySameArtist, tryMix, tryFallback]
|
||||||
|
: [tryMix, trySameArtist, tryFallback];
|
||||||
|
|
||||||
|
for (const strat of order) {
|
||||||
|
const track = await strat();
|
||||||
|
if (track) return strat === tryMix ? track : finish(track);
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,7 +511,7 @@ function pickSerialized(p, ctx, lastTrack) {
|
|||||||
const run = async () => {
|
const run = async () => {
|
||||||
try {
|
try {
|
||||||
const track = await pickAutoplayTrack(p, ctx, lastTrack);
|
const track = await pickAutoplayTrack(p, ctx, lastTrack);
|
||||||
if (track) rememberTrack(p, track);
|
if (track) { rememberTrack(p, track); markPicked(p, track); }
|
||||||
return track;
|
return track;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[Autoplay] Pick error:", e?.message);
|
logger.warn("[Autoplay] Pick error:", e?.message);
|
||||||
@@ -270,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) {
|
||||||
@@ -331,33 +612,47 @@ export async function run(msg, data) {
|
|||||||
const p = await this.getPlayer(msg, true, true, false);
|
const p = await this.getPlayer(msg, true, true, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
|
|
||||||
|
const prefix = this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guildId) || "%";
|
||||||
|
|
||||||
p._autoplay = !p._autoplay;
|
p._autoplay = !p._autoplay;
|
||||||
|
|
||||||
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(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg.reply({
|
const embed = new EmbedBuilder()
|
||||||
embeds: [new EmbedBuilder()
|
.setColor(0xe9196c)
|
||||||
.setColor(getGlobalColor())
|
.setAuthor({ name: `🔁 ${this.t(msg, "responses.autoplay.autoplayTitleEnabled")}` })
|
||||||
.setDescription(this.t(msg, "responses.autoplay.enabled"))]
|
.setTitle(this.t(msg, "responses.autoplay.statusActive"))
|
||||||
});
|
.setDescription(this.t(msg, "responses.autoplay.autoplayDescEnabled"))
|
||||||
|
.setFooter({ text: `${this.t(msg, "responses.autoplay.autoplayEngine")} • ${this.t(msg, "responses.autoplay.disableHint", { prefix })}` });
|
||||||
|
|
||||||
|
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;
|
||||||
p._autoplayPickChain = null;
|
p._autoplayPickChain = null;
|
||||||
p._autoplayQueueEndPicking = false;
|
p._autoplayQueueEndPicking = false;
|
||||||
|
p._autoplaySeed = null;
|
||||||
|
p._autoplaySeedKey = null;
|
||||||
|
p._autoplaySeedTags = null;
|
||||||
|
p._autoplayPickedVids = null;
|
||||||
|
|
||||||
return msg.reply({
|
const embed = new EmbedBuilder()
|
||||||
embeds: [new EmbedBuilder()
|
.setColor(0xe9196c)
|
||||||
.setColor(getGlobalColor())
|
.setAuthor({ name: `⏹️ ${this.t(msg, "responses.autoplay.autoplayTitleDisabled")}` })
|
||||||
.setDescription(this.t(msg, "responses.autoplay.disabled"))]
|
.setTitle(this.t(msg, "responses.autoplay.statusDisabled"))
|
||||||
});
|
.setDescription(this.t(msg, "responses.autoplay.autoplayDescDisabled"))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.autoplay.enableHint", { prefix }) });
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/bassboost
|
||||||
|
* @description Quick equalizer bass boost filter with low, medium, and hard presets.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
|
export const BASSBOOST_PRESETS = {
|
||||||
|
low: {
|
||||||
|
label: "Low",
|
||||||
|
equalizer: [
|
||||||
|
{ band: 0, gain: 0.25 },
|
||||||
|
{ band: 1, gain: 0.20 },
|
||||||
|
{ band: 2, gain: 0.15 },
|
||||||
|
{ band: 3, gain: 0.10 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
medium: {
|
||||||
|
label: "Medium",
|
||||||
|
equalizer: [
|
||||||
|
{ band: 0, gain: 0.60 },
|
||||||
|
{ band: 1, gain: 0.70 },
|
||||||
|
{ band: 2, gain: 0.50 },
|
||||||
|
{ band: 3, gain: 0.25 },
|
||||||
|
{ band: 4, gain: 0.00 },
|
||||||
|
{ band: 5, gain: -0.25 },
|
||||||
|
{ band: 6, gain: -0.45 },
|
||||||
|
{ band: 7, gain: -0.55 },
|
||||||
|
{ band: 8, gain: -0.60 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
hard: {
|
||||||
|
label: "Hard",
|
||||||
|
equalizer: [
|
||||||
|
{ band: 0, gain: 1.00 },
|
||||||
|
{ band: 1, gain: 1.10 },
|
||||||
|
{ band: 2, gain: 0.80 },
|
||||||
|
{ band: 3, gain: 0.50 },
|
||||||
|
{ band: 4, gain: 0.25 },
|
||||||
|
{ band: 5, gain: -0.20 },
|
||||||
|
{ band: 6, gain: -0.45 },
|
||||||
|
{ band: 7, gain: -0.65 },
|
||||||
|
{ band: 8, gain: -0.80 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @type {CommandBuilder}
|
||||||
|
* @description Command definition for the bassboost command.
|
||||||
|
*/
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("bassboost")
|
||||||
|
.setDescription("Apply a low, medium, or hard bass boost equalizer effect.", "commands.bassboost")
|
||||||
|
.setCategory("music")
|
||||||
|
.addChoiceOption(o =>
|
||||||
|
o.setName("level")
|
||||||
|
.setDescription("Bass boost level: 'low', 'medium', 'hard', or 'off'.", "options.bassboost.level")
|
||||||
|
.addChoices("low", "medium", "hard", "off")
|
||||||
|
.setDefault("medium")
|
||||||
|
)
|
||||||
|
.addAliases("bb", "bass");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run handler for the bassboost command.
|
||||||
|
*
|
||||||
|
* @param {object} message - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message, data) {
|
||||||
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
const current = p.queue?.getCurrent();
|
||||||
|
const levelArg = data.get("level")?.value?.toLowerCase() || "medium";
|
||||||
|
const prefix = this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) || "%";
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder().setColor(0xe9196c);
|
||||||
|
|
||||||
|
if (levelArg === "off" || levelArg === "none" || levelArg === "reset") {
|
||||||
|
await p.applyFilter({}, null);
|
||||||
|
embed.setAuthor({ name: `🔊 ${this.t(message, "responses.bassboost.eqTitle")}` })
|
||||||
|
.setTitle(this.t(message, "responses.bassboost.offTitle"))
|
||||||
|
.setDescription(this.t(message, "responses.bassboost.disabled"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.bassboost.offFooter", { prefix }) });
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const preset = BASSBOOST_PRESETS[levelArg] || BASSBOOST_PRESETS.medium;
|
||||||
|
const filterMeta = {
|
||||||
|
key: `bassboost_${levelArg}`,
|
||||||
|
label: `Bass Boost (${preset.label})`,
|
||||||
|
emoji: "🔊",
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await p.applyFilter({ equalizer: preset.equalizer }, filterMeta);
|
||||||
|
if (!res.ok) {
|
||||||
|
embed.setDescription(this.t(message, "responses.bassboost.failed", { reason: res.reason || "Unknown error" }));
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
let desc = this.t(message, "responses.bassboost.applied", { level: preset.label });
|
||||||
|
if (current?.title) {
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
const authorStr = rawAuthor ? ` • ${rawAuthor}` : "";
|
||||||
|
desc += `\n**${Utils.truncate(current.title, 45)}**${authorStr}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const subBassText = this.t(message, "responses.bassboost.subBass") || "Sub-Bass";
|
||||||
|
const midBassText = this.t(message, "responses.bassboost.midBass") || "Mid-Bass";
|
||||||
|
const highText = this.t(message, "responses.bassboost.high") || "High";
|
||||||
|
|
||||||
|
const gainSub = levelArg === "hard" ? "+1.10 dB" : levelArg === "low" ? "+0.25 dB" : "+0.70 dB";
|
||||||
|
const gainMid = levelArg === "hard" ? "+0.80 dB" : levelArg === "low" ? "+0.15 dB" : "+0.50 dB";
|
||||||
|
const gainHigh = levelArg === "hard" ? "-0.80 dB" : levelArg === "low" ? "+0.00 dB" : "-0.65 dB";
|
||||||
|
|
||||||
|
desc += `\n\n` + "`" + `${subBassText}: ${gainSub} │ ${midBassText}: ${gainMid} │ ${highText}: ${gainHigh}` + "`";
|
||||||
|
|
||||||
|
embed
|
||||||
|
.setAuthor({ name: `🔊 ${this.t(message, "responses.bassboost.eqTitle")}` })
|
||||||
|
.setTitle(this.t(message, "responses.bassboost.activeTitle", { level: preset.label }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(message, "responses.bassboost.resetHint", { prefix }) });
|
||||||
|
|
||||||
|
if (current?.thumbnail) {
|
||||||
|
embed.setThumbnail(current.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
+39
-8
@@ -5,7 +5,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 { getGlobalColor } from "../src/ui/index.mjs";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
@@ -13,24 +12,56 @@ import { getGlobalColor } from "../src/ui/index.mjs";
|
|||||||
*/
|
*/
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("clear")
|
.setName("clear")
|
||||||
.setDescription("Remove all songs from the queue.", "commands.clear")
|
.setDescription("Remove all songs, or a slice of songs, from the queue.", "commands.clear")
|
||||||
.addAliases("c")
|
.addAliases("c")
|
||||||
.setCategory("music");
|
.setCategory("music")
|
||||||
|
.addNumberOption(o =>
|
||||||
|
o.setName("from")
|
||||||
|
.setDescription("Starting queue position to clear from (optional, 1-based).")
|
||||||
|
.setRequired(false)
|
||||||
|
)
|
||||||
|
.addNumberOption(o =>
|
||||||
|
o.setName("to")
|
||||||
|
.setDescription("Ending queue position to clear to (optional, 1-based).")
|
||||||
|
.setRequired(false)
|
||||||
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run handler for the clear command.
|
* Run handler for the clear command.
|
||||||
* Clears the entire queue and sends a confirmation embed.
|
* Clears the entire queue, or a specified range of tracks, and sends a confirmation embed.
|
||||||
*
|
*
|
||||||
* @param {object} msg - The command message wrapper.
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} [data] - Parsed options.
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
export async function run(msg) {
|
export async function run(msg, data) {
|
||||||
const p = await this.getPlayer(msg, false, false, false);
|
const p = await this.getPlayer(msg, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
|
|
||||||
|
const rawFrom = data?.get?.("from")?.value;
|
||||||
|
const rawTo = data?.get?.("to")?.value;
|
||||||
|
const fromVal = (typeof rawFrom === "number" && Number.isFinite(rawFrom)) ? rawFrom : null;
|
||||||
|
const toVal = (typeof rawTo === "number" && Number.isFinite(rawTo)) ? rawTo : null;
|
||||||
|
|
||||||
|
if (fromVal !== null) {
|
||||||
|
if (fromVal < 1) return msg.replyEmbed("Queue position must be 1 or greater.").catch(() => {});
|
||||||
|
const startIdx = Math.floor(fromVal) - 1;
|
||||||
|
const endIdx = (toVal !== null && toVal >= 1) ? Math.floor(toVal) - 1 : startIdx;
|
||||||
|
const res = p.removeRange(startIdx, endIdx);
|
||||||
|
return msg.replyEmbed(res).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const count = p.queue.size();
|
||||||
p.clear();
|
p.clear();
|
||||||
|
const pluralStr = count === 1 ? this.t(msg, "responses.play.trackSingle") : this.t(msg, "responses.play.trackPlural");
|
||||||
|
const prefix = this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guildId) || "%";
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setDescription(this.t(msg, "responses.clear.cleared"))
|
.setAuthor({ name: `🗑️ ${this.t(msg, "responses.clear.clearedTitle")}` })
|
||||||
;
|
.setTitle(this.t(msg, "responses.clear.cleared"))
|
||||||
|
.setDescription(this.t(msg, "responses.clear.clearedSummary", { count, plural: pluralStr }))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.clear.footerHint", { prefix }) });
|
||||||
|
|
||||||
msg.reply({ embeds: [embed] }).catch(() => {});
|
msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+3
-2
@@ -55,9 +55,10 @@ export async function run(msg, data) {
|
|||||||
default: {
|
default: {
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(ERROR_COLOR)
|
.setColor(ERROR_COLOR)
|
||||||
.setTitle("Debug — Unknown Target")
|
.setAuthor({ name: this.t(msg, "responses.debug.author") })
|
||||||
|
.setTitle(this.t(msg, "responses.debug.unknownTitle"))
|
||||||
.setDescription(`Unknown debug target: \`${target}\`.\nValid options: \`voice\`, \`voice-rejoin\`, \`247-rejoin\`.`)
|
.setDescription(`Unknown debug target: \`${target}\`.\nValid options: \`voice\`, \`voice-rejoin\`, \`247-rejoin\`.`)
|
||||||
;
|
.setFooter({ text: this.t(msg, "responses.debug.footerHelp") });
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -147,7 +147,7 @@ async function processRejoinBatch(ctx, entries, statusMsg, title) {
|
|||||||
const icon = r.success ? "✅" : "❌";
|
const icon = r.success ? "✅" : "❌";
|
||||||
progressLines.push(`${icon} \`${r.label}\`${r.success ? ` — room:${r.roomState}` : ` — failed (${r.reason ?? "?"})`}`);
|
progressLines.push(`${icon} \`${r.label}\`${r.success ? ` — room:${r.roomState}` : ` — failed (${r.reason ?? "?"})`}`);
|
||||||
}
|
}
|
||||||
await statusMsg.edit({ embeds: [new EmbedBuilder().setColor(WARN_COLOR).setTitle(`Debug — ${title}`).setDescription(progressLines.join("\n").slice(0, MAX_DESC))] }).catch(() => {});
|
await statusMsg.edit({ embeds: [new EmbedBuilder().setColor(WARN_COLOR).setAuthor({ name: this.t ? this.t(msg, "responses.debug.rejoinAuthor") : (ctx.t ? ctx.t(msg, "responses.debug.rejoinAuthor") : "🛠️ Voice Rejoin Controller") }).setTitle(`Debug — ${title}`).setDescription(progressLines.join("\n").slice(0, MAX_DESC)).setFooter({ text: this.t ? this.t(msg, "responses.debug.rejoinFooter") : (ctx.t ? ctx.t(msg, "responses.debug.rejoinFooter") : "Owner Diagnostics • Batch Rejoin") })] }).catch(() => {});
|
||||||
|
|
||||||
const result = await forceRejoinPlayer(ctx, player);
|
const result = await forceRejoinPlayer(ctx, player);
|
||||||
result.label = label;
|
result.label = label;
|
||||||
@@ -197,7 +197,7 @@ function buildRejoinResultEmbed(results, title, noun) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR;
|
const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR;
|
||||||
return { embeds: [new EmbedBuilder().setColor(finalColor).setTitle(`Debug — ${title}`).setDescription(resultLines.join("\n").slice(0, MAX_DESC))] };
|
return { embeds: [new EmbedBuilder().setColor(finalColor).setAuthor({ name: this.t ? this.t(msg, "responses.debug.rejoinAuthor") : (ctx.t ? ctx.t(msg, "responses.debug.rejoinAuthor") : "🛠️ Voice Rejoin Controller") }).setTitle(`Debug — ${title}`).setDescription(resultLines.join("\n").slice(0, MAX_DESC)).setFooter({ text: this.t ? this.t(msg, "responses.debug.rejoinFooter") : (ctx.t ? ctx.t(msg, "responses.debug.rejoinFooter") : "Owner Diagnostics • Batch Rejoin") })] };
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Run a batch rejoin operation on matching players.
|
* Run a batch rejoin operation on matching players.
|
||||||
@@ -222,8 +222,10 @@ export async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEm
|
|||||||
: "";
|
: "";
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(SUCCESS_COLOR)
|
.setColor(SUCCESS_COLOR)
|
||||||
|
.setAuthor({ name: this.t ? this.t(msg, "responses.debug.rejoinAuthor") : (ctx.t ? ctx.t(msg, "responses.debug.rejoinAuthor") : "🛠️ Voice Rejoin Controller") })
|
||||||
.setTitle(`Debug — ${title}`)
|
.setTitle(`Debug — ${title}`)
|
||||||
.setDescription(`No ${noun} found. All voice connections appear healthy.${hintLine}`)
|
.setDescription(`No ${noun} found. All voice connections appear healthy.${hintLine}`)
|
||||||
|
.setFooter({ text: this.t ? this.t(msg, "responses.debug.rejoinFooter") : (ctx.t ? ctx.t(msg, "responses.debug.rejoinFooter") : "Owner Diagnostics • Batch Rejoin") })
|
||||||
;
|
;
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
@@ -245,8 +247,10 @@ export async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEm
|
|||||||
|
|
||||||
const statusEmbed = new EmbedBuilder()
|
const statusEmbed = new EmbedBuilder()
|
||||||
.setColor(WARN_COLOR)
|
.setColor(WARN_COLOR)
|
||||||
|
.setAuthor({ name: this.t ? this.t(msg, "responses.debug.rejoinAuthor") : (ctx.t ? ctx.t(msg, "responses.debug.rejoinAuthor") : "🛠️ Voice Rejoin Controller") })
|
||||||
.setTitle(`Debug — ${title}`)
|
.setTitle(`Debug — ${title}`)
|
||||||
.setDescription(statusLines.join("\n").slice(0, MAX_DESC))
|
.setDescription(statusLines.join("\n").slice(0, MAX_DESC))
|
||||||
|
.setFooter({ text: this.t ? this.t(msg, "responses.debug.rejoinFooter") : (ctx.t ? ctx.t(msg, "responses.debug.rejoinFooter") : "Owner Diagnostics • Batch Rejoin") })
|
||||||
;
|
;
|
||||||
const statusMsg = await msg.reply({ embeds: [statusEmbed] });
|
const statusMsg = await msg.reply({ embeds: [statusEmbed] });
|
||||||
|
|
||||||
|
|||||||
@@ -153,8 +153,10 @@ export async function runVoiceDiagnostic(msg) {
|
|||||||
const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor();
|
const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor();
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(embedColor)
|
.setColor(embedColor)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.debug.voiceAuthor") })
|
||||||
.setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""))
|
.setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""))
|
||||||
.setDescription(pages[0].slice(0, MAX_DESC))
|
.setDescription(pages[0].slice(0, MAX_DESC))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.debug.telemetryFooter") })
|
||||||
;
|
;
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
@@ -176,6 +178,7 @@ export async function runVoiceDiagnostic(msg) {
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(embedColor)
|
.setColor(embedColor)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.debug.voiceAuthor") })
|
||||||
.setTitle(this.t(msg, "responses.debug.voiceTitle") + titleSuffix + ` — ${pageLabel}`)
|
.setTitle(this.t(msg, "responses.debug.voiceTitle") + titleSuffix + ` — ${pageLabel}`)
|
||||||
.setDescription(pages[pageIdx].slice(0, MAX_DESC))
|
.setDescription(pages[pageIdx].slice(0, MAX_DESC))
|
||||||
.setFooter({ text: footerText })
|
.setFooter({ text: footerText })
|
||||||
|
|||||||
+9
-18
@@ -1,11 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* @module commands/eval
|
* @module commands/eval
|
||||||
* @description Owner-only command to evaluate arbitrary JavaScript code and display the result.
|
* @description Owner-only command to evaluate arbitrary JavaScript code and display the result.
|
||||||
*
|
|
||||||
* SECURITY: this is NOT a sandbox. The code runs with the full privileges of the bot process
|
|
||||||
* (filesystem, network, database, `await import("node:child_process")`...). Treat every ID in
|
|
||||||
* config.owners as root access to the host. Every use is written to the audit log, and known
|
|
||||||
* secret values from the config are masked in the output to prevent ACCIDENTAL leaks only.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
@@ -96,10 +91,9 @@ function removeSensitive(obj, level = 0, visited = new WeakSet()) {
|
|||||||
* Sanitize a value for safe display: await promises, redact sensitive keys,
|
* Sanitize a value for safe display: await promises, redact sensitive keys,
|
||||||
* inspect with node:util, and escape markup characters.
|
* inspect with node:util, and escape markup characters.
|
||||||
* @param {*} value - The raw eval result.
|
* @param {*} value - The raw eval result.
|
||||||
* @param {string[]} [secrets=[]] - Secret VALUES to mask anywhere in the output (see Redact.mjs).
|
|
||||||
* @returns {Promise<string>} The sanitized output string.
|
* @returns {Promise<string>} The sanitized output string.
|
||||||
*/
|
*/
|
||||||
async function clean(value, secrets = []) {
|
async function clean(value, config = null) {
|
||||||
if (value instanceof Promise) value = await value;
|
if (value instanceof Promise) value = await value;
|
||||||
|
|
||||||
if (typeof value === "object" && value !== null) {
|
if (typeof value === "object" && value !== null) {
|
||||||
@@ -115,7 +109,11 @@ async function clean(value, secrets = []) {
|
|||||||
output = `[Inspection Error]: ${err.message}`;
|
output = `[Inspection Error]: ${err.message}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
output = redactSecrets(output, secrets);
|
/* Mask all configured secret values */
|
||||||
|
if (config) {
|
||||||
|
const secrets = collectSecrets(config);
|
||||||
|
output = redactSecrets(output, secrets);
|
||||||
|
}
|
||||||
|
|
||||||
return output
|
return output
|
||||||
.replace(/`/g, "`\u200b")
|
.replace(/`/g, "`\u200b")
|
||||||
@@ -153,8 +151,7 @@ function isSingleExpression(code) {
|
|||||||
/**
|
/**
|
||||||
* @private
|
* @private
|
||||||
* @async
|
* @async
|
||||||
* Execute a JavaScript expression/statement in an async function. NOT a sandbox: shadowing
|
* Execute a JavaScript expression/statement in a sandboxed async context.
|
||||||
* `process`/`require` below only hides the usual globals, it does not restrict anything.
|
|
||||||
* @param {string} expression - The code to evaluate.
|
* @param {string} expression - The code to evaluate.
|
||||||
* @param {object} context - The `this` context for the eval.
|
* @param {object} context - The `this` context for the eval.
|
||||||
* @returns {Promise<{output: string, isError: boolean, type: string, elapsed: number}>} Eval result.
|
* @returns {Promise<{output: string, isError: boolean, type: string, elapsed: number}>} Eval result.
|
||||||
@@ -163,11 +160,6 @@ async function runEval(expression, context) {
|
|||||||
const start = Date.now();
|
const start = Date.now();
|
||||||
let result, isError = false, type = "undefined";
|
let result, isError = false, type = "undefined";
|
||||||
|
|
||||||
const secrets = collectSecrets(context?.config);
|
|
||||||
for (const t of [context?.client?.token, context?.config?.token]) {
|
|
||||||
if (typeof t === "string" && t.length >= 6 && !secrets.includes(t)) secrets.push(t);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const code = isSingleExpression(expression)
|
const code = isSingleExpression(expression)
|
||||||
? `return (${expression});`
|
? `return (${expression});`
|
||||||
@@ -183,7 +175,7 @@ async function runEval(expression, context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const elapsed = Date.now() - start;
|
const elapsed = Date.now() - start;
|
||||||
const output = await clean(result, secrets);
|
const output = await clean(result);
|
||||||
|
|
||||||
return { output, isError, type, elapsed };
|
return { output, isError, type, elapsed };
|
||||||
}
|
}
|
||||||
@@ -212,8 +204,6 @@ export const command = new CommandBuilder()
|
|||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const expression = data.get("expression").value;
|
const expression = data.get("expression").value;
|
||||||
|
|
||||||
logger.warn(`[eval] ${msg?.message?.author?.id ?? msg?.author?.id ?? "unknown"} ran: ${String(expression).replace(/\s+/g, " ").slice(0, 200)}`);
|
|
||||||
|
|
||||||
const context = Object.assign({
|
const context = Object.assign({
|
||||||
message: msg?.message,
|
message: msg?.message,
|
||||||
msg,
|
msg,
|
||||||
@@ -258,6 +248,7 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(isError ? ERROR_COLOR : getGlobalColor())
|
.setColor(isError ? ERROR_COLOR : getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.eval.author") })
|
||||||
.setTitle(title)
|
.setTitle(title)
|
||||||
.setDescription(desc)
|
.setDescription(desc)
|
||||||
.setFooter({ text: footerText })
|
.setFooter({ text: footerText })
|
||||||
|
|||||||
@@ -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] });
|
||||||
|
}
|
||||||
+51
-13
@@ -20,6 +20,20 @@ const FILTERS = [
|
|||||||
desc: "Remove all filters — restore original audio",
|
desc: "Remove all filters — restore original audio",
|
||||||
payload: {},
|
payload: {},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
emoji: "🔉",
|
||||||
|
key: "bassboost_low",
|
||||||
|
label: "Bass Boost (Low)",
|
||||||
|
desc: "Subtle low-end boost for acoustic & gentle tracks",
|
||||||
|
payload: {
|
||||||
|
equalizer: [
|
||||||
|
{ band: 0, gain: 0.25 },
|
||||||
|
{ band: 1, gain: 0.20 },
|
||||||
|
{ band: 2, gain: 0.15 },
|
||||||
|
{ band: 3, gain: 0.10 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
emoji: "🔊",
|
emoji: "🔊",
|
||||||
key: "bassboost",
|
key: "bassboost",
|
||||||
@@ -44,6 +58,25 @@ const FILTERS = [
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
emoji: "💥",
|
||||||
|
key: "bassboost_hard",
|
||||||
|
label: "Bass Boost (Hard)",
|
||||||
|
desc: "Maximum sub-bass boost — skull-shattering low end",
|
||||||
|
payload: {
|
||||||
|
equalizer: [
|
||||||
|
{ band: 0, gain: 1.00 },
|
||||||
|
{ band: 1, gain: 1.10 },
|
||||||
|
{ band: 2, gain: 0.80 },
|
||||||
|
{ band: 3, gain: 0.50 },
|
||||||
|
{ band: 4, gain: 0.25 },
|
||||||
|
{ band: 5, gain: -0.20 },
|
||||||
|
{ band: 6, gain: -0.45 },
|
||||||
|
{ band: 7, gain: -0.65 },
|
||||||
|
{ band: 8, gain: -0.80 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
emoji: "🌙",
|
emoji: "🌙",
|
||||||
key: "nightcore",
|
key: "nightcore",
|
||||||
@@ -227,7 +260,7 @@ function buildPageEmbed(t, msg, page, activeKeys, current) {
|
|||||||
const lines = pageItems.map(f => {
|
const lines = pageItems.map(f => {
|
||||||
const isActive = activeSet.has(f.key);
|
const isActive = activeSet.has(f.key);
|
||||||
const active = isActive ? " " + t(msg, "responses.filter.activeLabel") : "";
|
const active = isActive ? " " + t(msg, "responses.filter.activeLabel") : "";
|
||||||
return `${f.emoji} **${f.label}**${active} — *${f.desc}*`;
|
return `${f.emoji} **${f.label}**${active}\n *${f.desc}*`;
|
||||||
});
|
});
|
||||||
|
|
||||||
const navHint = totalPages > 1
|
const navHint = totalPages > 1
|
||||||
@@ -240,21 +273,26 @@ function buildPageEmbed(t, msg, page, activeKeys, current) {
|
|||||||
const f = FILTERS.find(f => f.key === k);
|
const f = FILTERS.find(f => f.key === k);
|
||||||
return f ? `${f.emoji} ${f.label}` : k;
|
return f ? `${f.emoji} ${f.label}` : k;
|
||||||
});
|
});
|
||||||
activeSummary = `\n🔥 Active: ${activeLabels.join(" + ")}\n`;
|
activeSummary = `\n🟢 **${t(msg, "responses.filter.activePrefix") || "Active:"}** ${activeLabels.join(" + ")}\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setAuthor({ name: t(msg, "responses.filter.pickerTitle") })
|
.setAuthor({ name: `🎛️ ${t(msg, "responses.filter.pickerTitle")}` })
|
||||||
.setDescription(
|
.setDescription(
|
||||||
`${trackLine}\n${activeSummary}\n` +
|
`${trackLine}\n${activeSummary}\n` +
|
||||||
lines.join("\n") +
|
lines.join("\n\n") +
|
||||||
navHint
|
navHint
|
||||||
)
|
)
|
||||||
.setFooter({
|
.setFooter({
|
||||||
text: t(msg, "responses.filter.footer", { page: page + 1, total: totalPages })
|
text: `${t(msg, "responses.filter.footer", { page: page + 1, total: totalPages })} • ${t(msg, "responses.filter.realtimeDsp") || "Real-time DSP"}`
|
||||||
})
|
});
|
||||||
;
|
|
||||||
|
if (current?.thumbnail) {
|
||||||
|
embed.setThumbnail(current.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
|
return embed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -422,10 +460,10 @@ export async function run(msg) {
|
|||||||
activeKeys = previousActiveKeys;
|
activeKeys = previousActiveKeys;
|
||||||
const errEmbed = new EmbedBuilder()
|
const errEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: `🎛️ ${this.t(msg, "responses.filter.pickerTitle")}` })
|
||||||
.setDescription(
|
.setDescription(
|
||||||
this.t(msg, "responses.filter.applyFailed", { filter: filter.label, reason })
|
this.t(msg, "responses.filter.applyFailed", { filter: filter.label, reason })
|
||||||
)
|
);
|
||||||
;
|
|
||||||
await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {});
|
await menuMsg.edit({ embeds: [errEmbed] }).catch(() => {});
|
||||||
await Utils.sleep(1500);
|
await Utils.sleep(1500);
|
||||||
await menuMsg.edit({
|
await menuMsg.edit({
|
||||||
@@ -450,12 +488,12 @@ export async function run(msg) {
|
|||||||
|
|
||||||
const confirmEmbed = new EmbedBuilder()
|
const confirmEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: `🎛️ ${this.t(msg, "responses.filter.pickerTitle")}` })
|
||||||
.setDescription(
|
.setDescription(
|
||||||
`${successMsg}\n\n` +
|
`${successMsg}\n\n` +
|
||||||
`*${filter.desc}*\n\n` +
|
`*${filter.desc}*\n\n` +
|
||||||
`💡 ${this.t(msg, "responses.filter.reactToToggle")}`
|
`💡 ${this.t(msg, "responses.filter.reactToToggle")}`
|
||||||
)
|
);
|
||||||
;
|
|
||||||
|
|
||||||
await menuMsg.edit({ embeds: [confirmEmbed] }).catch(() => {});
|
await menuMsg.edit({ embeds: [confirmEmbed] }).catch(() => {});
|
||||||
await Utils.sleep(1200);
|
await Utils.sleep(1200);
|
||||||
|
|||||||
+21
-6
@@ -4,7 +4,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { cleanId } from "../src/ui/index.mjs";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { cleanId, getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { resolveChannelCached } from "../src/utils/Helpers247.mjs";
|
import { resolveChannelCached } from "../src/utils/Helpers247.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -34,13 +35,27 @@ export const command = new CommandBuilder()
|
|||||||
*/
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const cid = cleanId(data.get("channelId").value);
|
const cid = cleanId(data.get("channelId").value);
|
||||||
|
const buildForceLeaveEmbed = (desc) => new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.forceleave.authorAdmin") })
|
||||||
|
.setTitle(this.t(msg, "responses.forceleave.titleEviction"))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.forceleave.footerTip", { channel: cid }) });
|
||||||
|
|
||||||
const targetChannel = await resolveChannelCached(this.client, cid);
|
const targetChannel = await resolveChannelCached(this.client, cid);
|
||||||
if (!targetChannel) return msg.reply(this.t(msg, "responses.forceleave.channelNotFound"));
|
if (!targetChannel) {
|
||||||
if (cleanId(msg.message?.guildId) !== cleanId(targetChannel.guildId))
|
return msg.reply({ embeds: [buildForceLeaveEmbed(this.t(msg, "responses.forceleave.channelNotFound"))] });
|
||||||
return msg.reply(this.t(msg, "responses.forceleave.wrongServer"));
|
}
|
||||||
|
if (cleanId(msg.message?.guildId) !== cleanId(targetChannel.guildId)) {
|
||||||
|
return msg.reply({ embeds: [buildForceLeaveEmbed(this.t(msg, "responses.forceleave.wrongServer"))] });
|
||||||
|
}
|
||||||
const p = this.players.playerMap.get(cid)
|
const p = this.players.playerMap.get(cid)
|
||||||
?? [...this.players.playerMap.values()].find((player) => cleanId(player?._channelId) === cid);
|
?? [...this.players.playerMap.values()].find((player) => cleanId(player?._channelId) === cid);
|
||||||
if (!p) return msg.reply(this.t(msg, "responses.forceleave.playerNotFound"));
|
if (!p) {
|
||||||
if (!p.connection) return msg.reply(this.t(msg, "responses.forceleave.playerNotInit"));
|
return msg.reply({ embeds: [buildForceLeaveEmbed(this.t(msg, "responses.forceleave.playerNotFound"))] });
|
||||||
|
}
|
||||||
|
if (!p.connection) {
|
||||||
|
return msg.reply({ embeds: [buildForceLeaveEmbed(this.t(msg, "responses.forceleave.playerNotInit"))] });
|
||||||
|
}
|
||||||
await this.players.leave(msg, cid);
|
await this.players.leave(msg, cid);
|
||||||
}
|
}
|
||||||
+5
-4
@@ -25,8 +25,6 @@ export const command = new CommandBuilder()
|
|||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const description = this.t(message, "responses.invite.description");
|
|
||||||
|
|
||||||
const botUser = this.client?.user;
|
const botUser = this.client?.user;
|
||||||
const botIcon = botUser?.displayAvatarURL?.() || null;
|
const botIcon = botUser?.displayAvatarURL?.() || null;
|
||||||
|
|
||||||
@@ -36,8 +34,11 @@ export async function run(message) {
|
|||||||
name: this.t(message, "responses.invite.title"),
|
name: this.t(message, "responses.invite.title"),
|
||||||
iconURL: botIcon
|
iconURL: botIcon
|
||||||
})
|
})
|
||||||
.setDescription(description)
|
.setTitle(this.t(message, "responses.invite.addRemixTitle"))
|
||||||
;
|
.setDescription(this.t(message, "responses.invite.description"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.invite.footer") });
|
||||||
|
|
||||||
|
if (botIcon) embed.setThumbnail(botIcon);
|
||||||
|
|
||||||
await message.reply({
|
await message.reply({
|
||||||
embeds: [embed]
|
embeds: [embed]
|
||||||
|
|||||||
+13
-4
@@ -67,8 +67,13 @@ export async function run(message, data) {
|
|||||||
if (rawArg) {
|
if (rawArg) {
|
||||||
const resolvedId = resolveChannelId(rawArg, this, message);
|
const resolvedId = resolveChannelId(rawArg, this, message);
|
||||||
if (!resolvedId) {
|
if (!resolvedId) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
const prefix = this.handler.getPrefix(getMessageGuildId(message));
|
||||||
.setDescription(this.t(message, "responses.join.voiceChannelNotFound"));
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.join.promptAuthor") })
|
||||||
|
.setTitle(this.t(message, "responses.join.promptTitle"))
|
||||||
|
.setDescription(this.t(message, "responses.join.voiceChannelNotFound"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.join.promptFooter", { prefix }) });
|
||||||
return message.reply({ embeds: [embed] });
|
return message.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
return this.players.initPlayer(message, resolvedId);
|
return this.players.initPlayer(message, resolvedId);
|
||||||
@@ -77,8 +82,12 @@ export async function run(message, data) {
|
|||||||
const { channelId: cid } = await this.players.checkVoiceChannels(message);
|
const { channelId: cid } = await this.players.checkVoiceChannels(message);
|
||||||
if (!cid) {
|
if (!cid) {
|
||||||
const prefix = this.handler.getPrefix(getMessageGuildId(message));
|
const prefix = this.handler.getPrefix(getMessageGuildId(message));
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
const embed = new EmbedBuilder()
|
||||||
.setDescription(this.t(message, "responses.join.noVoiceChannel", { prefix }));
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.join.promptAuthor") })
|
||||||
|
.setTitle(this.t(message, "responses.join.promptTitle"))
|
||||||
|
.setDescription(this.t(message, "responses.join.noVoiceChannel", { prefix }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.join.promptFooter", { prefix }) });
|
||||||
return message.reply({ embeds: [embed] });
|
return message.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+63
-15
@@ -45,7 +45,9 @@ export async function runAccountActions(msg, data, lastfm, prefix, userId, targe
|
|||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(msg, "responses.lastfm.alreadyLinked", { username: existing.username, prefix }))]
|
.setAuthor({ name: this.t(msg, "responses.lastfm.accountAuthor") })
|
||||||
|
.setDescription(this.t(msg, "responses.lastfm.alreadyLinked", { username: existing.username, prefix }))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.accountFooter", { prefix }) })]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -75,11 +77,14 @@ export async function runAccountActions(msg, data, lastfm, prefix, userId, targe
|
|||||||
|
|
||||||
const replyEmbed = new EmbedBuilder()
|
const replyEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.lastfm.accountAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.authLinkTitle"))
|
||||||
.setDescription(
|
.setDescription(
|
||||||
sent
|
sent
|
||||||
? this.t(msg, "responses.lastfm.authDM", { prefix })
|
? this.t(msg, "responses.lastfm.authDM", { prefix })
|
||||||
: this.t(msg, "responses.lastfm.authDMFailed", { url: authUrl, prefix })
|
: this.t(msg, "responses.lastfm.authDMFailed", { url: authUrl, prefix })
|
||||||
);
|
)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.accountFooter", { prefix }) });
|
||||||
|
|
||||||
return msg.reply({ embeds: [replyEmbed] });
|
return msg.reply({ embeds: [replyEmbed] });
|
||||||
}
|
}
|
||||||
@@ -113,7 +118,10 @@ export async function runAccountActions(msg, data, lastfm, prefix, userId, targe
|
|||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(msg, "responses.lastfm.linked", { username: session.name }))]
|
.setAuthor({ name: this.t(msg, "responses.lastfm.accountAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.accountLinkedTitle"))
|
||||||
|
.setDescription(this.t(msg, "responses.lastfm.linked", { username: session.name }))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.accountFooter", { prefix }) })]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,7 +131,12 @@ export async function runAccountActions(msg, data, lastfm, prefix, userId, targe
|
|||||||
|
|
||||||
await lastfm.removeUser(userId);
|
await lastfm.removeUser(userId);
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.unlinked", { username: user.username }))]
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.lastfm.accountAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.accountUnlinkedTitle"))
|
||||||
|
.setDescription(this.t(msg, "responses.lastfm.unlinked", { username: user.username }))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.accountFooter", { prefix }) })]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,10 +150,13 @@ export async function runAccountActions(msg, data, lastfm, prefix, userId, targe
|
|||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.lastfm.accountAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.scrobbleTitle"))
|
||||||
.setDescription(newState
|
.setDescription(newState
|
||||||
? this.t(msg, "responses.lastfm.scrobbleEnabled", { username: user.username })
|
? this.t(msg, "responses.lastfm.scrobbleEnabled", { username: user.username })
|
||||||
: this.t(msg, "responses.lastfm.scrobbleDisabled")
|
: this.t(msg, "responses.lastfm.scrobbleDisabled")
|
||||||
)]
|
)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.accountFooter", { prefix }) })]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,17 +206,43 @@ export async function runAccountActions(msg, data, lastfm, prefix, userId, targe
|
|||||||
|
|
||||||
lastfm.syncUserScrobbleCount(profileUserId).catch(() => {});
|
lastfm.syncUserScrobbleCount(profileUserId).catch(() => {});
|
||||||
|
|
||||||
|
const avatarUrl = info.image?.[3]?.["#text"] || info.image?.[2]?.["#text"] || null;
|
||||||
|
const regDate = info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown";
|
||||||
|
const scrobbleStatus = user.scrobbleEnabled
|
||||||
|
? this.t(msg, "responses.lastfm.profileScrobbleEnabled")
|
||||||
|
: this.t(msg, "responses.lastfm.profileScrobbleDisabled");
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setAuthor({ name: this.t(msg, "responses.lastfm.profileTitle", { username: info.name }), iconURL: info.image?.[2]?.["#text"] || undefined, url: info.url })
|
.setAuthor({ name: this.t(msg, "responses.lastfm.profileAuthor"), iconURL: avatarUrl || undefined, url: info.url })
|
||||||
.setDescription([
|
.setTitle(info.name)
|
||||||
this.t(msg, "responses.lastfm.profileScrobbles", { playcount: Utils.formatNumber(info.playcount ?? 0) }),
|
.setURL(info.url || undefined)
|
||||||
this.t(msg, "responses.lastfm.profileRegistered", { date: info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown" }),
|
.setDescription(
|
||||||
this.t(msg, "responses.lastfm.profileScrobbleStatus", { status: user.scrobbleEnabled ? this.t(msg, "responses.lastfm.profileScrobbleEnabled") : this.t(msg, "responses.lastfm.profileScrobbleDisabled") }),
|
`📅 **${this.t(msg, "responses.lastfm.profileFieldRegistered")}:** ${regDate}\n` +
|
||||||
``,
|
`🔗 **[${this.t(msg, "responses.lastfm.profileLink", { url: info.url })}](${info.url})**`
|
||||||
this.t(msg, "responses.lastfm.profileLink", { url: info.url }),
|
)
|
||||||
].join("\n"))
|
.addFields(
|
||||||
.setFooter({ text: this.t(msg, "responses.lastfm.profileScrobbleFooter", { prefix }) });
|
{
|
||||||
|
name: this.t(msg, "responses.lastfm.profileFieldTotalScrobbles"),
|
||||||
|
value: `🎵 **${Utils.formatNumber(info.playcount ?? 0)}**`,
|
||||||
|
inline: true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: this.t(msg, "responses.lastfm.profileFieldArtists"),
|
||||||
|
value: `🎤 **${Utils.formatNumber(info.artist_count ?? 0)}**`,
|
||||||
|
inline: true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: this.t(msg, "responses.lastfm.profileFieldScrobbling"),
|
||||||
|
value: scrobbleStatus,
|
||||||
|
inline: true
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.profileFooterPro", { prefix }) });
|
||||||
|
|
||||||
|
if (avatarUrl) {
|
||||||
|
embed.setThumbnail(avatarUrl);
|
||||||
|
}
|
||||||
|
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
@@ -220,7 +262,12 @@ export async function runAccountActions(msg, data, lastfm, prefix, userId, targe
|
|||||||
|
|
||||||
if (!playlists.length) {
|
if (!playlists.length) {
|
||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noPlaylists", { username: user.username }))]
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.lastfm.playlistsAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.playlistsTitle", { username: user.username }))
|
||||||
|
.setDescription(this.t(msg, "responses.lastfm.noPlaylists", { username: user.username }))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.playlistsFooter", { prefix }) })]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,6 +282,7 @@ export async function runAccountActions(msg, data, lastfm, prefix, userId, targe
|
|||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.lastfm.playlistsAuthor") })
|
||||||
.setTitle(this.t(msg, "responses.lastfm.playlistsTitle", { username: user.username }))
|
.setTitle(this.t(msg, "responses.lastfm.playlistsTitle", { username: user.username }))
|
||||||
.setDescription(desc)
|
.setDescription(desc)
|
||||||
.setFooter({ text: this.t(msg, "responses.lastfm.playlistsFooter", { prefix }) })]
|
.setFooter({ text: this.t(msg, "responses.lastfm.playlistsFooter", { prefix }) })]
|
||||||
|
|||||||
@@ -159,23 +159,52 @@ export async function runDiscoveryActions(msg, data, lastfm, prefix, userId, tar
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const lines = trendingData.map((item, i) => {
|
const isArtists = tokenTextTr === "artists";
|
||||||
const num = String(i + 1).padStart(2, " ");
|
trendingTitle = isArtists
|
||||||
const link = item.url ? `[${item.name}](${item.url})` : item.name;
|
? this.t(msg, "responses.lastfm.trendingTitleArtists")
|
||||||
const artistStr = item.artist ? ` by **${item.artist}**` : "";
|
: this.t(msg, "responses.lastfm.trendingTitleTracks");
|
||||||
const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} ${this.t(msg, "responses.lastfm.listeners")}` : item.playcount ? ` — ${Utils.formatNumber(item.playcount)} ${this.t(msg, "responses.lastfm.plays")}` : "";
|
|
||||||
return `\`${num}.\` ${link}${artistStr}${extra}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
const desc = lines.join("\n").slice(0, 4096);
|
const top1 = trendingData[0];
|
||||||
|
const runners = trendingData.slice(1, 10);
|
||||||
|
|
||||||
return msg.reply({
|
const embed = new EmbedBuilder()
|
||||||
embeds: [new EmbedBuilder()
|
.setColor(getGlobalColor())
|
||||||
.setColor(getGlobalColor())
|
.setAuthor({ name: this.t(msg, "responses.lastfm.trendingAuthor") })
|
||||||
.setTitle(trendingTitle)
|
.setTitle(trendingTitle)
|
||||||
.setDescription(desc)
|
.setFooter({ text: this.t(msg, "responses.lastfm.trendingFooterPro", { prefix }) });
|
||||||
.setFooter({ text: `💡 Use token option: tracks or artists` })]
|
|
||||||
});
|
if (top1) {
|
||||||
|
const link = top1.url ? `[${top1.name}](${top1.url})` : top1.name;
|
||||||
|
const artistStr = top1.artist ? ` by **${top1.artist}**` : "";
|
||||||
|
const extra = top1.listeners
|
||||||
|
? ` · **${Utils.formatNumber(top1.listeners)}** ${this.t(msg, "responses.lastfm.listeners")}`
|
||||||
|
: (top1.playcount ? ` · **${Utils.formatNumber(top1.playcount)}** ${this.t(msg, "responses.lastfm.plays")}` : "");
|
||||||
|
embed.addFields({
|
||||||
|
name: `🥇 ${this.t(msg, "responses.lastfm.trendingPodium1")}`,
|
||||||
|
value: `**${link}**${artistStr}${extra}`,
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runners.length > 0) {
|
||||||
|
const MEDALS = ["🥈", "🥉"];
|
||||||
|
const lines = runners.map((item, i) => {
|
||||||
|
const badge = i < 2 ? MEDALS[i] : `\`#${i + 2}\``;
|
||||||
|
const link = item.url ? `[${item.name}](${item.url})` : item.name;
|
||||||
|
const artistStr = item.artist ? ` · ${item.artist}` : "";
|
||||||
|
const extra = item.listeners
|
||||||
|
? ` (${Utils.formatNumber(item.listeners)})`
|
||||||
|
: (item.playcount ? ` (${Utils.formatNumber(item.playcount)})` : "");
|
||||||
|
return `${badge} **${link}**${artistStr}${extra}`;
|
||||||
|
});
|
||||||
|
embed.addFields({
|
||||||
|
name: `🔥 ${this.t(msg, "responses.lastfm.trendingRunnersUp")}`,
|
||||||
|
value: lines.join("\n").slice(0, 1024),
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
case "geo":
|
case "geo":
|
||||||
|
|||||||
+41
-80
@@ -1,8 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* @module commands/lastfm/help
|
* @module commands/lastfm/help
|
||||||
* @description Fallback help action for the lastfm command (the original
|
* @description Fallback help action for the lastfm command.
|
||||||
* switch's `default` branch). Extracted verbatim; reached when the action
|
* Dispatched when the subcommand action matches 'help' or an unknown action.
|
||||||
* matches no known action name.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
@@ -17,83 +16,45 @@ import { getGlobalColor } from "../../src/ui/index.mjs";
|
|||||||
* @param {string} userId - The invoking user's ID.
|
* @param {string} userId - The invoking user's ID.
|
||||||
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||||
* @param {string} action - The resolved action name.
|
* @param {string} action - The resolved action name.
|
||||||
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
* @returns {Promise<*>} Embed response for Last.fm help.
|
||||||
*/
|
*/
|
||||||
export async function runLastFmHelp(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
export async function runLastFmHelp(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
return msg.reply({
|
const pfx = prefix || "%";
|
||||||
embeds: [new EmbedBuilder()
|
|
||||||
.setColor(getGlobalColor())
|
const accountLines = [
|
||||||
.setDescription([
|
`• \`${pfx}fm link\` · \`${pfx}fm unlink\` · \`${pfx}fm scrobble\` · \`${pfx}fm np\``,
|
||||||
`🎵 **Last.fm Commands:**`,
|
`• \`${pfx}fm profile\` · \`${pfx}fm loved\` · \`${pfx}fm top\` · \`${pfx}fm artists\` · \`${pfx}fm recent\``,
|
||||||
``,
|
`• \`${pfx}fm love\` · \`${pfx}fm unlove\` · \`${pfx}fm playlists\``
|
||||||
`\`${prefix}lastfm link\` — Link your Last.fm account`,
|
].join("\n");
|
||||||
`\`${prefix}lastfm unlink\` — Disconnect your account`,
|
|
||||||
`\`${prefix}lastfm scrobble\` — Toggle auto-scrobbling`,
|
const discoveryLines = [
|
||||||
`\`${prefix}lastfm np\` — Show your Last.fm now playing`,
|
`• \`${pfx}fm artistinfo\` · \`${pfx}fm albuminfo\` · \`${pfx}fm trackinfo\` · \`${pfx}fm cover\``,
|
||||||
`\`${prefix}lastfm profile\` — View your Last.fm profile (or another user's with user option)`,
|
`• \`${pfx}fm trending\` · \`${pfx}fm weekly\` · \`${pfx}fm tag <name>\` · \`${pfx}fm geo <country>\``,
|
||||||
`\`${prefix}lastfm loved\` — View your loved tracks`,
|
`• \`${pfx}fm artisttags\` · \`${pfx}fm albumtags\` · \`${pfx}fm tagalbums <tag>\``
|
||||||
`\`${prefix}lastfm top\` — View your top tracks (supports period)`,
|
].join("\n");
|
||||||
`\`${prefix}lastfm artists\` — View your top artists (supports period)`,
|
|
||||||
`\`${prefix}lastfm recent\` — View your recent tracks`,
|
const socialLines = [
|
||||||
`\`${prefix}lastfm playlists\` — View your Last.fm playlists`,
|
`• \`${pfx}whoknows [artist]\` · \`${pfx}fm wkt\` · \`${pfx}fm wka\``,
|
||||||
`\`${prefix}lastfm leaderboard\` — Scrobble leaderboard`,
|
`• \`${pfx}fm crowns\` · \`${pfx}fm compare @user\` · \`${pfx}fm affinity\` · \`${pfx}fm lb\``,
|
||||||
`\`${prefix}lastfm love\` — Love the current track`,
|
`• \`${pfx}fm friends\` · \`${pfx}fm refreshmembers\``
|
||||||
`\`${prefix}lastfm unlove\` — Unlove the current track`,
|
].join("\n");
|
||||||
``,
|
|
||||||
`🔍 **Info Commands:**`,
|
const playbackLines = [
|
||||||
`\`${prefix}lastfm whoknows [artist]\` — Who in the server listens to an artist`,
|
`• \`${pfx}fm play loved\` · \`${pfx}fm play top\` · \`${pfx}fm play albums\` · \`${pfx}fm play artists\``,
|
||||||
`\`${prefix}lastfm whoknowstrack\` — Who knows a specific track`,
|
`• Cross-provider: \`${pfx}fm play sp:top\` (Spotify) · \`yt:top\` · \`dz:top\` · \`td:top\``
|
||||||
`\`${prefix}lastfm whoknowsalbum\` — Who knows a specific album`,
|
].join("\n");
|
||||||
`\`${prefix}lastfm artistinfo\` — Detailed info about an artist`,
|
|
||||||
`\`${prefix}lastfm albuminfo\` — Detailed info about an album`,
|
const embed = new EmbedBuilder()
|
||||||
`\`${prefix}lastfm trackinfo\` — Detailed info about a track`,
|
.setColor(getGlobalColor())
|
||||||
`\`${prefix}lastfm topalbums\` — View your top albums (supports period)`,
|
.setAuthor({ name: this.t(msg, "responses.lastfm.helpAuthor") })
|
||||||
`\`${prefix}lastfm toptags\` — View your top tags/genres`,
|
.setTitle(this.t(msg, "responses.lastfm.helpTitle"))
|
||||||
`\`${prefix}lastfm tag <name>\` — View info about a specific tag`,
|
.addFields(
|
||||||
`\`${prefix}lastfm compare @user\` — Compare your taste with another user`,
|
{ name: this.t(msg, "responses.lastfm.helpCategoryAccount"), value: accountLines, inline: false },
|
||||||
`\`${prefix}lastfm cover\` — Get album cover art for the current track`,
|
{ name: this.t(msg, "responses.lastfm.helpCategoryDiscovery"), value: discoveryLines, inline: false },
|
||||||
``,
|
{ name: this.t(msg, "responses.lastfm.helpCategorySocial"), value: socialLines, inline: false },
|
||||||
`🏷️ **Tag Commands:**`,
|
{ name: this.t(msg, "responses.lastfm.helpCategoryPlayback"), value: playbackLines, inline: false }
|
||||||
`\`${prefix}lastfm artisttags\` — Top tags for an artist`,
|
)
|
||||||
`\`${prefix}lastfm albumtags\` — Top tags for an album`,
|
.setFooter({ text: this.t(msg, "responses.lastfm.helpFooterPro", { prefix: pfx }) });
|
||||||
`\`${prefix}lastfm tracktags\` — Top tags for a track`,
|
|
||||||
`\`${prefix}lastfm tagalbums <tag>\` — Top albums for a tag`,
|
return msg.reply({ embeds: [embed] });
|
||||||
``,
|
|
||||||
`👥 **Social Commands:**`,
|
|
||||||
`\`${prefix}lastfm affinity\` — Find users with similar taste`,
|
|
||||||
`\`${prefix}lastfm crowns\` — View your artist crowns (#1 listener)`,
|
|
||||||
`\`${prefix}lastfm friends\` — View your Last.fm friends`,
|
|
||||||
`\`${prefix}lastfm refreshmembers\` — Refresh server member cache`,
|
|
||||||
``,
|
|
||||||
`📊 **Charts & Discovery:**`,
|
|
||||||
`\`${prefix}lastfm weekly [artists|tracks|albums]\` — Weekly charts`,
|
|
||||||
`\`${prefix}lastfm trending [tracks|artists]\` — Global trending on Last.fm`,
|
|
||||||
`\`${prefix}lastfm geo [artists|tracks] <country>\` — Top by country`,
|
|
||||||
`\`${prefix}lastfm artisttracks\` — Your scrobbles for an artist`,
|
|
||||||
`\`${prefix}lastfm search <query>\` — Universal search`,
|
|
||||||
``,
|
|
||||||
`🎶 **Play from Last.fm:**`,
|
|
||||||
`\`${prefix}lastfm play loved\` — Play your loved tracks`,
|
|
||||||
`\`${prefix}lastfm play top\` — Play your top tracks`,
|
|
||||||
`\`${prefix}lastfm play recent\` — Play your recent tracks`,
|
|
||||||
`\`${prefix}lastfm play albums\` — Play your top albums`,
|
|
||||||
`\`${prefix}lastfm play artists\` — Play your top artists' tracks`,
|
|
||||||
`\`${prefix}lastfm play playlist 1\` — Play a playlist`,
|
|
||||||
``,
|
|
||||||
`🎧 **Play with a specific provider (defaults to \`top\`):**`,
|
|
||||||
`\`${prefix}lastfm play sp\` or \`${prefix}lastfm play sp:top\` — Play top tracks, search on Spotify`,
|
|
||||||
`\`${prefix}lastfm play td\` or \`${prefix}lastfm play td:top\` — Play top tracks, search on Tidal`,
|
|
||||||
`\`${prefix}lastfm play dz\` or \`${prefix}lastfm play dz:top\` — Play top tracks, search on Deezer`,
|
|
||||||
`\`${prefix}lastfm play yt\` or \`${prefix}lastfm play yt:top\` — Play top tracks, search on YouTube`,
|
|
||||||
``,
|
|
||||||
`🎧 **Last.fm as resolve provider (all categories):**`,
|
|
||||||
`\`${prefix}lastfm play lf:loved\` — Play loved tracks, search on Last.fm`,
|
|
||||||
`\`${prefix}lastfm play lf:top\` — Play top tracks, search on Last.fm`,
|
|
||||||
`\`${prefix}lastfm play lf:recent\` — Play recent tracks, search on Last.fm`,
|
|
||||||
`\`${prefix}lastfm play lf:albums\` — Play top albums, search on Last.fm`,
|
|
||||||
`\`${prefix}lastfm play lf:artists\` — Play top artists, search on Last.fm`,
|
|
||||||
``,
|
|
||||||
`💡 Or use inline: \`${prefix}play lastfm:loved\` or \`${prefix}play lastfm:sp\` or \`${prefix}play lastfm:td:top\``,
|
|
||||||
].join("\n"))]
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
+134
-62
@@ -102,44 +102,46 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(`🎤 ${info.name}`)
|
.setAuthor({ name: this.t(msg, "responses.lastfm.artistSpotlightAuthor"), iconURL: info.image || undefined })
|
||||||
|
.setTitle(info.name)
|
||||||
.setURL(info.url || undefined)
|
.setURL(info.url || undefined)
|
||||||
.setThumbnail(info.image || undefined);
|
.setThumbnail(info.image || undefined);
|
||||||
|
|
||||||
|
let desc = "";
|
||||||
|
if (info.tags?.length) {
|
||||||
|
const tagStr = info.tags.slice(0, 6).map(t => {
|
||||||
|
const tagLower = String(t).toLowerCase().replace(/\s+/g, "+");
|
||||||
|
return `[\`${t}\`](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
||||||
|
}).join(" ");
|
||||||
|
desc += tagStr + "\n\n";
|
||||||
|
}
|
||||||
|
if (info.bio) {
|
||||||
|
const cleanBio = info.bio.replace(/<[^>]*>/g, "").trim();
|
||||||
|
if (cleanBio.length > 0) {
|
||||||
|
const truncated = cleanBio.length > 280 ? cleanBio.slice(0, 277) + "..." : cleanBio;
|
||||||
|
desc += `> ${truncated}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (desc) embed.setDescription(desc.trim());
|
||||||
|
|
||||||
const fields = [];
|
const fields = [];
|
||||||
fields.push({ name: "Listeners", value: Utils.formatNumber(info.stats?.listeners ?? 0), inline: true });
|
fields.push({ name: this.t(msg, "responses.lastfm.artistFieldListeners"), value: `👥 **${Utils.formatNumber(info.stats?.listeners ?? 0)}**`, inline: true });
|
||||||
fields.push({ name: "Global Plays", value: Utils.formatNumber(info.stats?.playcount ?? 0), inline: true });
|
fields.push({ name: this.t(msg, "responses.lastfm.artistFieldPlays"), value: `▶️ **${Utils.formatNumber(info.stats?.playcount ?? 0)}**`, inline: true });
|
||||||
|
|
||||||
if (info.userplaycount != null && user) {
|
if (info.userplaycount != null && user) {
|
||||||
fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true });
|
fields.push({ name: this.t(msg, "responses.lastfm.artistFieldUserPlays"), value: `🎧 **${Utils.formatNumber(info.userplaycount)}**`, inline: true });
|
||||||
}
|
|
||||||
|
|
||||||
if (info.tags?.length) {
|
|
||||||
const tagStr = info.tags.slice(0, 8).map(t => {
|
|
||||||
const tagLower = String(t).toLowerCase().replace(/\s+/g, "+");
|
|
||||||
return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
|
||||||
}).join(" · ");
|
|
||||||
fields.push({ name: "Tags", value: tagStr, inline: false });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (info.similar?.length) {
|
if (info.similar?.length) {
|
||||||
const simStr = info.similar.slice(0, 5).map(s => {
|
const simStr = info.similar.slice(0, 5).map(s => {
|
||||||
return s.url ? `[${s.name}](${s.url})` : s.name;
|
return s.url ? `[${s.name}](${s.url})` : s.name;
|
||||||
}).join(" · ");
|
}).join(" · ");
|
||||||
fields.push({ name: "Similar Artists", value: simStr, inline: false });
|
fields.push({ name: this.t(msg, "responses.lastfm.artistFieldSimilar"), value: simStr, inline: false });
|
||||||
}
|
}
|
||||||
|
|
||||||
embed.addFields(...fields);
|
embed.addFields(...fields);
|
||||||
|
|
||||||
if (info.bio) {
|
embed.setFooter({ text: this.t(msg, "responses.lastfm.artistFooterPro", { artist: info.name }) });
|
||||||
const cleanBio = info.bio.replace(/<[^>]*>/g, "").trim();
|
|
||||||
if (cleanBio.length > 0) {
|
|
||||||
const truncated = cleanBio.length > 300 ? cleanBio.slice(0, 297) + "..." : cleanBio;
|
|
||||||
embed.setDescription(truncated);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" });
|
|
||||||
|
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
@@ -160,7 +162,7 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
|
|
||||||
const tokenText = data.get("token")?.value;
|
const tokenText = data.get("token")?.value;
|
||||||
if (tokenText) {
|
if (tokenText) {
|
||||||
const dashMatch = tokenText.length <= 300 ? tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/) : null;
|
const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
if (dashMatch) {
|
if (dashMatch) {
|
||||||
artistName = dashMatch[1].trim();
|
artistName = dashMatch[1].trim();
|
||||||
albumName = dashMatch[2].trim();
|
albumName = dashMatch[2].trim();
|
||||||
@@ -194,18 +196,39 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.lastfm.albumSpotlightAuthor") })
|
||||||
.setTitle(`💿 ${info.name}`)
|
.setTitle(`💿 ${info.name}`)
|
||||||
.setURL(info.url || undefined)
|
.setURL(info.url || undefined)
|
||||||
.setThumbnail(info.image || undefined);
|
.setThumbnail(info.image || undefined);
|
||||||
|
|
||||||
const fields = [];
|
|
||||||
|
|
||||||
if (info.artist) {
|
if (info.artist) {
|
||||||
fields.push({ name: "Artist", value: info.artist, inline: true });
|
embed.setDescription(`*by* **${info.artist}**`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fields = [];
|
||||||
|
|
||||||
if (info.userplaycount != null && user) {
|
if (info.userplaycount != null && user) {
|
||||||
fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true });
|
fields.push({
|
||||||
|
name: `🎧 ${this.t(msg, "responses.lastfm.albumFieldYourPlays")}`,
|
||||||
|
value: `**${Utils.formatNumber(info.userplaycount)}**`,
|
||||||
|
inline: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (info.tracks?.length) {
|
||||||
|
fields.push({
|
||||||
|
name: `🎼 ${this.t(msg, "responses.lastfm.albumFieldTracks")}`,
|
||||||
|
value: `**${info.tracks.length}**`,
|
||||||
|
inline: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (info.listeners) {
|
||||||
|
fields.push({
|
||||||
|
name: `👥 ${this.t(msg, "responses.lastfm.trackFieldListeners")}`,
|
||||||
|
value: `**${Utils.formatNumber(Number(info.listeners))}**`,
|
||||||
|
inline: true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (info.tags?.length) {
|
if (info.tags?.length) {
|
||||||
@@ -213,21 +236,36 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
const tagLower = String(t).toLowerCase().replace(/\s+/g, "+");
|
const tagLower = String(t).toLowerCase().replace(/\s+/g, "+");
|
||||||
return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
||||||
}).join(" · ");
|
}).join(" · ");
|
||||||
fields.push({ name: "Tags", value: tagStr, inline: false });
|
fields.push({
|
||||||
|
name: `🏷️ ${this.t(msg, "responses.lastfm.albumFieldTags")}`,
|
||||||
|
value: tagStr,
|
||||||
|
inline: false,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (info.tracks?.length) {
|
if (info.tracks?.length) {
|
||||||
const trackLines = info.tracks.slice(0, 15).map((t, i) => {
|
const trackLines = info.tracks.slice(0, 10).map((t, i) => {
|
||||||
const num = String(i + 1).padStart(2, " ");
|
const num = String(i + 1).padStart(2, "0");
|
||||||
const dur = t.duration > 0 ? ` (${formatDuration(t.duration)})` : "";
|
const dur = t.duration > 0 ? ` (${formatDuration(t.duration)})` : "";
|
||||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
return `\`${num}.\` ${link}${dur}`;
|
return `\`${num}.\` ${link}${dur}`;
|
||||||
});
|
});
|
||||||
fields.push({ name: "Tracklist", value: trackLines.join("\n").slice(0, 1024), inline: false });
|
const extraCount = info.tracks.length > 10 ? `\n*... +${info.tracks.length - 10} more*` : "";
|
||||||
|
fields.push({
|
||||||
|
name: `📜 ${this.t(msg, "responses.lastfm.albumFieldTracklist")}`,
|
||||||
|
value: (trackLines.join("\n") + extraCount).slice(0, 1024),
|
||||||
|
inline: false,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
embed.addFields(...fields);
|
embed.addFields(...fields);
|
||||||
embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" });
|
embed.setFooter({
|
||||||
|
text: this.t(msg, "responses.lastfm.albumFooterPro", {
|
||||||
|
prefix,
|
||||||
|
artist: info.artist || "Artist",
|
||||||
|
album: info.name,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
@@ -249,7 +287,7 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
|
|
||||||
const tokenText = data.get("token")?.value;
|
const tokenText = data.get("token")?.value;
|
||||||
if (tokenText) {
|
if (tokenText) {
|
||||||
const dashMatch = tokenText.length <= 300 ? tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/) : null;
|
const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
if (dashMatch) {
|
if (dashMatch) {
|
||||||
artistName = dashMatch[1].trim();
|
artistName = dashMatch[1].trim();
|
||||||
trackName = dashMatch[2].trim();
|
trackName = dashMatch[2].trim();
|
||||||
@@ -289,6 +327,7 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.lastfm.trackSpotlightAuthor") })
|
||||||
.setTitle(`🎵 ${info.name}`)
|
.setTitle(`🎵 ${info.name}`)
|
||||||
.setURL(info.url || undefined);
|
.setURL(info.url || undefined);
|
||||||
|
|
||||||
@@ -296,30 +335,55 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
embed.setThumbnail(info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]);
|
embed.setThumbnail(info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let desc = "";
|
||||||
|
if (info.artist?.name || info.artist?.["#text"]) {
|
||||||
|
const aName = String(info.artist?.name ?? info.artist?.["#text"]);
|
||||||
|
desc += `*by* **${aName}**`;
|
||||||
|
}
|
||||||
|
if (info.album?.title) {
|
||||||
|
desc += ` · *from* **${info.album.title}**`;
|
||||||
|
}
|
||||||
|
if (info.wiki?.summary) {
|
||||||
|
const cleanSummary = info.wiki.summary.replace(/<[^>]*>/g, "").trim();
|
||||||
|
if (cleanSummary.length > 0) {
|
||||||
|
const truncated = cleanSummary.length > 200 ? cleanSummary.slice(0, 197) + "..." : cleanSummary;
|
||||||
|
desc += (desc ? "\n\n" : "") + truncated;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (desc) embed.setDescription(desc);
|
||||||
|
|
||||||
const fields = [];
|
const fields = [];
|
||||||
|
|
||||||
if (info.artist?.name || info.artist?.["#text"]) {
|
|
||||||
fields.push({ name: "Artist", value: String(info.artist?.name ?? info.artist?.["#text"] ?? "Unknown"), inline: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (info.album?.title) {
|
|
||||||
fields.push({ name: "Album", value: info.album.title, inline: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (info.listeners) {
|
if (info.listeners) {
|
||||||
fields.push({ name: "Listeners", value: Utils.formatNumber(Number(info.listeners)), inline: true });
|
fields.push({
|
||||||
|
name: `👥 ${this.t(msg, "responses.lastfm.trackFieldListeners")}`,
|
||||||
|
value: `**${Utils.formatNumber(Number(info.listeners))}**`,
|
||||||
|
inline: true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (info.playcount) {
|
if (info.playcount) {
|
||||||
fields.push({ name: "Global Plays", value: Utils.formatNumber(Number(info.playcount)), inline: true });
|
fields.push({
|
||||||
|
name: `📈 ${this.t(msg, "responses.lastfm.trackFieldPlays")}`,
|
||||||
|
value: `**${Utils.formatNumber(Number(info.playcount))}**`,
|
||||||
|
inline: true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (info.userplaycount) {
|
if (info.userplaycount) {
|
||||||
fields.push({ name: "Your Plays", value: Utils.formatNumber(Number(info.userplaycount)), inline: true });
|
fields.push({
|
||||||
|
name: `🎧 ${this.t(msg, "responses.lastfm.trackFieldUserPlays")}`,
|
||||||
|
value: `**${Utils.formatNumber(Number(info.userplaycount))}**`,
|
||||||
|
inline: true,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const userLoved = info.userloved === "1" || info.userloved === 1 || info.userloved === true;
|
const userLoved = info.userloved === "1" || info.userloved === 1 || info.userloved === true;
|
||||||
fields.push({ name: "Loved", value: userLoved ? "❤️ Yes" : "🖤 No", inline: true });
|
fields.push({
|
||||||
|
name: `❤️ ${this.t(msg, "responses.lastfm.trackFieldLoved")}`,
|
||||||
|
value: userLoved ? this.t(msg, "responses.lastfm.lovedStatusYes") : this.t(msg, "responses.lastfm.lovedStatusNo"),
|
||||||
|
inline: true,
|
||||||
|
});
|
||||||
|
|
||||||
if (info.toptags?.tag?.length) {
|
if (info.toptags?.tag?.length) {
|
||||||
const tagStr = info.toptags.tag.slice(0, 8).map(t => {
|
const tagStr = info.toptags.tag.slice(0, 8).map(t => {
|
||||||
@@ -327,34 +391,40 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
const tagLower = String(tagName).toLowerCase().replace(/\s+/g, "+");
|
const tagLower = String(tagName).toLowerCase().replace(/\s+/g, "+");
|
||||||
return `[${tagName}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
return `[${tagName}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
||||||
}).join(" · ");
|
}).join(" · ");
|
||||||
fields.push({ name: "Tags", value: tagStr, inline: false });
|
fields.push({
|
||||||
}
|
name: `🏷️ ${this.t(msg, "responses.lastfm.trackFieldTags")}`,
|
||||||
|
value: tagStr,
|
||||||
embed.addFields(...fields);
|
inline: false,
|
||||||
|
});
|
||||||
if (info.wiki?.summary) {
|
|
||||||
const cleanSummary = info.wiki.summary.replace(/<[^>]*>/g, "").trim();
|
|
||||||
if (cleanSummary.length > 0) {
|
|
||||||
const truncated = cleanSummary.length > 200 ? cleanSummary.slice(0, 197) + "..." : cleanSummary;
|
|
||||||
embed.setDescription(truncated);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let similarTracks = [];
|
let similarTracks = [];
|
||||||
try {
|
try {
|
||||||
similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 5);
|
similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 4);
|
||||||
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
|
||||||
if (similarTracks.length) {
|
if (similarTracks.length) {
|
||||||
const simStr = similarTracks.map(t => {
|
const simStr = similarTracks.map(t => {
|
||||||
const matchPct = Math.round(t.match * 100);
|
const matchPct = Math.round(t.match * 100);
|
||||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
return `${link} by **${t.artist}** (${matchPct}%)`;
|
return `${link} — **${t.artist}** \`(${matchPct}% match)\``;
|
||||||
}).join("\n");
|
}).join("\n");
|
||||||
embed.addFields({ name: "Similar Tracks", value: simStr.slice(0, 1024), inline: false });
|
fields.push({
|
||||||
|
name: `✨ ${this.t(msg, "responses.lastfm.trackFieldSimilar")}`,
|
||||||
|
value: simStr.slice(0, 1024),
|
||||||
|
inline: false,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
embed.setFooter({ text: `Last.fm: ${user.username}` });
|
embed.addFields(...fields);
|
||||||
|
embed.setFooter({
|
||||||
|
text: this.t(msg, "responses.lastfm.trackFooterPro", {
|
||||||
|
prefix,
|
||||||
|
user: user.username,
|
||||||
|
track: info.name,
|
||||||
|
artist: artistName,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
@@ -494,9 +564,11 @@ export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUs
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(this.t(msg, "responses.lastfm.coverTitle", { album: albumTitle }))
|
.setAuthor({ name: this.t(msg, "responses.lastfm.coverAuthor") })
|
||||||
|
.setTitle(albumTitle)
|
||||||
|
.setDescription(`🎵 **${trackName}** ${String.fromCharCode(8212)} **${artistName}**`)
|
||||||
.setImage(coverUrl)
|
.setImage(coverUrl)
|
||||||
.setFooter({ text: this.t(msg, "responses.lastfm.coverFooter", { track: trackName, artist: artistName }) });
|
.setFooter({ text: this.t(msg, "responses.lastfm.coverFooterPro", { prefix }) });
|
||||||
|
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,25 +36,32 @@ export const LISTENING_ACTIONS = new Set([
|
|||||||
* @param {function(string, object=): string} tr - Translator bound to the invoking message.
|
* @param {function(string, object=): string} tr - Translator bound to the invoking message.
|
||||||
* @param {boolean} [showPlaycount=false] - Whether to show play counts.
|
* @param {boolean} [showPlaycount=false] - Whether to show play counts.
|
||||||
* @param {string} [prefix="%"] - The command prefix for the footer hint.
|
* @param {string} [prefix="%"] - The command prefix for the footer hint.
|
||||||
|
* @param {string|null} [authorName=null] - Optional author header text.
|
||||||
* @returns {EmbedBuilder} The constructed embed.
|
* @returns {EmbedBuilder} The constructed embed.
|
||||||
*/
|
*/
|
||||||
function buildTrackList(username, title, tracks, tr, showPlaycount = false, prefix = "%") {
|
function buildTrackList(username, title, tracks, tr, showPlaycount = false, prefix = "%", authorName = null) {
|
||||||
const lines = tracks.map((t, i) => {
|
const lines = tracks.map((t, i) => {
|
||||||
const num = String(i + 1).padStart(2, " ");
|
const num = String(i + 1).padStart(2, "0");
|
||||||
let name = t.name;
|
let name = t.name;
|
||||||
if (name.length > 40) name = name.slice(0, 37) + "...";
|
if (name.length > 40) name = name.slice(0, 37) + "...";
|
||||||
const link = t.url ? `[${name}](${t.url})` : name;
|
const link = t.url ? `[${name}](${t.url})` : name;
|
||||||
const extra = showPlaycount && t.playcount ? ` (${t.playcount} ${tr("responses.lastfm.plays")})` : "";
|
const extra = showPlaycount && t.playcount ? ` \`(${t.playcount} ${tr("responses.lastfm.plays")})\`` : "";
|
||||||
return `\`${num}.\` ${link} — **${t.artist}**${extra}`;
|
return `\`${num}.\` ${link} — **${t.artist}**${extra}`;
|
||||||
});
|
});
|
||||||
|
|
||||||
const desc = lines.join("\n").slice(0, 4096);
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
return new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(title) /* locale titles (lovedTitle/topTitle/recentTitle) already embed {{username}} */
|
.setTitle(title) /* locale titles (lovedTitle/topTitle/recentTitle) already embed {{username}} */
|
||||||
.setDescription(desc)
|
.setDescription(desc)
|
||||||
.setFooter({ text: tr("responses.lastfm.trackListFooter", { prefix }) });
|
.setFooter({ text: tr("responses.lastfm.trackListFooter", { prefix }) });
|
||||||
|
|
||||||
|
if (authorName) {
|
||||||
|
embed.setAuthor({ name: authorName });
|
||||||
|
}
|
||||||
|
|
||||||
|
return embed;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -70,29 +77,43 @@ function buildTrackList(username, title, tracks, tr, showPlaycount = false, pref
|
|||||||
* @returns {EmbedBuilder} The constructed embed.
|
* @returns {EmbedBuilder} The constructed embed.
|
||||||
*/
|
*/
|
||||||
function buildLeaderboardEmbed(lb, pageIdx, prefix, tr, opts = {}) {
|
function buildLeaderboardEmbed(lb, pageIdx, prefix, tr, opts = {}) {
|
||||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
|
||||||
const startRank = pageIdx * lb.perPage;
|
const startRank = pageIdx * lb.perPage;
|
||||||
const requesterId = opts.requesterId ? String(opts.requesterId) : null;
|
const requesterId = opts.requesterId ? String(opts.requesterId) : null;
|
||||||
|
|
||||||
const lines = lb.entries.map((entry, i) => {
|
const lines = lb.entries.map((entry, i) => {
|
||||||
const rank = startRank + i + 1;
|
const rank = startRank + i + 1;
|
||||||
const head = rank <= 3 ? `${MEDALS[rank - 1]} ` : "";
|
|
||||||
const who = entry.userId ? `<@${entry.userId}>` : (entry.username || "?");
|
const who = entry.userId ? `<@${entry.userId}>` : (entry.username || "?");
|
||||||
const lfName = entry.username ? ` — *${entry.username}*` : "";
|
const lfName = entry.username ? ` (*${entry.username}*)` : "";
|
||||||
const marker = requesterId && String(entry.userId) === requesterId ? ` **${tr("responses.lastfm.leaderboardYou")}**` : "";
|
const marker = requesterId && String(entry.userId) === requesterId ? ` **${tr("responses.lastfm.leaderboardYou")}**` : "";
|
||||||
const count = Utils.formatNumber(entry.scrobbleCount);
|
const count = Utils.formatNumber(entry.scrobbleCount);
|
||||||
return `${head}**${rank}.** ${who}${lfName} — **${count}** ${tr("responses.lastfm.leaderboardScrobbles")}${marker}`;
|
|
||||||
|
if (rank === 1) {
|
||||||
|
return `🥇 **#1 ${tr("responses.lastfm.leaderboardChampion")}**\n> ${who}${lfName} — **${count}** ${tr("responses.lastfm.leaderboardScrobbles")}${marker}`;
|
||||||
|
}
|
||||||
|
if (rank === 2) {
|
||||||
|
return `🥈 **#2** ${who}${lfName} — **${count}** ${tr("responses.lastfm.leaderboardScrobbles")}${marker}`;
|
||||||
|
}
|
||||||
|
if (rank === 3) {
|
||||||
|
return `🥉 **#3** ${who}${lfName} — **${count}** ${tr("responses.lastfm.leaderboardScrobbles")}${marker}`;
|
||||||
|
}
|
||||||
|
const num = String(rank).padStart(2, "0");
|
||||||
|
return `\`${num}.\` ${who}${lfName} — **${count}** ${tr("responses.lastfm.leaderboardScrobbles")}${marker}`;
|
||||||
});
|
});
|
||||||
|
|
||||||
const desc = (lines.join("\n") + (opts.extraLine ? `\n\n${opts.extraLine}` : "")).slice(0, 4096);
|
let desc = lines.join("\n\n");
|
||||||
|
if (opts.extraLine) {
|
||||||
|
desc += `\n\n────────────────────\n${opts.extraLine}`;
|
||||||
|
}
|
||||||
|
|
||||||
const title = lb.scope === "server"
|
const title = lb.scope === "server"
|
||||||
? tr("responses.lastfm.leaderboardTitleServer")
|
? tr("responses.lastfm.leaderboardTitleServer")
|
||||||
: tr("responses.lastfm.leaderboardTitleGlobal");
|
: tr("responses.lastfm.leaderboardTitleGlobal");
|
||||||
|
|
||||||
return new EmbedBuilder()
|
return new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: tr("responses.lastfm.leaderboardAuthorPro") })
|
||||||
.setTitle(title)
|
.setTitle(title)
|
||||||
.setDescription(desc)
|
.setDescription(desc.slice(0, 4096))
|
||||||
.setFooter({ text: tr("responses.lastfm.leaderboardFooterSync", { prefix }) });
|
.setFooter({ text: tr("responses.lastfm.leaderboardFooterSync", { prefix }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +151,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg.reply({ embeds: [buildTrackList(user.username, tr("responses.lastfm.lovedTitle", { username: user.username }), tracks, tr, false, prefix)] });
|
return msg.reply({ embeds: [buildTrackList(user.username, tr("responses.lastfm.lovedTitle", { username: user.username }), tracks, tr, false, prefix, tr("responses.lastfm.trackListAuthorLoved"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
case "top": {
|
case "top": {
|
||||||
@@ -155,7 +176,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar
|
|||||||
}
|
}
|
||||||
|
|
||||||
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
||||||
return msg.reply({ embeds: [buildTrackList(user.username, tr("responses.lastfm.topTitle", { username: user.username }) + periodLabel, tracks, tr, true, prefix)] });
|
return msg.reply({ embeds: [buildTrackList(user.username, tr("responses.lastfm.topTitle", { username: user.username }) + periodLabel, tracks, tr, true, prefix, tr("responses.lastfm.trackListAuthorTop"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
case "leaderboard":
|
case "leaderboard":
|
||||||
@@ -273,7 +294,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg.reply({ embeds: [buildTrackList(user.username, tr("responses.lastfm.recentTitle", { username: user.username }), tracks, tr, false, prefix)] });
|
return msg.reply({ embeds: [buildTrackList(user.username, tr("responses.lastfm.recentTitle", { username: user.username }), tracks, tr, false, prefix, tr("responses.lastfm.trackListAuthorRecent"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
case "artists": {
|
case "artists": {
|
||||||
@@ -299,7 +320,7 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar
|
|||||||
|
|
||||||
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
||||||
const lines = artists.map((a, i) => {
|
const lines = artists.map((a, i) => {
|
||||||
const num = String(i + 1).padStart(2, " ");
|
const num = String(i + 1).padStart(2, "0");
|
||||||
let name = a.name;
|
let name = a.name;
|
||||||
if (name.length > 40) name = name.slice(0, 37) + "...";
|
if (name.length > 40) name = name.slice(0, 37) + "...";
|
||||||
const link = a.url ? `[${name}](${a.url})` : name;
|
const link = a.url ? `[${name}](${a.url})` : name;
|
||||||
@@ -311,7 +332,8 @@ export async function runListeningActions(msg, data, lastfm, prefix, userId, tar
|
|||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(tr("responses.lastfm.artistsTitle", { username: user.username }) + periodLabel)
|
.setAuthor({ name: tr("responses.lastfm.artistsTitle", { username: user.username }) })
|
||||||
|
.setTitle(`🎤 ${tr("responses.lastfm.artistsTitle", { username: user.username })}${periodLabel}`)
|
||||||
.setDescription(desc)
|
.setDescription(desc)
|
||||||
.setFooter({ text: tr("responses.lastfm.artistsFooter", { prefix }) })]
|
.setFooter({ text: tr("responses.lastfm.artistsFooter", { prefix }) })]
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -109,9 +109,12 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
|||||||
let statusMsg;
|
let statusMsg;
|
||||||
try {
|
try {
|
||||||
statusMsg = await msg.reply({
|
statusMsg = await msg.reply({
|
||||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
embeds: [new EmbedBuilder().setColor(getGlobalColor())
|
||||||
`${categoryEmoji} Fetching your ${categoryLabel} tracks from Last.fm${resolveLabel}...`
|
.setAuthor({ name: ctx.t(msg, "responses.lastfm.playDirectoryAuthor") })
|
||||||
)]
|
.setTitle(ctx.t(msg, "responses.lastfm.playLoadingTitle"))
|
||||||
|
.setDescription(
|
||||||
|
`${categoryEmoji} Fetching your ${categoryLabel} tracks from Last.fm${resolveLabel}...`
|
||||||
|
)]
|
||||||
});
|
});
|
||||||
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||||
|
|
||||||
@@ -128,9 +131,11 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!result.tracks.length) {
|
if (!result.tracks.length) {
|
||||||
const noTracks = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
const noTracks = { embeds: [new EmbedBuilder().setColor(getGlobalColor())
|
||||||
`${categoryEmoji} No ${categoryLabel.toLowerCase()} tracks found for **${result.username}**.`
|
.setAuthor({ name: ctx.t(msg, "responses.lastfm.playDirectoryAuthor") })
|
||||||
)] };
|
.setDescription(
|
||||||
|
`${categoryEmoji} No ${categoryLabel.toLowerCase()} tracks found for **${result.username}**.`
|
||||||
|
)] };
|
||||||
if (statusMsg) statusMsg.edit(noTracks).catch(() => msg.reply(noTracks));
|
if (statusMsg) statusMsg.edit(noTracks).catch(() => msg.reply(noTracks));
|
||||||
else msg.reply(noTracks);
|
else msg.reply(noTracks);
|
||||||
return;
|
return;
|
||||||
@@ -141,9 +146,18 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
|||||||
|
|
||||||
if (statusMsg) {
|
if (statusMsg) {
|
||||||
statusMsg.edit({
|
statusMsg.edit({
|
||||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
embeds: [new EmbedBuilder().setColor(getGlobalColor())
|
||||||
`${categoryEmoji} Loading **${result.tracks.length}** ${categoryLabel.toLowerCase()} tracks from **${result.username}**${resolveLabel}...`
|
.setAuthor({ name: ctx.t(msg, "responses.lastfm.playDirectoryAuthor") })
|
||||||
)]
|
.setTitle(ctx.t(msg, "responses.lastfm.playLoadingTitle"))
|
||||||
|
.setDescription(
|
||||||
|
ctx.t(msg, "responses.lastfm.playLoadingDesc", {
|
||||||
|
emoji: categoryEmoji,
|
||||||
|
count: result.tracks.length,
|
||||||
|
category: categoryLabel.toLowerCase(),
|
||||||
|
username: result.username,
|
||||||
|
provider: resolveLabel,
|
||||||
|
})
|
||||||
|
)]
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,12 +182,17 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const summary = [];
|
const summary = [];
|
||||||
if (added > 0) summary.push(`✅ Added **${added}** track${added !== 1 ? "s" : ""} to the queue`);
|
if (added > 0) summary.push(`✅ ${ctx.t(msg, "responses.lastfm.playDoneAdded", { count: added })}`);
|
||||||
if (failed > 0) summary.push(`⚠️ ${failed} track${failed !== 1 ? "s" : ""} couldn't be found`);
|
if (failed > 0) summary.push(`⚠️ ${ctx.t(msg, "responses.lastfm.playDoneNotFound", { count: failed })}`);
|
||||||
|
|
||||||
const doneEmbed = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
const doneEmbed = { embeds: [new EmbedBuilder().setColor(getGlobalColor())
|
||||||
`${categoryEmoji} **${categoryLabel} Tracks — ${result.username}**\n${summary.join(" · ")}`
|
.setAuthor({ name: ctx.t(msg, "responses.lastfm.playDirectoryAuthor") })
|
||||||
)] };
|
.setTitle(ctx.t(msg, "responses.lastfm.playDoneTitle"))
|
||||||
|
.setDescription(
|
||||||
|
`${categoryEmoji} **${categoryLabel} Tracks — ${result.username}**\n\n` +
|
||||||
|
summary.join("\n")
|
||||||
|
)
|
||||||
|
.setFooter({ text: ctx.t(msg, "responses.lastfm.playDirectoryFooter", { prefix }) })] };
|
||||||
|
|
||||||
if (statusMsg) statusMsg.edit(doneEmbed).catch(() => msg.reply(doneEmbed));
|
if (statusMsg) statusMsg.edit(doneEmbed).catch(() => msg.reply(doneEmbed));
|
||||||
else msg.reply(doneEmbed);
|
else msg.reply(doneEmbed);
|
||||||
@@ -278,42 +297,33 @@ export async function runPlaybackActions(msg, data, lastfm, prefix, userId, targ
|
|||||||
|
|
||||||
if (!parsed.category) {
|
if (!parsed.category) {
|
||||||
const lfProviderNote = parsed.showAllCategories && parsed.resolveProvider
|
const lfProviderNote = parsed.showAllCategories && parsed.resolveProvider
|
||||||
? `\n\n💡 \`${prefix}lastfm play ${parsed.resolveProvider}:<category>\` — Specify a category after the provider:`
|
? `\n💡 \`${prefix}lastfm play ${parsed.resolveProvider}:<category>\``
|
||||||
: "";
|
: "";
|
||||||
return msg.reply({
|
|
||||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([
|
const directoryEmbed = new EmbedBuilder()
|
||||||
`❌ Usage: \`${prefix}lastfm play <category>\``,
|
.setColor(getGlobalColor())
|
||||||
``,
|
.setAuthor({ name: this.t(msg, "responses.lastfm.playDirectoryAuthor") })
|
||||||
`**Categories:**`,
|
.setTitle(this.t(msg, "responses.lastfm.playDirectoryTitle"))
|
||||||
`\`loved\` — Play your loved tracks`,
|
.setDescription(
|
||||||
`\`top\` — Play your top tracks`,
|
`\`${prefix}lastfm play <category> [provider]\`\n\n` +
|
||||||
`\`recent\` — Play your recent tracks`,
|
`**${this.t(msg, "responses.lastfm.playDirectoryCollections")}:**\n` +
|
||||||
`\`albums\` — Play your top albums`,
|
`• \`loved\` — ${this.t(msg, "responses.lastfm.playCategoryLoved")}\n` +
|
||||||
`\`artists\` — Play your top artists' tracks`,
|
`• \`top\` — ${this.t(msg, "responses.lastfm.playCategoryTop")}\n` +
|
||||||
`\`playlist <number>\` — Play a playlist (use \`${prefix}lastfm playlists\` to list)`,
|
`• \`recent\` — ${this.t(msg, "responses.lastfm.playCategoryRecent")}\n` +
|
||||||
``,
|
`• \`albums\` — ${this.t(msg, "responses.lastfm.playCategoryAlbums")}\n` +
|
||||||
`**With a search provider (defaults to \`top\`):**`,
|
`• \`artists\` — ${this.t(msg, "responses.lastfm.playCategoryArtists")}\n` +
|
||||||
`\`${prefix}lastfm play td\` or \`${prefix}lastfm play td:top\` — Play top tracks, search on Tidal`,
|
`• \`playlist <num>\` — ${this.t(msg, "responses.lastfm.playCategoryPlaylist")}`
|
||||||
`\`${prefix}lastfm play sp\` or \`${prefix}lastfm play sp:top\` — Play top tracks, search on Spotify`,
|
)
|
||||||
`\`${prefix}lastfm play dz\` or \`${prefix}lastfm play dz:top\` — Play top tracks, search on Deezer`,
|
.addFields({
|
||||||
`\`${prefix}lastfm play yt\` or \`${prefix}lastfm play yt:top\` — Play top tracks, search on YouTube`,
|
name: `🌐 ${this.t(msg, "responses.lastfm.playDirectoryProviders")}`,
|
||||||
``,
|
value:
|
||||||
`**Last.fm as resolve provider (all categories):**`,
|
"`sp` (Spotify) · `td` (Tidal) · `dz` (Deezer) · `yt` (YouTube) · `lf` (Last.fm)\n" +
|
||||||
`\`${prefix}lastfm play lf:loved\` — Play loved tracks, search on Last.fm`,
|
`*Examples:* \`${prefix}fm play loved\` · \`${prefix}fm play td:top\` · \`${prefix}fm play lf:loved\`${lfProviderNote}`,
|
||||||
`\`${prefix}lastfm play lf:top\` — Play top tracks, search on Last.fm`,
|
inline: false,
|
||||||
`\`${prefix}lastfm play lf:recent\` — Play recent tracks, search on Last.fm`,
|
})
|
||||||
`\`${prefix}lastfm play lf:albums\` — Play top albums, search on Last.fm`,
|
.setFooter({ text: this.t(msg, "responses.lastfm.playDirectoryFooter", { prefix }) });
|
||||||
`\`${prefix}lastfm play lf:artists\` — Play top artists, search on Last.fm`,
|
|
||||||
``,
|
return msg.reply({ embeds: [directoryEmbed] });
|
||||||
`**Examples:**`,
|
|
||||||
`\`${prefix}lastfm play loved\``,
|
|
||||||
`\`${prefix}lastfm play td\``,
|
|
||||||
`\`${prefix}lastfm play sp:top\``,
|
|
||||||
`\`${prefix}lastfm play lf:loved\``,
|
|
||||||
`\`${prefix}lastfm play playlist 1\``,
|
|
||||||
lfProviderNote,
|
|
||||||
].join("\n"))]
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return playLastFmCategory(this, msg, userId, parsed.category, {
|
return playLastFmCategory(this, msg, userId, parsed.category, {
|
||||||
|
|||||||
+43
-26
@@ -75,39 +75,56 @@ export async function runTagActions(msg, data, lastfm, prefix, userId, targetUse
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(`🏷️ ${tagInfo.name}`)
|
.setAuthor({ name: this.t(msg, "responses.lastfm.tagAuthor") })
|
||||||
.setURL(tagInfo.url || undefined);
|
.setTitle(tagInfo.name)
|
||||||
|
.setURL(tagInfo.url || undefined)
|
||||||
const fields = [];
|
.setFooter({ text: this.t(msg, "responses.lastfm.tagFooterPro", { tag: tagInfo.name }) });
|
||||||
fields.push({ name: "Reach", value: Utils.formatNumber(tagInfo.reach), inline: true });
|
|
||||||
fields.push({ name: "Total Taggings", value: Utils.formatNumber(tagInfo.count), inline: true });
|
|
||||||
|
|
||||||
if (topArtists.length) {
|
|
||||||
const artistStr = topArtists.map((a, i) => {
|
|
||||||
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
|
||||||
return `${i + 1}. ${link} (**${Utils.formatNumber(a.playcount)}** ${this.t(msg, "responses.lastfm.plays")})`;
|
|
||||||
}).join("\n");
|
|
||||||
fields.push({ name: "Top Artists", value: artistStr.slice(0, 1024), inline: false });
|
|
||||||
}
|
|
||||||
|
|
||||||
if (topTracks.length) {
|
|
||||||
const trackStr = topTracks.map((t, i) => {
|
|
||||||
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
|
||||||
return `${i + 1}. ${link} by **${t.artist}**`;
|
|
||||||
}).join("\n");
|
|
||||||
fields.push({ name: "Top Tracks", value: trackStr.slice(0, 1024), inline: false });
|
|
||||||
}
|
|
||||||
|
|
||||||
embed.addFields(...fields);
|
|
||||||
|
|
||||||
if (tagInfo.summary) {
|
if (tagInfo.summary) {
|
||||||
const cleanSummary = tagInfo.summary.replace(/<[^>]*>/g, "").trim();
|
const cleanSummary = tagInfo.summary.replace(/<[^>]*>/g, "").trim();
|
||||||
if (cleanSummary.length > 0) {
|
if (cleanSummary.length > 0) {
|
||||||
const truncated = cleanSummary.length > 300 ? cleanSummary.slice(0, 297) + "..." : cleanSummary;
|
const truncated = cleanSummary.length > 280 ? cleanSummary.slice(0, 277) + "..." : cleanSummary;
|
||||||
embed.setDescription(truncated);
|
embed.setDescription(`> *${truncated}*`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
embed.addFields(
|
||||||
|
{
|
||||||
|
name: this.t(msg, "responses.lastfm.tagFieldReach"),
|
||||||
|
value: `👥 **${Utils.formatNumber(tagInfo.reach)}**`,
|
||||||
|
inline: true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: this.t(msg, "responses.lastfm.tagFieldTaggings"),
|
||||||
|
value: `🏷️ **${Utils.formatNumber(tagInfo.count)}**`,
|
||||||
|
inline: true
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (topArtists.length) {
|
||||||
|
const artistStr = topArtists.slice(0, 5).map((a, i) => {
|
||||||
|
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||||
|
return `\`${i + 1}.\` ${link} (${Utils.formatNumber(a.playcount)} ${this.t(msg, "responses.lastfm.plays")})`;
|
||||||
|
}).join(" · ");
|
||||||
|
embed.addFields({
|
||||||
|
name: this.t(msg, "responses.lastfm.tagFieldPillars"),
|
||||||
|
value: artistStr.slice(0, 1024),
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (topTracks.length) {
|
||||||
|
const trackStr = topTracks.slice(0, 5).map((t, i) => {
|
||||||
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
|
return `\`${i + 1}.\` ${link} — **${t.artist}**`;
|
||||||
|
}).join("\n");
|
||||||
|
embed.addFields({
|
||||||
|
name: this.t(msg, "responses.lastfm.tagFieldTopTracks"),
|
||||||
|
value: trackStr.slice(0, 1024),
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+124
-53
@@ -124,18 +124,30 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ
|
|||||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||||
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
||||||
|
|
||||||
const lines = listeners.map((l, i) => {
|
const top1 = listeners[0];
|
||||||
const medal = i < 3 ? MEDALS[i] : ` `;
|
|
||||||
return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
const desc = lines.join("\n").slice(0, 4096);
|
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(this.t(msg, "responses.lastfm.whoknowsTitle", { artist: artistName }))
|
.setAuthor({ name: this.t(msg, "responses.lastfm.serverLeaderboardAuthor") })
|
||||||
.setDescription(desc)
|
.setTitle(artistName)
|
||||||
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) });
|
.setFooter({ text: `${listeners.length} listener${listeners.length !== 1 ? "s" : ""} • ${Utils.formatNumber(totalPlays)} total plays • %fm` });
|
||||||
|
|
||||||
|
if (top1) {
|
||||||
|
embed.addFields({
|
||||||
|
name: this.t(msg, "responses.lastfm.crownHolder"),
|
||||||
|
value: `**${top1.username}** — **${Utils.formatNumber(top1.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`,
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const rest = listeners.slice(1);
|
||||||
|
if (rest.length > 0) {
|
||||||
|
const lines = rest.map((l, i) => {
|
||||||
|
const rank = i + 2;
|
||||||
|
const medal = rank === 2 ? "🥈" : rank === 3 ? "🥉" : `\`#${rank}\``;
|
||||||
|
return `${medal} **${l.username}** — **${Utils.formatNumber(l.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`;
|
||||||
|
});
|
||||||
|
embed.setDescription(lines.join("\n").slice(0, 4096));
|
||||||
|
}
|
||||||
|
|
||||||
const replyPayload = { embeds: [embed] };
|
const replyPayload = { embeds: [embed] };
|
||||||
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||||
@@ -180,25 +192,40 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pct = Math.min(100, Math.max(0, Math.round(comparison.matchPercentage ?? 0)));
|
||||||
|
const filledBars = Math.round(pct / 10);
|
||||||
|
const emptyBars = 10 - filledBars;
|
||||||
|
const bar = "█".repeat(filledBars) + "░".repeat(emptyBars);
|
||||||
|
|
||||||
|
let level = "Low";
|
||||||
|
if (pct >= 80) level = "Super";
|
||||||
|
else if (pct >= 60) level = "High";
|
||||||
|
else if (pct >= 40) level = "Medium";
|
||||||
|
else if (pct >= 20) level = "Fair";
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(this.t(msg, "responses.lastfm.compareTitle"))
|
.setAuthor({ name: this.t(msg, "responses.lastfm.compareAuthor") })
|
||||||
.setDescription([
|
.setTitle(`${comparison.user1.username} & ${comparison.user2.username}`)
|
||||||
`**${comparison.user1.username}** vs **${comparison.user2.username}**`,
|
.setDescription(
|
||||||
``,
|
`📊 **[${bar}] ${pct}% MATCH**\n` +
|
||||||
`📊 **${comparison.matchPercentage}%** match`,
|
`*${this.t(msg, "responses.lastfm.compareMeter", { level, score: pct })}*\n\n` +
|
||||||
``,
|
`👤 **${comparison.user1.username}**: ${Utils.formatNumber(comparison.user1.totalArtists)} artists · ` +
|
||||||
`👤 ${comparison.user1.username}: ${comparison.user1.totalArtists} top artists`,
|
`👤 **${comparison.user2.username}**: ${Utils.formatNumber(comparison.user2.totalArtists)} artists`
|
||||||
`👤 ${comparison.user2.username}: ${comparison.user2.totalArtists} top artists`,
|
)
|
||||||
].join("\n"));
|
.setFooter({ text: this.t(msg, "responses.lastfm.compareFooterPro", { prefix }) });
|
||||||
|
|
||||||
if (comparison.commonArtists?.length) {
|
if (comparison.commonArtists?.length) {
|
||||||
const commonStr = comparison.commonArtists.slice(0, 15).map((a, i) => {
|
const commonStr = comparison.commonArtists.slice(0, 10).map((a, i) => {
|
||||||
const num = String(i + 1).padStart(2, " ");
|
const num = String(i + 1).padStart(2, " ");
|
||||||
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||||
return `\`${num}.\` ${link} (**${a.playcount}** ${this.t(msg, "responses.lastfm.plays")})`;
|
return `\`${num}.\` ${link} — **${Utils.formatNumber(a.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`;
|
||||||
}).join("\n");
|
}).join("\n");
|
||||||
embed.addFields({ name: `Common Artists (${comparison.commonArtists.length})`, value: commonStr.slice(0, 1024), inline: false });
|
embed.addFields({
|
||||||
|
name: `${this.t(msg, "responses.lastfm.compareFieldShared")} (${comparison.commonArtists.length})`,
|
||||||
|
value: commonStr.slice(0, 1024),
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
@@ -328,22 +355,44 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ
|
|||||||
filteredCrowns = crowns.slice(0, 10);
|
filteredCrowns = crowns.slice(0, 10);
|
||||||
}
|
}
|
||||||
|
|
||||||
const lines = filteredCrowns.slice(0, 20).map(c => {
|
const topCrown = filteredCrowns[0];
|
||||||
const link = c.artistUrl ? `[${c.artist}](${c.artistUrl})` : c.artist;
|
const rest = filteredCrowns.slice(1, 15);
|
||||||
const nextStr = c.nextBest ? ` (next: **${c.nextBest.username}** with ${Utils.formatNumber(c.nextBest.playcount)})` : "";
|
|
||||||
return `👑 ${link} — **${Utils.formatNumber(c.userPlaycount)}** ${this.t(msg, "responses.lastfm.plays")}${nextStr}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
const desc = lines.join("\n").slice(0, 4096);
|
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.lastfm.crownsAuthor") })
|
||||||
.setTitle(this.t(msg, "responses.lastfm.crownsTitle", { username: user.username }))
|
.setTitle(this.t(msg, "responses.lastfm.crownsTitle", { username: user.username }))
|
||||||
.setDescription(desc)
|
.setFooter({ text: this.t(msg, "responses.lastfm.crownsFooterPro", { prefix }) });
|
||||||
.setFooter({ text: this.t(msg, "responses.lastfm.crownsFooter", { count: filteredCrowns.length, plural: filteredCrowns.length !== 1 ? "s" : "" }) });
|
|
||||||
|
|
||||||
if (filteredCrowns[0]?.image) {
|
if (topCrown) {
|
||||||
embed.setThumbnail(filteredCrowns[0].image);
|
const topLink = topCrown.artistUrl ? `[${topCrown.artist}](${topCrown.artistUrl})` : topCrown.artist;
|
||||||
|
let leadDesc = this.t(msg, "responses.lastfm.crownsUncontested");
|
||||||
|
if (topCrown.nextBest && topCrown.nextBest.playcount > 0) {
|
||||||
|
const lead = topCrown.userPlaycount - topCrown.nextBest.playcount;
|
||||||
|
leadDesc = `${this.t(msg, "responses.lastfm.crownsLead", { lead: Utils.formatNumber(lead) })} · ${this.t(msg, "responses.lastfm.crownsRunnerUp", { user: topCrown.nextBest.username, plays: Utils.formatNumber(topCrown.nextBest.playcount) })}`;
|
||||||
|
}
|
||||||
|
embed.addFields({
|
||||||
|
name: `👑 ${this.t(msg, "responses.lastfm.crownsMonopolyField")}`,
|
||||||
|
value: `**${topLink}** — **${Utils.formatNumber(topCrown.userPlaycount)}** ${this.t(msg, "responses.lastfm.plays")}\n*${leadDesc}*`,
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rest.length > 0) {
|
||||||
|
const otherLines = rest.map(c => {
|
||||||
|
const link = c.artistUrl ? `[${c.artist}](${c.artistUrl})` : c.artist;
|
||||||
|
const runner = c.nextBest ? ` (${c.nextBest.username}: ${Utils.formatNumber(c.nextBest.playcount)})` : "";
|
||||||
|
return `👑 ${link} — **${Utils.formatNumber(c.userPlaycount)}**${runner}`;
|
||||||
|
});
|
||||||
|
embed.addFields({
|
||||||
|
name: `🏛️ ${this.t(msg, "responses.lastfm.crownsOtherField")} (${filteredCrowns.length})`,
|
||||||
|
value: otherLines.join("\n").slice(0, 1024),
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (topCrown?.image) {
|
||||||
|
embed.setThumbnail(topCrown.image);
|
||||||
}
|
}
|
||||||
|
|
||||||
const replyPayload = { embeds: [embed] };
|
const replyPayload = { embeds: [embed] };
|
||||||
@@ -417,22 +466,33 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
|
||||||
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
||||||
|
const top1 = listeners[0];
|
||||||
const lines = listeners.map((l, i) => {
|
|
||||||
const medal = i < 3 ? MEDALS[i] : ` `;
|
|
||||||
return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
const desc = lines.join("\n").slice(0, 4096);
|
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(this.t(msg, "responses.lastfm.whoknowsTrackTitle", { track: trackName }))
|
.setAuthor({ name: this.t(msg, "responses.lastfm.trackLeaderboardAuthor") })
|
||||||
.setDescription(desc)
|
.setTitle(trackName + (artistName ? ` by ${artistName}` : ""))
|
||||||
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsTrackFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays), artist: artistName }) });
|
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsTrackFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays), artist: artistName }) });
|
||||||
|
|
||||||
|
if (top1) {
|
||||||
|
embed.addFields({
|
||||||
|
name: this.t(msg, "responses.lastfm.crownHolder"),
|
||||||
|
value: `**${top1.username}** — **${Utils.formatNumber(top1.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`,
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const rest = listeners.slice(1);
|
||||||
|
if (rest.length > 0) {
|
||||||
|
const lines = rest.map((l, i) => {
|
||||||
|
const rank = i + 2;
|
||||||
|
const medal = rank === 2 ? "🥈" : rank === 3 ? "🥉" : `\`#${rank}\``;
|
||||||
|
return `${medal} **${l.username}** — **${Utils.formatNumber(l.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`;
|
||||||
|
});
|
||||||
|
embed.setDescription(lines.join("\n").slice(0, 4096));
|
||||||
|
}
|
||||||
|
|
||||||
const replyPayload = { embeds: [embed] };
|
const replyPayload = { embeds: [embed] };
|
||||||
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||||
else msg.reply(replyPayload);
|
else msg.reply(replyPayload);
|
||||||
@@ -498,22 +558,33 @@ export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targ
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MEDALS = ["🥇", "🥈", "🥉"];
|
|
||||||
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
||||||
|
const top1 = listeners[0];
|
||||||
const lines = listeners.map((l, i) => {
|
|
||||||
const medal = i < 3 ? MEDALS[i] : ` `;
|
|
||||||
return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`;
|
|
||||||
});
|
|
||||||
|
|
||||||
const desc = lines.join("\n").slice(0, 4096);
|
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(this.t(msg, "responses.lastfm.whoknowsAlbumTitle", { album: albumName }))
|
.setAuthor({ name: this.t(msg, "responses.lastfm.albumLeaderboardAuthor") })
|
||||||
.setDescription(desc)
|
.setTitle(albumName + (artistName ? ` by ${artistName}` : ""))
|
||||||
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) });
|
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) });
|
||||||
|
|
||||||
|
if (top1) {
|
||||||
|
embed.addFields({
|
||||||
|
name: this.t(msg, "responses.lastfm.crownHolder"),
|
||||||
|
value: `**${top1.username}** — **${Utils.formatNumber(top1.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`,
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const rest = listeners.slice(1);
|
||||||
|
if (rest.length > 0) {
|
||||||
|
const lines = rest.map((l, i) => {
|
||||||
|
const rank = i + 2;
|
||||||
|
const medal = rank === 2 ? "🥈" : rank === 3 ? "🥉" : `\`#${rank}\``;
|
||||||
|
return `${medal} **${l.username}** — **${Utils.formatNumber(l.playcount)}** ${this.t(msg, "responses.lastfm.plays")}`;
|
||||||
|
});
|
||||||
|
embed.setDescription(lines.join("\n").slice(0, 4096));
|
||||||
|
}
|
||||||
|
|
||||||
const replyPayload = { embeds: [embed] };
|
const replyPayload = { embeds: [embed] };
|
||||||
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||||
else msg.reply(replyPayload);
|
else msg.reply(replyPayload);
|
||||||
|
|||||||
+39
-13
@@ -6,13 +6,13 @@
|
|||||||
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 { logger } from "../src/core/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { getGlobalColor, cleanId } from "../src/ui/index.mjs";
|
import { cleanId } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the leave/stop command. */
|
/** @type {CommandBuilder} @description Command definition for the leave/stop command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("leave")
|
.setName("leave")
|
||||||
.setDescription("Make the bot leave a voice channel", "commands.leave")
|
.setDescription("Make the bot leave a voice channel", "commands.leave")
|
||||||
.addAliases("l", "stop")
|
.addAliases("l", "dc", "discounted", "bye")
|
||||||
.setCategory("music")
|
.setCategory("music")
|
||||||
.addChannelOption(o =>
|
.addChannelOption(o =>
|
||||||
o.setName("channel")
|
o.setName("channel")
|
||||||
@@ -71,20 +71,27 @@ export async function run(msg, data) {
|
|||||||
if (userChannelId) targetChannelId = cleanId(userChannelId);
|
if (userChannelId) targetChannelId = cleanId(userChannelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const leaveNotice = (desc) => new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `👋 ${this.t(msg, "responses.leave.sessionEndedTitle")}` })
|
||||||
|
.setDescription(desc);
|
||||||
|
|
||||||
if (!targetChannelId) {
|
if (!targetChannelId) {
|
||||||
if (guildPlayers.length === 0) {
|
if (guildPlayers.length === 0) {
|
||||||
return msg.reply(this.t(msg, "responses.leave.notInVoice"));
|
return msg.reply({ embeds: [leaveNotice(this.t(msg, "responses.leave.notInVoice"))] });
|
||||||
}
|
}
|
||||||
const channelList = guildPlayers.map(([mapKey, p]) => {
|
const channelList = guildPlayers.map(([mapKey, p]) => {
|
||||||
const id = cleanId(p._channelId ?? mapKey);
|
const id = cleanId(p._channelId ?? mapKey);
|
||||||
return id ? `<#${id}>` : "\`unknown\`";
|
return id ? `<#${id}>` : "\`unknown\`";
|
||||||
});
|
});
|
||||||
return msg.reply(
|
return msg.reply({
|
||||||
|
embeds: [leaveNotice(
|
||||||
this.t(msg, "responses.leave.specifyChannel", {
|
this.t(msg, "responses.leave.specifyChannel", {
|
||||||
channels: channelList.map(c => `• ${c}`).join("\n"),
|
channels: channelList.map(c => `• ${c}`).join("\n"),
|
||||||
prefix: this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id)
|
prefix: this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id)
|
||||||
})
|
})
|
||||||
);
|
)]
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const player = this.players.playerMap.get(targetChannelId)
|
const player = this.players.playerMap.get(targetChannelId)
|
||||||
@@ -95,29 +102,33 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
if (!player) {
|
if (!player) {
|
||||||
if (guildPlayers.length === 0) {
|
if (guildPlayers.length === 0) {
|
||||||
return msg.reply(this.t(msg, "responses.leave.notInVoice"));
|
return msg.reply({ embeds: [leaveNotice(this.t(msg, "responses.leave.notInVoice"))] });
|
||||||
}
|
}
|
||||||
const channelList = guildPlayers.map(([mapKey, p]) => {
|
const channelList = guildPlayers.map(([mapKey, p]) => {
|
||||||
const id = cleanId(p._channelId ?? mapKey);
|
const id = cleanId(p._channelId ?? mapKey);
|
||||||
return id ? `<#${id}>` : "\`unknown\`";
|
return id ? `<#${id}>` : "\`unknown\`";
|
||||||
});
|
});
|
||||||
if (!client?.channels?.get?.(targetChannelId)) {
|
if (!client?.channels?.get?.(targetChannelId)) {
|
||||||
return msg.reply(
|
return msg.reply({
|
||||||
|
embeds: [leaveNotice(
|
||||||
this.t(msg, "responses.leave.specifyChannel", {
|
this.t(msg, "responses.leave.specifyChannel", {
|
||||||
channels: channelList.map(c => `• ${c}`).join("\n"),
|
channels: channelList.map(c => `• ${c}`).join("\n"),
|
||||||
prefix: this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id)
|
prefix: this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id)
|
||||||
})
|
})
|
||||||
);
|
)]
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return msg.reply(
|
return msg.reply({
|
||||||
|
embeds: [leaveNotice(
|
||||||
this.t(msg, "responses.leave.noPlayerInChannel", {
|
this.t(msg, "responses.leave.noPlayerInChannel", {
|
||||||
channel: targetChannelId,
|
channel: targetChannelId,
|
||||||
channels: channelList.map(c => `• ${c}`).join("\n")
|
channels: channelList.map(c => `• ${c}`).join("\n")
|
||||||
})
|
})
|
||||||
);
|
)]
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!player?.connection) return msg.reply(this.t(msg, "responses.leave.playerNotInit"));
|
if (!player?.connection) return msg.reply({ embeds: [leaveNotice(this.t(msg, "responses.leave.playerNotInit"))] });
|
||||||
|
|
||||||
const activeChannelId = cleanId(player._channelId) || targetChannelId;
|
const activeChannelId = cleanId(player._channelId) || targetChannelId;
|
||||||
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
|
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
|
||||||
@@ -155,8 +166,23 @@ export async function run(msg, data) {
|
|||||||
}, rejoinDelay);
|
}, rejoinDelay);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const prefix = this.handler.getPrefix(cleanGuildId) || "%";
|
||||||
|
const chObj = client?.channels?.get?.(activeChannelId);
|
||||||
|
const channelName = chObj?.name ? `#${chObj.name}` : `<#${activeChannelId}>`;
|
||||||
|
|
||||||
const label247 = was247
|
const label247 = was247
|
||||||
? " (rejoining in " + Math.round(rejoinDelay / 1000) + "s — 24/7 is still saved. Use `" + this.handler.getPrefix(cleanGuildId) + "247` to disable it.)"
|
? "\n\n⏱️ " + "*(rejoining in " + Math.round(rejoinDelay / 1000) + "s — 24/7 is still saved. Use `" + prefix + "247` to disable it.)*"
|
||||||
: "";
|
: "";
|
||||||
msg.reply(this.t(msg, "responses.leave.left") + label247);
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `👋 ${this.t(msg, "responses.leave.sessionEndedTitle")}` })
|
||||||
|
.setTitle(this.t(msg, "responses.leave.disconnectedBadge"))
|
||||||
|
.setDescription(
|
||||||
|
`🔊 **${this.t(msg, "responses.leave.leftChannel", { channel: channelName })}**\n` +
|
||||||
|
`🗑️ ${this.t(msg, "responses.leave.queueCleared")}` + label247
|
||||||
|
)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.leave.rejoinHint", { prefix }) });
|
||||||
|
|
||||||
|
msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+37
-15
@@ -4,7 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { QueuePaginator, getGlobalColor } from "../src/ui/index.mjs";
|
import { QueuePaginator } from "../src/ui/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
|
||||||
const PAGE_SIZE = 10;
|
const PAGE_SIZE = 10;
|
||||||
@@ -39,9 +39,14 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
const current = p.queue.getCurrent();
|
const current = p.queue.getCurrent();
|
||||||
const totalTracks = p.queue.size();
|
const totalTracks = p.queue.size();
|
||||||
|
const prefix = this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) || "%";
|
||||||
|
|
||||||
if (!current && totalTracks === 0) {
|
if (!current && totalTracks === 0) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.list.empty", { prefix: this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) }));
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: this.t(message, "responses.list.queueTitle") })
|
||||||
|
.setDescription(this.t(message, "responses.list.empty", { prefix }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.play.controlsHint", { prefix }) });
|
||||||
return message.reply({ embeds: [embed] });
|
return message.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,23 +59,31 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
const buildEmbed = (page) => {
|
const buildEmbed = (page) => {
|
||||||
const safePage = (isNaN(page) || page < 1) ? 1 : Math.min(Math.floor(page), totalPages);
|
const safePage = (isNaN(page) || page < 1) ? 1 : Math.min(Math.floor(page), totalPages);
|
||||||
const loopState = p.queue.songLoop ? "🔂 Song" : p.queue.loop ? "🔁 Queue" : "🛑 Off";
|
const loopState = p.queue.songLoop
|
||||||
|
? `🔂 ${this.t(message, "responses.play.loopSongLabel")}`
|
||||||
|
: p.queue.loop
|
||||||
|
? `🔄 ${this.t(message, "responses.play.loopQueueLabel")}`
|
||||||
|
: this.t(message, "responses.play.loopOffLabel");
|
||||||
|
|
||||||
let desc = "";
|
let desc = "";
|
||||||
|
|
||||||
const remaining = p.getQueueRemainingTime();
|
const remaining = p.getQueueRemainingTime();
|
||||||
desc += `📋 **${totalTracks} track${totalTracks !== 1 ? "s" : ""} in queue** • ⏱️ \`${remaining}\`\n`;
|
const pluralStr = totalTracks === 1 ? this.t(message, "responses.play.trackSingle") : this.t(message, "responses.play.trackPlural");
|
||||||
|
const headerStr = this.t(message, "responses.list.tracksCount", { count: totalTracks, plural: pluralStr });
|
||||||
|
desc += `📋 **${headerStr}** • ⏱️ ` + "`" + remaining + "`" + "\n";
|
||||||
|
|
||||||
if (current) {
|
if (current) {
|
||||||
const elapsed = p.getCurrentElapsedDuration();
|
const elapsed = p.getCurrentElapsedDuration();
|
||||||
const total = p.getCurrentDuration();
|
const total = p.getCurrentDuration();
|
||||||
const link = current.spotifyUrl || current.url || "";
|
const link = current.spotifyUrl || current.url || "";
|
||||||
let title = current.title ?? "Unknown";
|
let title = current.title ?? this.t(message, "responses.play.unknownTrack");
|
||||||
if (title.length > 50) title = title.slice(0, 47) + "...";
|
if (title.length > 50) title = title.slice(0, 47) + "...";
|
||||||
const titleFmt = link ? `[${title}](${link})` : title;
|
const titleFmt = link ? `[${title}](${link})` : title;
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
const authorStr = rawAuthor ? ` • ${rawAuthor}` : "";
|
||||||
|
|
||||||
desc += "\n" + this.t(message, "responses.list.nowPlaying") + "\n";
|
desc += `\n▶️ **${this.t(message, "responses.list.nowPlayingHeader")}:**\n`;
|
||||||
desc += `${titleFmt} • \`${elapsed} / ${total}\`\n`;
|
desc += `${titleFmt}${authorStr} • ` + "`" + elapsed + " / " + total + "`" + "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
desc += `\n`;
|
desc += `\n`;
|
||||||
@@ -78,26 +91,35 @@ export async function run(message, data) {
|
|||||||
if (totalTracks === 0) {
|
if (totalTracks === 0) {
|
||||||
desc += this.t(message, "responses.list.emptyInline");
|
desc += this.t(message, "responses.list.emptyInline");
|
||||||
} else {
|
} else {
|
||||||
|
desc += `**${this.t(message, "responses.list.upNextHeader")}:**\n`;
|
||||||
const { items, start } = p.queue.getPage(safePage, PAGE_SIZE);
|
const { items, start } = p.queue.getPage(safePage, PAGE_SIZE);
|
||||||
|
|
||||||
items.forEach((vid, i) => {
|
items.forEach((vid, i) => {
|
||||||
const index = String(start + i + 1).padStart(2, " ");
|
const index = start + i + 1;
|
||||||
const dur = vid.duration ? p.getDuration(vid.duration) : "?:??";
|
const dur = vid.duration ? p.getDuration(vid.duration) : "?:??";
|
||||||
const link = vid.spotifyUrl || vid.url || "";
|
const link = vid.spotifyUrl || vid.url || "";
|
||||||
let title = vid.title ?? "Unknown";
|
let title = vid.title ?? this.t(message, "responses.play.unknownTrack");
|
||||||
if (title.length > 45) title = title.slice(0, 42) + "...";
|
if (title.length > 45) title = title.slice(0, 42) + "...";
|
||||||
title = link ? `[${title}](${link})` : title;
|
title = link ? `[${title}](${link})` : title;
|
||||||
const upNext = (start + i === 0) ? " ▶" : "";
|
const rawAuthor = vid.artist || (typeof vid.author === "object" ? vid.author?.name : vid.author);
|
||||||
desc += `\`${index}.\` ${title}${upNext} • \`${dur}\`\n`;
|
const authorStr = rawAuthor ? ` • ${rawAuthor}` : "";
|
||||||
|
desc += "`#" + index + "` " + `**${title}**${authorStr} • ` + "`" + dur + "`" + "\n";
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return new EmbedBuilder()
|
const footerText = `${this.t(message, "responses.list.pageFooter", { page: safePage, totalPages, loopState })} • ${this.t(message, "responses.play.controlsHint", { prefix })}`;
|
||||||
.setColor(getGlobalColor())
|
|
||||||
|
const builder = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
.setAuthor({ name: this.t(message, "responses.list.queueTitle") })
|
.setAuthor({ name: this.t(message, "responses.list.queueTitle") })
|
||||||
.setDescription(desc.trim())
|
.setDescription(desc.trim())
|
||||||
.setFooter({ text: `Page ${safePage}/${totalPages} • ${loopState}` })
|
.setFooter({ text: footerText });
|
||||||
;
|
|
||||||
|
if (current?.thumbnail) {
|
||||||
|
builder.setThumbnail(current.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder;
|
||||||
};
|
};
|
||||||
|
|
||||||
new QueuePaginator(message, this.messages, this.client)
|
new QueuePaginator(message, this.messages, this.client)
|
||||||
|
|||||||
+17
-7
@@ -28,10 +28,15 @@ export const command = new CommandBuilder()
|
|||||||
*/
|
*/
|
||||||
export async function run(msg) {
|
export async function run(msg) {
|
||||||
if (!isLogChannelEnabled()) {
|
if (!isLogChannelEnabled()) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
const embed = new EmbedBuilder()
|
||||||
"❌ The error-log channel is **disabled**.\n" +
|
.setColor(getGlobalColor())
|
||||||
"Set `errorLogChannel.enabled` to `true` and `errorLogChannel.channelId` to your log channel ID in config.json, then restart the bot."
|
.setAuthor({ name: this.t(msg, "responses.logtest.author") })
|
||||||
);
|
.setTitle(this.t(msg, "responses.logtest.disabledTitle"))
|
||||||
|
.setDescription(
|
||||||
|
"❌ The error-log channel is **disabled**.\n" +
|
||||||
|
"Set `errorLogChannel.enabled` to `true` and `errorLogChannel.channelId` to your log channel ID in config.json, then restart the bot."
|
||||||
|
)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.logtest.footerConfig") });
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,8 +46,13 @@ export async function run(msg) {
|
|||||||
`Manual test entry requested by ${who} — if you can read this in the log channel, error forwarding is working.`
|
`Manual test entry requested by ${who} — if you can read this in the log channel, error forwarding is working.`
|
||||||
);
|
);
|
||||||
|
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
const embed = new EmbedBuilder()
|
||||||
"📨 Test entry queued — check the log channel; it should arrive within a few seconds."
|
.setColor(getGlobalColor())
|
||||||
);
|
.setAuthor({ name: this.t(msg, "responses.logtest.author") })
|
||||||
|
.setTitle(this.t(msg, "responses.logtest.queuedTitle"))
|
||||||
|
.setDescription(
|
||||||
|
"📨 Test entry queued — check the log channel; it should arrive within a few seconds."
|
||||||
|
)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.logtest.footerPipeline") });
|
||||||
return msg.reply({ embeds: [embed] }).catch(() => {});
|
return msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+40
-5
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
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 { getGlobalColor } from "../src/ui/index.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the loop command. */
|
/** @type {CommandBuilder} @description Command definition for the loop command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -29,10 +29,45 @@ export const command = new CommandBuilder()
|
|||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const p = await this.getPlayer(message);
|
const p = await this.getPlayer(message);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const res = p.loop(data.get("type").value);
|
|
||||||
|
const type = data.get("type").value;
|
||||||
|
const current = p.queue.getCurrent();
|
||||||
|
const prefix = this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) || "%";
|
||||||
|
|
||||||
|
const state = p.queue.toggleLoop(type);
|
||||||
|
|
||||||
|
let badge = this.t(message, "responses.loop.loopOffBadge");
|
||||||
|
let desc = this.t(message, "responses.loop.loopOffDesc");
|
||||||
|
let icon = "⏹️";
|
||||||
|
|
||||||
|
if (state) {
|
||||||
|
if (type === "song") {
|
||||||
|
badge = this.t(message, "responses.loop.songLoopBadge");
|
||||||
|
desc = this.t(message, "responses.loop.songLoopDesc");
|
||||||
|
icon = "🔂";
|
||||||
|
} else {
|
||||||
|
badge = this.t(message, "responses.loop.queueLoopBadge");
|
||||||
|
desc = this.t(message, "responses.loop.queueLoopDesc");
|
||||||
|
icon = "🔄";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current?.title) {
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
const authorStr = rawAuthor ? ` • ${rawAuthor}` : "";
|
||||||
|
desc += `\n**${Utils.truncate(current.title, 45)}**${authorStr}`;
|
||||||
|
}
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setDescription(res)
|
.setAuthor({ name: `${icon} ${this.t(message, "responses.loop.loopTitle")}` })
|
||||||
;
|
.setTitle(badge)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(message, "responses.loop.cycleFooter", { prefix }) });
|
||||||
|
|
||||||
|
if (current?.thumbnail) {
|
||||||
|
embed.setThumbnail(current.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
message.reply({ embeds: [embed] }).catch(() => {});
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+152
-30
@@ -6,75 +6,195 @@
|
|||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { logger } from "../src/core/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/ui/index.mjs";
|
|
||||||
import { Utils } from "../src/utils/Utils.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the lyrics command. */
|
/** @type {CommandBuilder} @description Command definition for the lyrics command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("lyrics")
|
.setName("lyrics")
|
||||||
.setDescription("Display synced lyrics from NodeLink", "commands.lyrics")
|
.setDescription("Display synced or unsynced lyrics for the current track or a queried song.", "commands.lyrics")
|
||||||
.addAliases("lyric", "ly")
|
.addAliases("lyric", "ly")
|
||||||
.setCategory("music");
|
.setCategory("music")
|
||||||
|
.addTextOption(o =>
|
||||||
|
o.setName("query")
|
||||||
|
.setDescription("The song title and artist to search lyrics for (optional).", "options.lyrics.query")
|
||||||
|
.setRequired(false)
|
||||||
|
);
|
||||||
|
|
||||||
/** @private @type {string[]} Loading animation frames. */
|
/** @private @type {string[]} Loading animation frames. */
|
||||||
const LOADING_FRAMES = ["◐", "◓", "◑", "◒"];
|
const LOADING_FRAMES = ["◐", "◓", "◑", "◒"];
|
||||||
/** @private @type {number} Session timeout in milliseconds (3 minutes). */
|
/** @private @type {number} Session timeout in milliseconds (3 minutes). */
|
||||||
const SESSION_MS = 180_000;
|
const SESSION_MS = 180_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Search LRCLIB and NodeLink directly for lyrics when no player is active or a custom query is passed.
|
||||||
|
* @param {object|null} lavalink
|
||||||
|
* @param {string} rawQuery
|
||||||
|
* @param {string} searchTitle
|
||||||
|
* @param {string|null} searchArtist
|
||||||
|
* @returns {Promise<object|null>}
|
||||||
|
*/
|
||||||
|
async function fetchDirectLyrics(lavalink, rawQuery, searchTitle, searchArtist) {
|
||||||
|
const headers = { "User-Agent": "FluxerBot/1.0 (music bot lyrics lookup)" };
|
||||||
|
const urls = [];
|
||||||
|
if (searchArtist) {
|
||||||
|
const p1 = new URLSearchParams({ track_name: searchTitle, artist_name: searchArtist });
|
||||||
|
urls.push("https://lrclib.net/api/search?" + p1.toString());
|
||||||
|
}
|
||||||
|
const p2 = new URLSearchParams({ q: rawQuery });
|
||||||
|
urls.push("https://lrclib.net/api/search?" + p2.toString());
|
||||||
|
|
||||||
|
let candidates = [];
|
||||||
|
for (const url of urls) {
|
||||||
|
try {
|
||||||
|
const res = await fetch(url, { headers, signal: AbortSignal.timeout(10_000) });
|
||||||
|
if (!res.ok) continue;
|
||||||
|
const body = await res.json();
|
||||||
|
if (Array.isArray(body) && body.length) {
|
||||||
|
candidates = body;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (candidates.length) {
|
||||||
|
const best = Utils.pickBestLyrics(candidates, {
|
||||||
|
title: searchTitle,
|
||||||
|
artist: searchArtist,
|
||||||
|
durationSec: null,
|
||||||
|
}) || candidates[0];
|
||||||
|
|
||||||
|
if (best) {
|
||||||
|
if (best.instrumental) {
|
||||||
|
return { text: "", source: "LRCLIB", synced: false, lines: [], title: best.trackName, artist: best.artistName };
|
||||||
|
}
|
||||||
|
const parsed = Utils.parseSyncedLyrics(best.syncedLyrics);
|
||||||
|
if (parsed) {
|
||||||
|
return {
|
||||||
|
text: parsed.map(l => l.text).join("\n"),
|
||||||
|
source: "LRCLIB",
|
||||||
|
synced: true,
|
||||||
|
lines: parsed,
|
||||||
|
title: best.trackName,
|
||||||
|
artist: best.artistName,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (best.plainLyrics) {
|
||||||
|
const text = String(best.plainLyrics).trim();
|
||||||
|
return {
|
||||||
|
text,
|
||||||
|
source: "LRCLIB",
|
||||||
|
synced: false,
|
||||||
|
lines: text.split("\n").map(l => ({ text: l })),
|
||||||
|
title: best.trackName,
|
||||||
|
artist: best.artistName,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const node = lavalink?.getNode?.() ?? null;
|
||||||
|
if (node) {
|
||||||
|
try {
|
||||||
|
const path = `/loadlyrics?identifier=${encodeURIComponent(rawQuery)}`;
|
||||||
|
const results = await node.request(path);
|
||||||
|
if (results?.data?.lines?.length) {
|
||||||
|
return {
|
||||||
|
text: results.data.lines.map(l => l.text).join("\n"),
|
||||||
|
source: "Lavalink",
|
||||||
|
synced: results.data.lines.some(l => l.startTimeMs != null),
|
||||||
|
lines: results.data.lines,
|
||||||
|
title: searchTitle,
|
||||||
|
artist: searchArtist,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @async
|
* @async
|
||||||
* Run handler for the lyrics command.
|
* Run handler for the lyrics command.
|
||||||
* Fetches lyrics for the currently playing track and displays them with
|
* Fetches lyrics for the currently playing track and displays them with
|
||||||
* paginated embeds and reaction-based navigation.
|
* paginated embeds and reaction-based navigation.
|
||||||
* @param {object} message - The command message wrapper.
|
* @param {object} message - The command message wrapper.
|
||||||
|
* @param {object} [data] - Parsed options.
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
export async function run(message) {
|
export async function run(message, data) {
|
||||||
|
const query = data?.get?.("query")?.value?.trim() || null;
|
||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
if (!p) return;
|
|
||||||
|
|
||||||
const current = p.queue.getCurrent();
|
let searchTitle = null;
|
||||||
if (!current) {
|
let searchArtist = null;
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.lyrics.nothingPlaying"));
|
let current = null;
|
||||||
return message.reply({ embeds: [embed] });
|
|
||||||
|
if (query) {
|
||||||
|
searchTitle = query;
|
||||||
|
const parts = query.split(/\s*[-–—]\s*/);
|
||||||
|
if (parts.length >= 2) {
|
||||||
|
searchArtist = parts[0].trim();
|
||||||
|
searchTitle = parts.slice(1).join(" - ").trim();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
current = p?.queue?.getCurrent() ?? null;
|
||||||
|
if (!current) {
|
||||||
|
const prefix = this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) || "%";
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: this.t(message, "responses.lyrics.lyricsAuthor") })
|
||||||
|
.setDescription(this.t(message, "responses.lyrics.nothingPlaying"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.lyrics.manualSearchFooter", { prefix }) });
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
searchTitle = current.title;
|
||||||
|
searchArtist = current.artists?.[0]?.name || current.author?.name || "Unknown Artist";
|
||||||
}
|
}
|
||||||
|
|
||||||
let frame = 0;
|
let frame = 0;
|
||||||
const loadingMsg = await message.reply({ embeds: [
|
const loadingMsg = await message.reply({ embeds: [
|
||||||
new EmbedBuilder().setColor(getGlobalColor())
|
new EmbedBuilder().setColor(0xe9196c)
|
||||||
.setDescription(`${LOADING_FRAMES[0]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) }))
|
.setDescription(`${LOADING_FRAMES[0]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(searchTitle, 40) }))
|
||||||
|
|
||||||
] });
|
] });
|
||||||
|
|
||||||
const loadingInterval = setInterval(() => {
|
const loadingInterval = setInterval(() => {
|
||||||
frame = (frame + 1) % LOADING_FRAMES.length;
|
frame = (frame + 1) % LOADING_FRAMES.length;
|
||||||
loadingMsg.edit({ embeds: [
|
loadingMsg.edit({ embeds: [
|
||||||
new EmbedBuilder().setColor(getGlobalColor())
|
new EmbedBuilder().setColor(0xe9196c)
|
||||||
.setDescription(`${LOADING_FRAMES[frame]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) }))
|
.setDescription(`${LOADING_FRAMES[frame]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(searchTitle, 40) }))
|
||||||
|
|
||||||
] }).catch(() => {});
|
] }).catch(() => {});
|
||||||
}, 800);
|
}, 800);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await p.lyrics();
|
let result = null;
|
||||||
|
if (p) {
|
||||||
|
result = await p.lyrics(query);
|
||||||
|
} else {
|
||||||
|
result = await fetchDirectLyrics(this.lavalink, query, searchTitle, searchArtist);
|
||||||
|
}
|
||||||
|
|
||||||
clearInterval(loadingInterval);
|
clearInterval(loadingInterval);
|
||||||
|
|
||||||
if (!result || !result.text) {
|
if (!result || !result.text) {
|
||||||
|
const prefix = this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) || "%";
|
||||||
return loadingMsg.edit({ embeds: [
|
return loadingMsg.edit({ embeds: [
|
||||||
new EmbedBuilder().setColor(getGlobalColor())
|
new EmbedBuilder().setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: this.t(message, "responses.lyrics.lyricsAuthor") })
|
||||||
.setDescription(
|
.setDescription(
|
||||||
this.t(message, "responses.lyrics.noLyrics", { title: Utils.truncate(current.title, 40) })
|
this.t(message, "responses.lyrics.noLyrics", { title: Utils.truncate(searchTitle, 40) })
|
||||||
)
|
)
|
||||||
|
.setFooter({ text: this.t(message, "responses.lyrics.artistSearchFooter", { prefix }) })
|
||||||
] });
|
] });
|
||||||
}
|
}
|
||||||
|
|
||||||
try { await loadingMsg.message.delete(); } catch(e) { logger.warn("[Lyrics] Error:", e?.message); }
|
try { await loadingMsg.message.delete(); } catch(e) { logger.warn("[Lyrics] Error:", e?.message); }
|
||||||
|
|
||||||
const syncIndicator = result.synced ? this.t(message, "responses.lyrics.syncedBadge") : "";
|
const syncIndicator = result.synced ? this.t(message, "responses.lyrics.syncedBadge") : "";
|
||||||
const displayTitle = Utils.cleanTitle(current.title);
|
const displayTitle = result.title || (current ? Utils.cleanTitle(current.title) : Utils.cleanTitle(searchTitle));
|
||||||
const artist = current.artists?.[0]?.name || current.author?.name || "Unknown Artist";
|
const artist = result.artist || (current?.artists?.[0]?.name || current?.author?.name) || searchArtist || "Unknown Artist";
|
||||||
const lines = result.text.split("\n").filter(l => l.trim());
|
const lines = result.text.split("\n").filter(l => l.trim());
|
||||||
const totalLines = lines.length;
|
const totalLines = lines.length;
|
||||||
|
|
||||||
@@ -116,16 +236,17 @@ export async function run(message) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (totalPages === 1) {
|
if (totalPages === 1) {
|
||||||
const headerLine = `by *${artist}*${syncIndicator}`;
|
const headerLine = `by **${artist}**${syncIndicator ? " • " + syncIndicator : ""}`;
|
||||||
const descBody = pages[0];
|
const descBody = pages[0];
|
||||||
const singleDesc = [headerLine, "", "```", descBody, "```"].join("\n");
|
const singleDesc = [headerLine, "", "```", descBody, "```"].join("\n");
|
||||||
|
|
||||||
const singleEmbed = new EmbedBuilder()
|
const singleEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`)
|
.setAuthor({ name: this.t(message, "responses.lyrics.lyricsAuthor") })
|
||||||
|
.setTitle(Utils.truncate(displayTitle, 50))
|
||||||
.setDescription(singleDesc.slice(0, MAX_DESC))
|
.setDescription(singleDesc.slice(0, MAX_DESC))
|
||||||
.setFooter({ text: this.t(message, "responses.lyrics.sourceFooter", { source: result.source, lines: totalLines }) });
|
.setFooter({ text: this.t(message, "responses.lyrics.sourceFooter", { source: result.source, lines: totalLines }) });
|
||||||
if (current.thumbnail) singleEmbed.setThumbnail(current.thumbnail);
|
if (current?.thumbnail) singleEmbed.setThumbnail(current.thumbnail);
|
||||||
return message.reply({ embeds: [singleEmbed] });
|
return message.reply({ embeds: [singleEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,18 +261,19 @@ export async function run(message) {
|
|||||||
* @returns {object} Embed payload for message reply/edit.
|
* @returns {object} Embed payload for message reply/edit.
|
||||||
*/
|
*/
|
||||||
const buildContent = (pageIdx, expired = false) => {
|
const buildContent = (pageIdx, expired = false) => {
|
||||||
const headerLine = `by *${artist}*${syncIndicator} • Page ${pageIdx + 1}/${totalPages}`;
|
const headerLine = `by **${artist}**${syncIndicator ? " • " + syncIndicator : ""} • Page ${pageIdx + 1}/${totalPages}`;
|
||||||
const descBody = pages[pageIdx];
|
const descBody = pages[pageIdx];
|
||||||
const desc = [headerLine, "", "```", descBody, "```"].join("\n");
|
const desc = [headerLine, "", "```", descBody, "```"].join("\n");
|
||||||
|
|
||||||
const b = new EmbedBuilder()
|
const b = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`)
|
.setAuthor({ name: this.t(message, "responses.lyrics.lyricsAuthor") })
|
||||||
|
.setTitle(Utils.truncate(displayTitle, 50))
|
||||||
.setDescription(desc.slice(0, MAX_DESC))
|
.setDescription(desc.slice(0, MAX_DESC))
|
||||||
.setFooter({ text: expired
|
.setFooter({ text: expired
|
||||||
? this.t(message, "responses.lyrics.controlsExpired", { lines: totalLines })
|
? this.t(message, "responses.lyrics.controlsExpired", { lines: totalLines })
|
||||||
: this.t(message, "responses.lyrics.sourceFooter", { source: result.source, lines: totalLines }) });
|
: this.t(message, "responses.lyrics.sourceFooter", { source: result.source, lines: totalLines }) });
|
||||||
if (current.thumbnail) b.setThumbnail(current.thumbnail);
|
if (current?.thumbnail) b.setThumbnail(current.thumbnail);
|
||||||
return { embeds: [b] };
|
return { embeds: [b] };
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -209,7 +331,7 @@ export async function run(message) {
|
|||||||
const closedHeader = `by *${artist}*${syncIndicator} • Page ${currentPage + 1}/${totalPages}`;
|
const closedHeader = `by *${artist}*${syncIndicator} • Page ${currentPage + 1}/${totalPages}`;
|
||||||
const closedDesc = [closedHeader, "", "```", pages[currentPage], "```"].join("\n");
|
const closedDesc = [closedHeader, "", "```", pages[currentPage], "```"].join("\n");
|
||||||
const closedEmbed = new EmbedBuilder()
|
const closedEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`)
|
.setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`)
|
||||||
.setDescription(closedDesc.slice(0, MAX_DESC))
|
.setDescription(closedDesc.slice(0, MAX_DESC))
|
||||||
.setFooter({ text: this.t(message, "responses.lyrics.sessionClosed", { lines: totalLines }) });
|
.setFooter({ text: this.t(message, "responses.lyrics.sessionClosed", { lines: totalLines }) });
|
||||||
@@ -219,6 +341,6 @@ export async function run(message) {
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
clearInterval(loadingInterval);
|
clearInterval(loadingInterval);
|
||||||
logger.error("[Lyrics Command] Error:", err);
|
logger.error("[Lyrics Command] Error:", err);
|
||||||
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.lyrics.error", { error: Utils.truncate(err.message, 100) }))] }).catch(() => {});
|
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(0xe9196c).setDescription(this.t(message, "responses.lyrics.error", { error: Utils.truncate(err.message, 100) }))] }).catch(() => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+19
-1
@@ -4,6 +4,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
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 the move command. */
|
/** @type {CommandBuilder} @description Command definition for the move command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -35,8 +37,24 @@ export async function run(message, data) {
|
|||||||
if (!p) return;
|
if (!p) return;
|
||||||
const from = data.get("from")?.value;
|
const from = data.get("from")?.value;
|
||||||
const to = data.get("to")?.value;
|
const to = data.get("to")?.value;
|
||||||
|
const prefix = this.handler?.getPrefix?.(message.message?.guildId ?? message.channel?.guildId) ?? "%";
|
||||||
if (from === null || from === undefined || from < 1) return message.replyEmbed("Source position must be 1 or greater.").catch(() => {});
|
if (from === null || from === undefined || from < 1) return message.replyEmbed("Source position must be 1 or greater.").catch(() => {});
|
||||||
if (to === null || to === undefined || to < 1) return message.replyEmbed("Target position must be 1 or greater.").catch(() => {});
|
if (to === null || to === undefined || to < 1) return message.replyEmbed("Target position must be 1 or greater.").catch(() => {});
|
||||||
|
|
||||||
|
const queueData = p.queue?.data ?? [];
|
||||||
|
const track = queueData[from - 1];
|
||||||
const res = p.move(from, to);
|
const res = p.move(from, to);
|
||||||
message.replyEmbed(res).catch(() => {});
|
if (typeof res === "string" && !res.startsWith("Moved")) {
|
||||||
|
return message.replyEmbed(res).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.move.reorderedAuthor") })
|
||||||
|
.setTitle(track?.title?.slice(0, 256) || "Reordered Track")
|
||||||
|
.setDescription(this.t(message, "responses.move.reorderedDesc", { from, to }))
|
||||||
|
.setFooter({ text: to === 1 ? this.t(message, "responses.move.nowPlayingNext", { prefix }) : this.t(message, "responses.move.viewUpdatedQueue", { prefix }) });
|
||||||
|
|
||||||
|
if (track?.thumbnail) embed.setThumbnail(track.thumbnail);
|
||||||
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -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] });
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/normalize
|
||||||
|
* @description Toggle dynamic volume normalization & ReplayGain leveling (EBU R128 standard).
|
||||||
|
* Prevents ear-blasting volume differences between YouTube, Spotify, and SoundCloud.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
|
import { calculateNormalizationGain, detectTrackSource } from "../src/music/audio/VolumeNormalizer.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @type {CommandBuilder}
|
||||||
|
* @description Command definition for the normalize command.
|
||||||
|
*/
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("normalize")
|
||||||
|
.setDescription("Toggle dynamic volume normalization (ReplayGain leveling) across music sources.", "commands.normalize")
|
||||||
|
.setCategory("music")
|
||||||
|
.addChoiceOption(o =>
|
||||||
|
o.setName("state")
|
||||||
|
.setDescription("Turn on/off or check status ('on', 'off', 'status'). Omit to toggle.", "options.normalize.state")
|
||||||
|
.addChoices("on", "off", "status")
|
||||||
|
.setRequired(false)
|
||||||
|
)
|
||||||
|
.addAliases("replaygain", "volumenormalize", "norm");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run handler for the normalize command.
|
||||||
|
*
|
||||||
|
* @param {object} message - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message, data) {
|
||||||
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
|
const guildSettings = this.getSettings ? this.getSettings(message) : null;
|
||||||
|
const currentSetting = guildSettings?.get ? (guildSettings.get("normalize") ?? true) : true;
|
||||||
|
|
||||||
|
const stateArg = data.get("state")?.value?.toLowerCase();
|
||||||
|
let newState;
|
||||||
|
|
||||||
|
if (stateArg === "status") {
|
||||||
|
newState = currentSetting;
|
||||||
|
} else if (stateArg === "on" || stateArg === "enable" || stateArg === "true") {
|
||||||
|
newState = true;
|
||||||
|
} else if (stateArg === "off" || stateArg === "disable" || stateArg === "false") {
|
||||||
|
newState = false;
|
||||||
|
} else {
|
||||||
|
// Toggle
|
||||||
|
newState = !currentSetting;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stateArg !== "status") {
|
||||||
|
if (guildSettings?.set) {
|
||||||
|
guildSettings.set("normalize", newState);
|
||||||
|
}
|
||||||
|
if (p) {
|
||||||
|
p.volumeNormalization = newState;
|
||||||
|
if (p._voiceConn) {
|
||||||
|
try {
|
||||||
|
p._voiceConn.setVolume(p.getEffectiveVolume());
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.normalize.headerAuthor") })
|
||||||
|
.setTitle(this.t(message, "responses.normalize.headerTitle"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.normalize.footer") });
|
||||||
|
|
||||||
|
const statusMsg = newState
|
||||||
|
? this.t(message, "responses.normalize.statusEnabled")
|
||||||
|
: this.t(message, "responses.normalize.statusDisabled");
|
||||||
|
const infoMsg = this.t(message, "responses.normalize.info");
|
||||||
|
|
||||||
|
embed.setDescription(`${statusMsg}\n\n*${infoMsg}*`);
|
||||||
|
|
||||||
|
if (p) {
|
||||||
|
const current = p.queue?.getCurrent?.();
|
||||||
|
if (current) {
|
||||||
|
const source = detectTrackSource(current);
|
||||||
|
const gain = calculateNormalizationGain(current);
|
||||||
|
const gainDb = (20 * Math.log10(gain)).toFixed(1);
|
||||||
|
const gainSign = gain >= 1 ? "+" : "";
|
||||||
|
|
||||||
|
embed.addFields(
|
||||||
|
{ name: this.t(message, "responses.normalize.fieldSource"), value: source || "Default", inline: true },
|
||||||
|
{ name: this.t(message, "responses.normalize.fieldGainOffset"), value: `${gainSign}${gainDb} dB (${(gain * 100).toFixed(0)}%)`, inline: true },
|
||||||
|
{ name: this.t(message, "responses.normalize.fieldEffectiveVolume"), value: `${Math.round(p.getEffectiveVolume())}%`, inline: true }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
+8
-7
@@ -27,23 +27,24 @@ export async function run(msg) {
|
|||||||
|
|
||||||
const loadingEmbed = new EmbedBuilder()
|
const loadingEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(msg, "responses.np.loading"))
|
.setAuthor({ name: this.t(msg, "responses.np.nowPlayingAuthor") })
|
||||||
;
|
.setDescription(this.t(msg, "responses.np.loading"));
|
||||||
const loadingMsg = await msg.reply({ embeds: [loadingEmbed] });
|
const loadingMsg = await msg.reply({ embeds: [loadingEmbed] });
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await p.nowPlaying();
|
const data = await p.nowPlaying();
|
||||||
if (!data?.msg) {
|
if (!data?.msg && !data?.embed) {
|
||||||
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses._common.nothingPlaying"))] }).catch(() => {});
|
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setAuthor({ name: this.t(msg, "responses.np.nowPlayingAuthor") }).setDescription(this.t(msg, "responses._common.nothingPlaying"))] }).catch(() => {});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const embed = new EmbedBuilder()
|
const embed = data.embed || new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.np.nowPlayingAuthor") })
|
||||||
.setDescription(data.msg);
|
.setDescription(data.msg);
|
||||||
if (data.image) embed.setThumbnail(data.image);
|
if (!data.embed && data.image) embed.setThumbnail(data.image);
|
||||||
|
|
||||||
loadingMsg.edit({ embeds: [embed] }).catch(() => {});
|
loadingMsg.edit({ embeds: [embed] }).catch(() => {});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses._common.nothingPlaying"))] }).catch(() => {});
|
loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setAuthor({ name: this.t(msg, "responses.np.nowPlayingAuthor") }).setDescription(this.t(msg, "responses._common.nothingPlaying"))] }).catch(() => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+47
-5
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
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 { getGlobalColor } from "../src/ui/index.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the pause command. */
|
/** @type {CommandBuilder} @description Command definition for the pause command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -23,10 +23,52 @@ export const command = new CommandBuilder()
|
|||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message);
|
const p = await this.getPlayer(message);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const res = p.pause();
|
|
||||||
|
const current = p.queue.getCurrent();
|
||||||
|
if (!p.connection || !current) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `⏸️ ${this.t(message, "responses.pause.pausedTitle")}` })
|
||||||
|
.setDescription(this.t(message, "responses._common.nothingPlaying"));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const prefix = this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) || "%";
|
||||||
|
|
||||||
|
if (p._paused) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `⏸️ ${this.t(message, "responses.pause.pausedTitle")}` })
|
||||||
|
.setDescription(this.t(message, "responses.pause.alreadyPaused"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.pause.resumeHint", { prefix }) });
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
p.pause();
|
||||||
|
p._autoPausedEmpty = false;
|
||||||
|
p._serverMutedAutoPaused = false;
|
||||||
|
const elapsed = p.getCurrentElapsedDuration();
|
||||||
|
const trackUrl = current.spotifyUrl || current.url || null;
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
|
||||||
|
let desc = trackUrl
|
||||||
|
? `**[${Utils.truncate(current.title || this.t(message, "responses.play.unknownTrack"), 50)}](${trackUrl})**`
|
||||||
|
: `**${Utils.truncate(current.title || this.t(message, "responses.play.unknownTrack"), 50)}**`;
|
||||||
|
|
||||||
|
if (rawAuthor) {
|
||||||
|
desc += `\n${this.t(message, "responses.play.byAuthor", { author: rawAuthor })}`;
|
||||||
|
}
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setDescription(res)
|
.setAuthor({ name: `⏸️ ${this.t(message, "responses.pause.pausedTitle")}` })
|
||||||
;
|
.setTitle(this.t(message, "responses.pause.pausedAt", { time: elapsed }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(message, "responses.pause.resumeHint", { prefix }) });
|
||||||
|
|
||||||
|
if (current.thumbnail) {
|
||||||
|
embed.setThumbnail(current.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
message.reply({ embeds: [embed] }).catch(() => {});
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+17
-13
@@ -5,7 +5,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 { getGlobalColor } from "../src/ui/index.mjs";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
@@ -68,7 +67,7 @@ export async function run(message) {
|
|||||||
const t = (...a) => this.t(message, ...a);
|
const t = (...a) => this.t(message, ...a);
|
||||||
|
|
||||||
const waitingEmbed = new EmbedBuilder()
|
const waitingEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setDescription(t("responses.ping.measuring"));
|
.setDescription(t("responses.ping.measuring"));
|
||||||
|
|
||||||
const t0 = Date.now();
|
const t0 = Date.now();
|
||||||
@@ -76,29 +75,34 @@ export async function run(message) {
|
|||||||
try {
|
try {
|
||||||
sent = await message.reply({ embeds: [waitingEmbed] });
|
sent = await message.reply({ embeds: [waitingEmbed] });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return; // couldn't even send the placeholder — nothing to edit
|
return;
|
||||||
}
|
}
|
||||||
const roundtrip = Date.now() - t0;
|
const roundtrip = Date.now() - t0;
|
||||||
|
|
||||||
const lines = [
|
|
||||||
`${t("responses.ping.roundtrip")} — \`${roundtrip}ms\``,
|
|
||||||
];
|
|
||||||
|
|
||||||
const gateway = readGatewayPing(this.client);
|
const gateway = readGatewayPing(this.client);
|
||||||
if (gateway >= 0) lines.push(`${t("responses.ping.gateway")} — \`${gateway}ms\``);
|
|
||||||
|
|
||||||
const node = readNodePing(this.lavalink);
|
const node = readNodePing(this.lavalink);
|
||||||
|
|
||||||
|
const restLabel = t("responses.ping.restApi") || "REST API";
|
||||||
|
const gatewayLabel = t("responses.ping.gatewayWs") || "Gateway WebSocket";
|
||||||
|
const nodeLabel = t("responses.ping.audioNode") || "Audio Node";
|
||||||
|
|
||||||
|
const lines = [
|
||||||
|
`⚡ **${restLabel}** — \`${roundtrip}ms\``,
|
||||||
|
];
|
||||||
|
if (gateway >= 0) lines.push(`🌐 **${gatewayLabel}** — \`${gateway}ms\``);
|
||||||
if (node) {
|
if (node) {
|
||||||
lines.push(`${t("responses.ping.node")} — \`${node.ping !== null ? node.ping + "ms" : "connected"}\``);
|
lines.push(`🎵 **${nodeLabel}** — \`${node.ping !== null ? node.ping + "ms" : "connected"}\``);
|
||||||
}
|
}
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setAuthor({
|
.setAuthor({
|
||||||
name: t("responses.ping.title"),
|
name: `🏓 ${t("responses.ping.pingDashboard") || t("responses.ping.title")}`,
|
||||||
iconURL: this.client?.user?.displayAvatarURL?.() || null,
|
iconURL: this.client?.user?.displayAvatarURL?.() || null,
|
||||||
})
|
})
|
||||||
.setDescription(lines.join("\n"));
|
.setTitle(`🟢 ${t("responses.ping.operational") || "Operational"}`)
|
||||||
|
.setDescription(lines.join("\n\n"))
|
||||||
|
.setFooter({ text: `Shard #${this.client?.shardId ?? 0} • NodeLink DSP` });
|
||||||
|
|
||||||
sent.edit({ embeds: [embed] }).catch(() => {});
|
sent.edit({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/pitch
|
||||||
|
* @description Adjust real-time audio pitch (0.5× to 2.0×) using timescale DSP filters.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @type {CommandBuilder}
|
||||||
|
* @description Command definition for the pitch command.
|
||||||
|
*/
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("pitch")
|
||||||
|
.setDescription("Adjust the pitch of the current track (0.5× to 2.0×).", "commands.pitch")
|
||||||
|
.setCategory("music")
|
||||||
|
.addNumberOption(o =>
|
||||||
|
o.setName("multiplier")
|
||||||
|
.setDescription("Pitch multiplier between 0.5 and 2.0 (e.g. 1.25). Omit to reset to 1.0×.", "options.pitch.multiplier")
|
||||||
|
.setRequired(false)
|
||||||
|
)
|
||||||
|
.addAliases("key");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run handler for the pitch command.
|
||||||
|
*
|
||||||
|
* @param {object} message - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message, data) {
|
||||||
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
const current = p.queue?.getCurrent();
|
||||||
|
const rawPitch = data.get("multiplier")?.value;
|
||||||
|
const prefix = this.handler?.getPrefix?.(message.message?.guildId ?? message.guild?.id) ?? "%";
|
||||||
|
const embed = new EmbedBuilder().setColor(0xe9196c);
|
||||||
|
|
||||||
|
if (rawPitch === null || rawPitch === undefined || isNaN(Number(rawPitch))) {
|
||||||
|
const currentTimescale = p.activeFilterPayload?.timescale;
|
||||||
|
const currentPitch = currentTimescale?.pitch ?? 1.0;
|
||||||
|
if (currentPitch !== 1.0) {
|
||||||
|
const existingPayload = { ...(p.activeFilterPayload || {}) };
|
||||||
|
delete existingPayload.timescale;
|
||||||
|
await p.applyFilter(existingPayload, Object.keys(existingPayload).length > 0 ? p.activeFilter : null);
|
||||||
|
embed.setAuthor({ name: `🎵 ${this.t(message, "responses.pitch.pitchTitle")}` })
|
||||||
|
.setTitle(this.t(message, "responses.pitch.normalRate"))
|
||||||
|
.setDescription(this.t(message, "responses.pitch.reset"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.pitch.resetHint", { prefix }) });
|
||||||
|
} else {
|
||||||
|
embed.setAuthor({ name: `🎵 ${this.t(message, "responses.pitch.pitchTitle")}` })
|
||||||
|
.setTitle(this.t(message, "responses.pitch.normalRate"))
|
||||||
|
.setDescription(this.t(message, "responses.pitch.current", { pitch: "1.0", prefix }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.pitch.resetHint", { prefix }) });
|
||||||
|
}
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const pitch = Utils.clamp(Number(rawPitch), 0.5, 2.0);
|
||||||
|
|
||||||
|
const existingTimescale = p.activeFilterPayload?.timescale || {};
|
||||||
|
const newTimescale = {
|
||||||
|
...existingTimescale,
|
||||||
|
speed: existingTimescale.speed ?? 1.0,
|
||||||
|
pitch,
|
||||||
|
rate: 1.0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
...(p.activeFilterPayload || {}),
|
||||||
|
timescale: newTimescale,
|
||||||
|
};
|
||||||
|
|
||||||
|
const filterMeta = {
|
||||||
|
key: `pitch_${pitch}`,
|
||||||
|
label: `${pitch}× Pitch`,
|
||||||
|
emoji: pitch > 1 ? "🐿️" : "🗣️",
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await p.applyFilter(payload, filterMeta);
|
||||||
|
if (!res.ok) {
|
||||||
|
embed.setDescription(this.t(message, "responses.pitch.failed", { reason: res.reason || "Unknown error" }));
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
let desc = this.t(message, "responses.pitch.set", { pitch });
|
||||||
|
if (current?.title) {
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
const authorStr = rawAuthor ? ` • ${rawAuthor}` : "";
|
||||||
|
desc += `\n**${Utils.truncate(current.title, 45)}**${authorStr}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
embed.setAuthor({ name: `🎵 ${this.t(message, "responses.pitch.pitchTitle")}` })
|
||||||
|
.setTitle(this.t(message, "responses.pitch.pitchMultiplier", { pitch }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(message, "responses.pitch.resetHint", { prefix }) });
|
||||||
|
|
||||||
|
if (current?.thumbnail) embed.setThumbnail(current.thumbnail);
|
||||||
|
|
||||||
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
+102
-48
@@ -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"];
|
||||||
|
|
||||||
@@ -73,7 +78,6 @@ function parseLastFmSubProvider(query) {
|
|||||||
function parseLastFmTrackQuery(raw) {
|
function parseLastFmTrackQuery(raw) {
|
||||||
const value = String(raw ?? "").trim();
|
const value = String(raw ?? "").trim();
|
||||||
if (!value) return null;
|
if (!value) return null;
|
||||||
if (value.length > 300) return null;
|
|
||||||
|
|
||||||
const byMatch = value.match(/^(.+?)\s+by\s+(.+)$/i);
|
const byMatch = value.match(/^(.+?)\s+by\s+(.+)$/i);
|
||||||
if (byMatch) {
|
if (byMatch) {
|
||||||
@@ -103,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;
|
||||||
@@ -140,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;
|
||||||
@@ -167,6 +172,7 @@ export const command = new CommandBuilder()
|
|||||||
)
|
)
|
||||||
.addExamples(
|
.addExamples(
|
||||||
"$prefixplay take over league of legends",
|
"$prefixplay take over league of legends",
|
||||||
|
"$prefixplay pop",
|
||||||
"$prefixplay sp: blinding lights",
|
"$prefixplay sp: blinding lights",
|
||||||
"$prefixplay dz: get lucky",
|
"$prefixplay dz: get lucky",
|
||||||
"$prefixplay -p yt take over league of legends",
|
"$prefixplay -p yt take over league of legends",
|
||||||
@@ -184,8 +190,8 @@ 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.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")
|
||||||
@@ -196,6 +202,30 @@ export const command = new CommandBuilder()
|
|||||||
, true)
|
, true)
|
||||||
.addAlias("p");
|
.addAlias("p");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forward a play status message or rich embed to the status message.
|
||||||
|
* @param {string|object|EmbedBuilder} d
|
||||||
|
* @param {object|null} statusMsg
|
||||||
|
* @param {object} message
|
||||||
|
*/
|
||||||
|
function forwardPlayMessage(d, statusMsg, message) {
|
||||||
|
let embed;
|
||||||
|
if (d instanceof EmbedBuilder) {
|
||||||
|
embed = d;
|
||||||
|
} else if (d?.embeds?.[0]) {
|
||||||
|
embed = d.embeds[0];
|
||||||
|
} else if (typeof d === "object" && d?.embed) {
|
||||||
|
embed = d.embed;
|
||||||
|
} else {
|
||||||
|
embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(String(d?.msg || d));
|
||||||
|
}
|
||||||
|
if (statusMsg) {
|
||||||
|
statusMsg.edit({ embeds: [embed] }).catch(() => {});
|
||||||
|
} else {
|
||||||
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run handler for the play command.
|
* Run handler for the play command.
|
||||||
* Handles URL detection, Last.fm integration, provider selection, and track searching.
|
* Handles URL detection, Last.fm integration, provider selection, and track searching.
|
||||||
@@ -205,7 +235,39 @@ export const command = new CommandBuilder()
|
|||||||
* @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";
|
||||||
@@ -216,16 +278,13 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
const statusEmbed = new EmbedBuilder()
|
const statusEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(":mag_right: Loading direct stream...");
|
.setAuthor({ name: this.t(message, "responses.play.streamPipelineAuthor") })
|
||||||
|
.setDescription(this.t(message, "responses.play.loadingDirectStream"));
|
||||||
let statusMsg = null;
|
let statusMsg = null;
|
||||||
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
||||||
|
|
||||||
const messages = p.playExternal(rawQuery);
|
const messages = p.playExternal(rawQuery);
|
||||||
messages.on("message", d => {
|
messages.on("message", d => forwardPlayMessage(d, statusMsg, message));
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
|
||||||
if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
else { message.reply({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -235,16 +294,13 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
const statusEmbed = new EmbedBuilder()
|
const statusEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(":mag_right: Resolving stream via Lavalink...");
|
.setAuthor({ name: this.t(message, "responses.play.streamPipelineAuthor") })
|
||||||
|
.setDescription(this.t(message, "responses.play.resolvingLavalinkStream"));
|
||||||
let statusMsg = null;
|
let statusMsg = null;
|
||||||
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
try { statusMsg = await message.reply({ embeds: [statusEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
||||||
|
|
||||||
const messages = p.playExternal(rawQuery, null, null, false, "stream");
|
const messages = p.playExternal(rawQuery, null, null, false, "stream");
|
||||||
messages.on("message", d => {
|
messages.on("message", d => forwardPlayMessage(d, statusMsg, message));
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
|
||||||
if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
else { message.reply({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -253,11 +309,15 @@ export async function run(message, data) {
|
|||||||
const parsed = parseLastFmUrl(lfUrl);
|
const parsed = parseLastFmUrl(lfUrl);
|
||||||
|
|
||||||
if (parsed && parsed.track) {
|
if (parsed && parsed.track) {
|
||||||
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
|
const requesterName = message.member?.displayName || message.author?.globalName || message.author?.username || null;
|
||||||
const lastfmTrackMeta = {
|
const lastfmTrackMeta = {
|
||||||
artist: parsed.artist,
|
artist: parsed.artist,
|
||||||
name: parsed.track,
|
name: parsed.track,
|
||||||
source: "lastfm",
|
source: "lastfm",
|
||||||
url: parsed.url,
|
url: parsed.url,
|
||||||
|
requester,
|
||||||
|
requesterName,
|
||||||
};
|
};
|
||||||
|
|
||||||
const p = await this.getPlayer(message, true, true, true);
|
const p = await this.getPlayer(message, true, true, true);
|
||||||
@@ -265,37 +325,33 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
const searchEmbed = new EmbedBuilder()
|
const searchEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: `🔎 ${this.t(message, "responses.play.searching")}` })
|
||||||
.setDescription(this.t(message, "responses.play.searching"));
|
.setDescription(this.t(message, "responses.play.searching"));
|
||||||
let statusMsg = null;
|
let statusMsg = null;
|
||||||
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
||||||
|
|
||||||
const playQuery = `${parsed.track} ${parsed.artist}`.trim();
|
const playQuery = `${parsed.track} ${parsed.artist}`.trim();
|
||||||
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider, lastfmTrackMeta);
|
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider, lastfmTrackMeta);
|
||||||
messages.on("message", d => {
|
messages.on("message", d => forwardPlayMessage(d, statusMsg, message));
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
|
||||||
if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
else { message.reply({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parsed && !parsed.track) {
|
if (parsed && !parsed.track) {
|
||||||
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
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 searchEmbed = new EmbedBuilder()
|
const searchEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: `🔎 ${this.t(message, "responses.play.searching")}` })
|
||||||
.setDescription(this.t(message, "responses.play.searching"));
|
.setDescription(this.t(message, "responses.play.searching"));
|
||||||
let statusMsg = null;
|
let statusMsg = null;
|
||||||
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { logger.warn("[Play] Error:", e?.message); }
|
||||||
|
|
||||||
const playQuery = parsed.artist;
|
const playQuery = parsed.artist;
|
||||||
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider);
|
const requesterName = message.member?.displayName || message.author?.globalName || message.author?.username || null;
|
||||||
messages.on("message", d => {
|
const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider, { requester, requesterName });
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
messages.on("message", d => forwardPlayMessage(d, statusMsg, message));
|
||||||
if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
else { message.reply({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -315,7 +371,7 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
if (!lowerQuery && resolveProvider && (resolveProvider === "lf" || resolveProvider === "lastfm")) {
|
if (!lowerQuery && resolveProvider && (resolveProvider === "lf" || resolveProvider === "lastfm")) {
|
||||||
return message.reply({
|
return message.reply({
|
||||||
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setAuthor({ name: this.t(message, "responses.play.lastfmPlaybackAuthor") }).setDescription([
|
||||||
`❌ Specify a Last.fm category after \`lf:\``,
|
`❌ Specify a Last.fm category after \`lf:\``,
|
||||||
``,
|
``,
|
||||||
`**Available categories:**`,
|
`**Available categories:**`,
|
||||||
@@ -374,11 +430,15 @@ export async function run(message, data) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
|
const requesterName = message.member?.displayName || message.author?.globalName || message.author?.username || null;
|
||||||
const lastfmTrackMeta = {
|
const lastfmTrackMeta = {
|
||||||
artist: searchResult.artist,
|
artist: searchResult.artist,
|
||||||
name: searchResult.name,
|
name: searchResult.name,
|
||||||
source: "lastfm",
|
source: "lastfm",
|
||||||
url: searchResult.url ?? "",
|
url: searchResult.url ?? "",
|
||||||
|
requester,
|
||||||
|
requesterName,
|
||||||
};
|
};
|
||||||
|
|
||||||
const playProvider = resolveProvider && resolveProvider !== "lf" && resolveProvider !== "lastfm"
|
const playProvider = resolveProvider && resolveProvider !== "lf" && resolveProvider !== "lastfm"
|
||||||
@@ -390,32 +450,33 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
const playQuery = `${searchResult.name} ${searchResult.artist}`.trim();
|
const playQuery = `${searchResult.name} ${searchResult.artist}`.trim();
|
||||||
const messages = p.play(playQuery, false, playProvider, lastfmTrackMeta);
|
const messages = p.play(playQuery, false, playProvider, lastfmTrackMeta);
|
||||||
messages.on("message", d => {
|
messages.on("message", d => forwardPlayMessage(d, statusMsg, message));
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
|
||||||
if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
else { message.reply({ embeds: [embed] }).catch(() => {}); }
|
|
||||||
});
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
|
const requesterName = message.member?.displayName || message.author?.globalName || message.author?.username || null;
|
||||||
const resolvedProvider =
|
const resolvedProvider =
|
||||||
provider === "lastfm" || provider === "lf"
|
provider === "lastfm" || provider === "lf"
|
||||||
? (flagProvider && flagProvider !== "lastfm" && flagProvider !== "lf" ? flagProvider : "yt")
|
? (flagProvider && flagProvider !== "lastfm" && flagProvider !== "lf" ? flagProvider : "yt")
|
||||||
: provider;
|
: provider;
|
||||||
const lastfmTrackMeta =
|
const parsedLastfmTrackMeta =
|
||||||
provider === "lastfm" || provider === "lf"
|
provider === "lastfm" || provider === "lf"
|
||||||
? parseLastFmTrackQuery(query)
|
? parseLastFmTrackQuery(query)
|
||||||
: null;
|
: null;
|
||||||
|
const lastfmTrackMeta = parsedLastfmTrackMeta
|
||||||
|
? { ...parsedLastfmTrackMeta, requester, requesterName }
|
||||||
|
: { requester, requesterName };
|
||||||
|
|
||||||
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 searchEmbed = new EmbedBuilder()
|
const searchEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(message, "responses.play.searching"))
|
.setAuthor({ name: `🔎 ${this.t(message, "responses.play.searching")}` })
|
||||||
;
|
.setDescription(this.t(message, "responses.play.searching"));
|
||||||
|
|
||||||
let statusMsg = null;
|
let statusMsg = null;
|
||||||
try {
|
try {
|
||||||
@@ -424,17 +485,10 @@ export async function run(message, data) {
|
|||||||
logger.warn("[Play] Error:", err?.message);
|
logger.warn("[Play] Error:", err?.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
const playQuery = lastfmTrackMeta
|
const playQuery = parsedLastfmTrackMeta
|
||||||
? `${lastfmTrackMeta.name} ${lastfmTrackMeta.artist}`.trim()
|
? `${parsedLastfmTrackMeta.name} ${parsedLastfmTrackMeta.artist}`.trim()
|
||||||
: query;
|
: query;
|
||||||
|
|
||||||
const messages = p.play(playQuery, false, resolvedProvider);
|
const messages = p.play(playQuery, false, resolvedProvider, lastfmTrackMeta);
|
||||||
messages.on("message", d => {
|
messages.on("message", d => forwardPlayMessage(d, statusMsg, message));
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d);
|
|
||||||
if (statusMsg) {
|
|
||||||
statusMsg.edit({ embeds: [embed] }).catch(() => {});
|
|
||||||
} else {
|
|
||||||
message.reply({ embeds: [embed] }).catch(() => {});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
@@ -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);
|
||||||
@@ -53,9 +52,9 @@ export function buildPlayerEmbed(bot, msg, player, timeout, state = {}) {
|
|||||||
let filterStatus = bot.t(msg, "responses.player.filterOff");
|
let filterStatus = bot.t(msg, "responses.player.filterOff");
|
||||||
if (player.activeFilter) {
|
if (player.activeFilter) {
|
||||||
if (player.activeFilter.label.includes("+")) {
|
if (player.activeFilter.label.includes("+")) {
|
||||||
filterStatus = `🔥 **${player.activeFilter.label}**`;
|
filterStatus = bot.t(msg, "responses.player.filterStacked", { label: player.activeFilter.label });
|
||||||
} else {
|
} else {
|
||||||
filterStatus = `${player.activeFilter.emoji ?? "🎛️"} **${player.activeFilter.label}**`;
|
filterStatus = bot.t(msg, "responses.player.filterActive", { emoji: player.activeFilter.emoji ?? "🎛️", label: player.activeFilter.label });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,7 +70,7 @@ export function buildPlayerEmbed(bot, msg, player, timeout, state = {}) {
|
|||||||
`${timeDisplay}`,
|
`${timeDisplay}`,
|
||||||
``,
|
``,
|
||||||
bot.t(msg, "responses.player.volumeLabel", { volume: volPercent }) + " " + volumeBar,
|
bot.t(msg, "responses.player.volumeLabel", { volume: volPercent }) + " " + volumeBar,
|
||||||
`${bot.t(msg, "responses.player.queueLabel", { count: queueSize })} | Loop: ${loopStatus} | Filter: ${filterStatus}`,
|
`${bot.t(msg, "responses.player.queueLabel", { count: queueSize })} • ${loopStatus} • ${filterStatus}`,
|
||||||
``,
|
``,
|
||||||
state.message ? `💬 *${state.message}*` : `💡 *${bot.t(msg, "responses.player.reactHint")}*`,
|
state.message ? `💬 *${state.message}*` : `💡 *${bot.t(msg, "responses.player.reactHint")}*`,
|
||||||
``,
|
``,
|
||||||
@@ -83,7 +82,8 @@ export function buildPlayerEmbed(bot, msg, player, timeout, state = {}) {
|
|||||||
: msg.author?.avatarURL ?? null;
|
: msg.author?.avatarURL ?? null;
|
||||||
|
|
||||||
const builder = new EmbedBuilder()
|
const builder = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: bot.t(msg, "responses.player.deckAuthor") })
|
||||||
.setTitle(bot.t(msg, "responses.player.title"))
|
.setTitle(bot.t(msg, "responses.player.title"))
|
||||||
.setDescription(description)
|
.setDescription(description)
|
||||||
.setFooter({
|
.setFooter({
|
||||||
|
|||||||
+24
-11
@@ -78,25 +78,38 @@ export async function openLyricsViewer(bot, msg, player, refresh, session) {
|
|||||||
let currentPage = 0;
|
let currentPage = 0;
|
||||||
|
|
||||||
const buildLyricsContent = (pageIdx, expired = false, closed = false) => {
|
const buildLyricsContent = (pageIdx, expired = false, closed = false) => {
|
||||||
const title = Utils.truncate(
|
const current = player.queue.getCurrent();
|
||||||
player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '',
|
const rawTitle = current?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? 'Unknown Track';
|
||||||
50
|
const title = Utils.truncate(rawTitle, 50);
|
||||||
);
|
const artist = current?.artist || (typeof current?.author === "object" ? current?.author?.name : current?.author) || "";
|
||||||
const lyricsSource = lyricsResult.source || "Lyrics";
|
const lyricsSource = lyricsResult.source || "Lyrics";
|
||||||
const footerText = closed
|
const footerText = closed
|
||||||
? `👋 Lyrics closed • ${lyricsSource} • ${totalLines} lines`
|
? `👋 Lyrics closed • ${lyricsSource} • ${totalLines} lines`
|
||||||
: expired
|
: expired
|
||||||
? `⌛ Controls expired • ${lyricsSource} • ${totalLines} lines`
|
? `⌛ Controls expired • ${lyricsSource} • ${totalLines} lines`
|
||||||
: `${lyricsSource} • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`;
|
: `${lyricsSource} • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`;
|
||||||
|
const headerLine = artist ? `by **${artist}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}` : `Page ${pageIdx + 1}/${totalPages}${syncBadge}`;
|
||||||
const desc = [
|
const desc = [
|
||||||
`**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`,
|
headerLine,
|
||||||
``,
|
"",
|
||||||
'```',
|
"```",
|
||||||
pages[pageIdx],
|
pages[pageIdx],
|
||||||
totalPages > 1 && !expired && !closed ? `\n\n💡 ⬅️ ➡️ Navigate • ❌ Close` : '',
|
totalPages > 1 && !expired && !closed ? "\n\n💡 ⬅️ ➡️ Navigate • ❌ Close" : "",
|
||||||
'```'
|
"```"
|
||||||
].join('\n');
|
].join("\n");
|
||||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText })] };
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: bot.t(msg, "responses.lyrics.lyricsAuthor") })
|
||||||
|
.setTitle(title)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: footerText });
|
||||||
|
|
||||||
|
if (current?.thumbnail) {
|
||||||
|
embed.setThumbnail(current.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { embeds: [embed] };
|
||||||
};
|
};
|
||||||
|
|
||||||
session.activeLyricsMsg = await msg.reply(buildLyricsContent(0));
|
session.activeLyricsMsg = await msg.reply(buildLyricsContent(0));
|
||||||
|
|||||||
@@ -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] });
|
||||||
|
}
|
||||||
|
}
|
||||||
+68
-6
@@ -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,15 +56,56 @@ 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";
|
||||||
|
|
||||||
const searchEmbed = new EmbedBuilder()
|
const searchEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(message, "responses.playnext.searching"))
|
.setAuthor({ name: `🔎 ${this.t(message, "responses.playnext.searching")}` })
|
||||||
;
|
.setDescription(this.t(message, "responses.playnext.searching"));
|
||||||
|
|
||||||
let statusMsg;
|
let statusMsg;
|
||||||
try {
|
try {
|
||||||
@@ -67,9 +114,24 @@ export async function run(message, data) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const messages = p.playFirst(query, provider);
|
const requester = message.author?.id ?? message.authorId ?? null;
|
||||||
|
const messages = p.playFirst(query, provider, { requester });
|
||||||
messages.on("message", d => {
|
messages.on("message", d => {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(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));
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Set Playing Next author tag on the added track embed */
|
||||||
|
const authorName = embed.data?.author?.name || "";
|
||||||
|
if (authorName.includes("Added to Queue") || !authorName) {
|
||||||
|
embed.setAuthor({ name: this.t(message, "responses.playnext.playingNext") });
|
||||||
|
}
|
||||||
|
|
||||||
if (statusMsg) statusMsg.edit({ embeds: [embed] }).catch(() => {});
|
if (statusMsg) statusMsg.edit({ embeds: [embed] }).catch(() => {});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/previous
|
||||||
|
* @description Play the previous track from recent playback history (supports %prev, %back, %undo).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
|
/** @type {CommandBuilder} @description Command definition for the previous command. */
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("previous")
|
||||||
|
.setDescription("Play the previous track from playback history.", "commands.previous")
|
||||||
|
.addAliases("prev", "back", "undo")
|
||||||
|
.setCategory("music");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* Run handler for the previous command.
|
||||||
|
* Steps backward into the queue's circular playback history.
|
||||||
|
* @param {object} message - The command message wrapper.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message) {
|
||||||
|
const p = await this.getPlayer(message, true, true, false);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
if (!p.queue?.history?.length) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setDescription(this.t(message, "responses.previous.noHistory"));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevSong = await p.playPrevious();
|
||||||
|
if (!prevSong) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setDescription(this.t(message, "responses.previous.failed"));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const titleDisplay = prevSong.title ? Utils.truncate(prevSong.title, 50) : this.t(message, "responses.play.unknownTrack");
|
||||||
|
const trackLink = prevSong.spotifyUrl || prevSong.url || "";
|
||||||
|
const rawAuthor = prevSong.artist || (typeof prevSong.author === "object" ? prevSong.author?.name : prevSong.author);
|
||||||
|
const thumb = prevSong.thumbnail || null;
|
||||||
|
const historyRemaining = p.queue.history.length;
|
||||||
|
|
||||||
|
let desc = trackLink ? `**[${titleDisplay}](${trackLink})**` : `**${titleDisplay}**`;
|
||||||
|
if (rawAuthor) {
|
||||||
|
desc += `\n${this.t(message, "responses.play.byAuthor", { author: rawAuthor })}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `⏮️ ${this.t(message, "responses.previous.author")}` })
|
||||||
|
.setTitle(this.t(message, "responses.previous.title"))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(message, "responses.previous.footer", { count: historyRemaining }) });
|
||||||
|
|
||||||
|
if (thumb) {
|
||||||
|
embed.setThumbnail(thumb);
|
||||||
|
}
|
||||||
|
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
+44
-13
@@ -5,7 +5,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 { getGlobalColor } from "../src/ui/index.mjs";
|
|
||||||
import { logger } from "../src/core/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/utils/UI.mjs";
|
import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/utils/UI.mjs";
|
||||||
|
|
||||||
@@ -38,7 +37,13 @@ export const command = function() {
|
|||||||
*/
|
*/
|
||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const radios = this.config.radio;
|
const radios = this.config.radio;
|
||||||
if (!radios?.length) return msg.reply(this.t(msg, "responses.radio.noStations"));
|
if (!radios?.length) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.radio.stationsAuthor") || "24/7 Radio Station Directory" })
|
||||||
|
.setDescription(this.t(msg, "responses.radio.noStations"));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
const input = (data.get("station")?.value ?? "").trim().toLowerCase();
|
const input = (data.get("station")?.value ?? "").trim().toLowerCase();
|
||||||
|
|
||||||
@@ -50,17 +55,29 @@ export async function run(msg, data) {
|
|||||||
const buildPage = () => {
|
const buildPage = () => {
|
||||||
const start = page * perPage;
|
const start = page * perPage;
|
||||||
const pickable = radios.slice(start, start + perPage);
|
const pickable = radios.slice(start, start + perPage);
|
||||||
|
const prefix = this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guildId) || "%";
|
||||||
|
|
||||||
let desc = `📻 **Radio Stations (Page ${page + 1}/${totalPages})**\n\n`;
|
let desc = "";
|
||||||
pickable.forEach((r, i) => {
|
pickable.forEach((r, i) => {
|
||||||
const displayName = r.detailedName ?? r.name ?? "Station";
|
const displayName = r.detailedName ?? r.name ?? "Station";
|
||||||
const stationDesc = String(r.description ?? "").replaceAll("\n", "\n ");
|
const stationDesc = String(r.description ?? "").replaceAll("\n", "\n ");
|
||||||
desc += `${NUMBER_EMOJIS[i]} **${displayName}** (\`${r.name ?? "station"}\`)\n`;
|
desc += `${NUMBER_EMOJIS[i]} **${displayName}** (\`${prefix}radio ${r.name ?? "station"}\`)\n`;
|
||||||
desc += ` ${stationDesc}\n\n`;
|
if (stationDesc) desc += ` ${stationDesc}\n\n`;
|
||||||
|
else desc += "\n";
|
||||||
});
|
});
|
||||||
desc += `⬅️ Previous ➡️ Next ❌ Cancel`;
|
|
||||||
|
|
||||||
return { payload: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }, pickable };
|
const authorName = this.t(msg, "responses.radio.stationsAuthor") || "24/7 Radio Station Directory";
|
||||||
|
const titleName = this.t(msg, "responses.radio.stationsTitle", { page: page + 1, total: totalPages });
|
||||||
|
const footerText = this.t(msg, "responses.radio.prevNext");
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: authorName })
|
||||||
|
.setTitle(titleName)
|
||||||
|
.setDescription(desc.trim())
|
||||||
|
.setFooter({ text: footerText });
|
||||||
|
|
||||||
|
return { payload: { embeds: [embed] }, pickable };
|
||||||
};
|
};
|
||||||
|
|
||||||
let { payload, pickable } = buildPage();
|
let { payload, pickable } = buildPage();
|
||||||
@@ -88,7 +105,11 @@ export async function run(msg, data) {
|
|||||||
settled = true;
|
settled = true;
|
||||||
unobserve();
|
unobserve();
|
||||||
clearReactions().catch(() => {});
|
clearReactions().catch(() => {});
|
||||||
listMsg.edit(this.t(msg, "responses.radio.timedOut")).catch(() => {});
|
const timedOutEmbed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.radio.stationsAuthor") || "24/7 Radio Station Directory" })
|
||||||
|
.setDescription(this.t(msg, "responses.radio.timedOut"));
|
||||||
|
listMsg.edit({ embeds: [timedOutEmbed] }).catch(() => {});
|
||||||
}, 60_000);
|
}, 60_000);
|
||||||
|
|
||||||
const normalize = (s) => s.replace(/\uFE0F/g, "");
|
const normalize = (s) => s.replace(/\uFE0F/g, "");
|
||||||
@@ -102,7 +123,11 @@ export async function run(msg, data) {
|
|||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
unobserve();
|
unobserve();
|
||||||
await clearReactions();
|
await clearReactions();
|
||||||
listMsg.edit(this.t(msg, "responses.radio.cancelled")).catch(() => {});
|
const cancelEmbed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.radio.stationsAuthor") || "24/7 Radio Station Directory" })
|
||||||
|
.setDescription(this.t(msg, "responses.radio.cancelled"));
|
||||||
|
listMsg.edit({ embeds: [cancelEmbed] }).catch(() => {});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (emoji === normalize(NEXT_EMOJI)) page = (page + 1) % totalPages;
|
if (emoji === normalize(NEXT_EMOJI)) page = (page + 1) % totalPages;
|
||||||
@@ -131,7 +156,11 @@ export async function run(msg, data) {
|
|||||||
const radio = radios.find(r => String(r.name ?? "").toLowerCase() === input);
|
const radio = radios.find(r => String(r.name ?? "").toLowerCase() === input);
|
||||||
if (!radio) {
|
if (!radio) {
|
||||||
const names = radios.map(r => `\`${r.name ?? "station"}\``).join(", ");
|
const names = radios.map(r => `\`${r.name ?? "station"}\``).join(", ");
|
||||||
return msg.reply(this.t(msg, "responses.radio.unknownStation", { station: input, stations: names }));
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.radio.stationsAuthor") || "24/7 Radio Station Directory" })
|
||||||
|
.setDescription(this.t(msg, "responses.radio.unknownStation", { station: input, stations: names }));
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
return playStation(this, msg, radio);
|
return playStation(this, msg, radio);
|
||||||
}
|
}
|
||||||
@@ -165,15 +194,17 @@ async function playStation(ctx, msg, radio, editTarget = null) {
|
|||||||
const stationLine = stationUrl
|
const stationLine = stationUrl
|
||||||
? `**[${stationName}](${stationUrl})**\n\n`
|
? `**[${stationName}](${stationUrl})**\n\n`
|
||||||
: `**${stationName}**\n\n`;
|
: `**${stationName}**\n\n`;
|
||||||
|
const skipHint = ctx.t(msg, "responses.radio.skipHint", { prefix }) || `_Use \`${prefix}skip\` to stop the radio, or \`${prefix}radio list\` to switch stations._`;
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: ctx.t(msg, "responses.radio.liveRadioAuthor") })
|
||||||
.setTitle(`📻 ${stationName}`)
|
.setTitle(`📻 ${stationName}`)
|
||||||
.setDescription(
|
.setDescription(
|
||||||
stationLine +
|
stationLine +
|
||||||
`${stationDesc}\n\n` +
|
`${stationDesc}\n\n` +
|
||||||
`_Use \`${prefix}skip\` to stop the radio, or \`${prefix}radio list\` to switch stations._`
|
skipHint
|
||||||
)
|
)
|
||||||
;
|
.setFooter({ text: ctx.t(msg, "responses.radio.webRadioFooter", { prefix }) });
|
||||||
|
|
||||||
if (editTarget) editTarget.edit({ embeds: [embed] }).catch(() => {});
|
if (editTarget) editTarget.edit({ embeds: [embed] }).catch(() => {});
|
||||||
else msg.reply({ embeds: [embed] }).catch(() => {});
|
else msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
|||||||
+2
-1
@@ -113,9 +113,10 @@ async function showPaged(msg, title, lines, pageSize = 14) {
|
|||||||
embeds: [
|
embeds: [
|
||||||
new EmbedBuilder()
|
new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t ? this.t(msg, "responses.reload.author") : "🔄 Module Hot Reload" })
|
||||||
.setTitle(title)
|
.setTitle(title)
|
||||||
.setDescription(pages[n].join("\n") + (pages.length > 1 ? `\n\nPage **${n + 1}** / **${pages.length}**` : ""))
|
.setDescription(pages[n].join("\n") + (pages.length > 1 ? `\n\nPage **${n + 1}** / **${pages.length}**` : ""))
|
||||||
|
.setFooter({ text: this.t ? this.t(msg, "responses.reload.footer") : "Owner Diagnostics • Dynamic Module Loader" })
|
||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+49
-10
@@ -4,30 +4,69 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
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 the remove command. */
|
/** @type {CommandBuilder} @description Command definition for the remove command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("remove")
|
.setName("remove")
|
||||||
.setDescription("Remove a specific song from the queue.", "commands.remove")
|
.setDescription("Remove a specific song or range of songs (e.g. `3` or `3-6`) from the queue.", "commands.remove")
|
||||||
.setCategory("music")
|
.setCategory("music")
|
||||||
.addNumberOption(opt =>
|
.addTextOption(opt =>
|
||||||
opt.setName("index")
|
opt.setName("position")
|
||||||
.setDescription("The position of the song in the queue. You can view the indices with the 'list' command", "options.remove.index")
|
.setDescription("The position or range of the song(s) to remove (e.g. `3` or `3-6`).", "options.remove.index")
|
||||||
.setRequired(true));
|
.setRequired(true));
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @async
|
* @async
|
||||||
* Run handler for the remove command.
|
* Run handler for the remove command.
|
||||||
* Removes a track at the specified 1-based index from the queue.
|
* Removes a track or range of tracks at the specified 1-based indices from the queue.
|
||||||
* @param {object} message - The command message wrapper.
|
* @param {object} message - The command message wrapper.
|
||||||
* @param {object} data - Parsed command data containing the index option.
|
* @param {object} data - Parsed command data containing the position option.
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
export async function run(message, data) {
|
export async function run(message, data) {
|
||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const index = data.get("index")?.value;
|
const raw = String(data.get("position")?.value ?? "").trim();
|
||||||
if (index === null || index === undefined || index < 1) return message.replyEmbed("Queue position must be 1 or greater.").catch(() => {});
|
const prefix = this.handler?.getPrefix?.(message.message?.guildId ?? message.channel?.guildId) ?? "%";
|
||||||
const res = p.remove(index - 1);
|
if (!raw) return message.replyEmbed("Please provide a queue position or range (e.g. `3` or `3-6`).").catch(() => {});
|
||||||
message.replyEmbed(res).catch(() => {});
|
|
||||||
|
const rangeMatch = raw.match(/^(\d+)\s*[-–—to:]+\s*(\d+)$/i) || raw.match(/^(\d+)\s+(\d+)$/);
|
||||||
|
if (rangeMatch) {
|
||||||
|
const from = parseInt(rangeMatch[1], 10);
|
||||||
|
const to = parseInt(rangeMatch[2], 10);
|
||||||
|
if (from < 1 || to < 1) return message.replyEmbed("Queue positions must be 1 or greater.").catch(() => {});
|
||||||
|
const res = p.removeRange(from - 1, to - 1);
|
||||||
|
if (typeof res === "string" && !res.includes("Successfully")) {
|
||||||
|
return message.replyEmbed(res).catch(() => {});
|
||||||
|
}
|
||||||
|
const remaining = p.queue?.size() ?? 0;
|
||||||
|
const count = Math.abs(to - from) + 1;
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.remove.removedAuthor") })
|
||||||
|
.setTitle(this.t(message, "responses.remove.removedRangeTitle", { count }))
|
||||||
|
.setDescription(this.t(message, "responses.remove.removedRangeDesc", { from: Math.min(from, to), to: Math.max(from, to) }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.remove.remainingFooter", { count: remaining, plural: remaining === 1 ? "" : "s", prefix }) });
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const single = parseInt(raw, 10);
|
||||||
|
if (isNaN(single) || single < 1) return message.replyEmbed("Queue position must be 1 or greater.").catch(() => {});
|
||||||
|
const queueData = p.queue?.data ?? [];
|
||||||
|
const track = queueData[single - 1];
|
||||||
|
const res = p.remove(single - 1);
|
||||||
|
if (typeof res === "string" && res.toLowerCase().includes("out of bounds")) {
|
||||||
|
return message.replyEmbed(res).catch(() => {});
|
||||||
|
}
|
||||||
|
const remaining = p.queue?.size() ?? 0;
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.remove.removedAuthor") })
|
||||||
|
.setTitle(track?.title?.slice(0, 256) || "Removed Track")
|
||||||
|
.setDescription(this.t(message, "responses.remove.removedSingleDesc", { position: single }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.remove.remainingFooter", { count: remaining, plural: remaining === 1 ? "" : "s", prefix }) });
|
||||||
|
if (track?.thumbnail) embed.setThumbnail(track.thumbnail);
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/replay
|
||||||
|
* @description Restart the currently playing track from the beginning without re-fetching from source.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
|
/** @type {CommandBuilder} @description Command definition for the replay command. */
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("replay")
|
||||||
|
.setDescription("Restart the current song from the beginning.", "commands.replay")
|
||||||
|
.addAliases("restart")
|
||||||
|
.setCategory("music");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* Run handler for the replay command.
|
||||||
|
* Seeks the player back to 0:00.
|
||||||
|
* @param {object} message - The command message wrapper.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message) {
|
||||||
|
const p = await this.getPlayer(message, true, true, false);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
const current = p.queue?.getCurrent();
|
||||||
|
if (!current) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setDescription(this.t(message, "responses.replay.nothingPlaying"));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current.type === "radio" || current.isLive) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setDescription(this.t(message, "responses.replay.live"));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const success = await p.seekToPosition(0);
|
||||||
|
if (!success) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setDescription(this.t(message, "responses.replay.failed"));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const titleDisplay = current.title ? Utils.truncate(current.title, 50) : this.t(message, "responses.play.unknownTrack");
|
||||||
|
const trackLink = current.spotifyUrl || current.url || "";
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
const thumb = current.thumbnail || null;
|
||||||
|
const trackDuration = p._getTrackDurationMs(current);
|
||||||
|
const totalStr = trackDuration > 0 ? Utils.prettifyMS(trackDuration) : null;
|
||||||
|
|
||||||
|
let desc = trackLink ? `**[${titleDisplay}](${trackLink})**` : `**${titleDisplay}**`;
|
||||||
|
if (rawAuthor) {
|
||||||
|
desc += `\n${this.t(message, "responses.play.byAuthor", { author: rawAuthor })}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `🔄 ${this.t(message, "responses.replay.author")}` })
|
||||||
|
.setTitle(this.t(message, "responses.replay.title"))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: totalStr ? this.t(message, "responses.replay.footer", { duration: totalStr }) : "Remix Music • Restarted from 0:00" });
|
||||||
|
|
||||||
|
if (thumb) {
|
||||||
|
embed.setThumbnail(thumb);
|
||||||
|
}
|
||||||
|
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
+47
-5
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
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 { getGlobalColor } from "../src/ui/index.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
@@ -26,10 +26,52 @@ export const command = new CommandBuilder()
|
|||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message, false, true, false);
|
const p = await this.getPlayer(message, false, true, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const res = p.resume();
|
|
||||||
|
const current = p.queue.getCurrent();
|
||||||
|
if (!p.connection || !current) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `▶️ ${this.t(message, "responses.resume.resumedTitle")}` })
|
||||||
|
.setDescription(this.t(message, "responses._common.nothingPlaying"));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const prefix = this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) || "%";
|
||||||
|
|
||||||
|
if (!p._paused) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `▶️ ${this.t(message, "responses.resume.resumedTitle")}` })
|
||||||
|
.setDescription(this.t(message, "responses.resume.notPaused"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.resume.pauseHint", { prefix }) });
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
p.resume();
|
||||||
|
p._autoPausedEmpty = false;
|
||||||
|
p._serverMutedAutoPaused = false;
|
||||||
|
const elapsed = p.getCurrentElapsedDuration();
|
||||||
|
const trackUrl = current.spotifyUrl || current.url || null;
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
|
||||||
|
let desc = trackUrl
|
||||||
|
? `**[${Utils.truncate(current.title || this.t(message, "responses.play.unknownTrack"), 50)}](${trackUrl})**`
|
||||||
|
: `**${Utils.truncate(current.title || this.t(message, "responses.play.unknownTrack"), 50)}**`;
|
||||||
|
|
||||||
|
if (rawAuthor) {
|
||||||
|
desc += `\n${this.t(message, "responses.play.byAuthor", { author: rawAuthor })}`;
|
||||||
|
}
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setDescription(res)
|
.setAuthor({ name: `▶️ ${this.t(message, "responses.resume.resumedTitle")}` })
|
||||||
;
|
.setTitle(this.t(message, "responses.resume.resumedAt", { time: elapsed }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(message, "responses.resume.pauseHint", { prefix }) });
|
||||||
|
|
||||||
|
if (current.thumbnail) {
|
||||||
|
embed.setThumbnail(current.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
message.reply({ embeds: [embed] }).catch(() => {});
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+35
-16
@@ -4,10 +4,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { Message, getGlobalColor } from "../src/ui/index.mjs";
|
import { Message } from "../src/ui/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/music/providers.mjs";
|
import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||||
import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/utils/UI.mjs";
|
import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/utils/UI.mjs";
|
||||||
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { logger } from "../src/core/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the search command. */
|
/** @type {CommandBuilder} @description Command definition for the search command. */
|
||||||
@@ -21,6 +22,7 @@ export const command = new CommandBuilder()
|
|||||||
.setCategory("music")
|
.setCategory("music")
|
||||||
.addExamples(
|
.addExamples(
|
||||||
"$prefixsearch never gonna give you up",
|
"$prefixsearch never gonna give you up",
|
||||||
|
"$prefixsearch pop",
|
||||||
"$prefixsearch sp: blinding lights",
|
"$prefixsearch sp: blinding lights",
|
||||||
"$prefixsearch -p dz get lucky"
|
"$prefixsearch -p dz get lucky"
|
||||||
)
|
)
|
||||||
@@ -33,7 +35,7 @@ export const command = new CommandBuilder()
|
|||||||
, true)
|
, true)
|
||||||
.addTextOption(o =>
|
.addTextOption(o =>
|
||||||
o.setName("query")
|
o.setName("query")
|
||||||
.setDescription("The query to search for, or a provider-prefixed query like `sp: song name`.", "options.search.query")
|
.setDescription("The song, artist, or music genre to search for; provider prefixes such as `sp: song name` also work.", "options.search.query")
|
||||||
.setRequired(true)
|
.setRequired(true)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -60,26 +62,35 @@ export async function run(msg, data) {
|
|||||||
const channel = msg.channel?.channel ?? msg.message?.channel;
|
const channel = msg.channel?.channel ?? msg.message?.channel;
|
||||||
if (!channel?.send) return;
|
if (!channel?.send) return;
|
||||||
|
|
||||||
|
let providerIcon = "🔍";
|
||||||
|
if (provider === "sp" || provider === "spotify") providerIcon = "🟢";
|
||||||
|
else if (provider === "sc" || provider === "soundcloud") providerIcon = "🟠";
|
||||||
|
else if (provider === "yt" || provider === "ytm" || provider === "youtube") providerIcon = "▶️";
|
||||||
|
|
||||||
|
const authorTitle = `${providerIcon} ${this.t(msg, "responses.search.resultsTitle", { provider: name })}`;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @private
|
* @private
|
||||||
* Build a search result embed.
|
* Build a search result embed.
|
||||||
* @param {string} description - The embed description text.
|
* @param {string} description - The embed description text.
|
||||||
* @param {string|null} footerText - Optional footer text.
|
* @param {string|null} footerText - Optional footer text.
|
||||||
* @param {string} [authorLabel=name] - The author field label (provider name).
|
* @param {string} [authorLabel=authorTitle] - The author field label.
|
||||||
|
* @param {string|null} [thumbnail=null] - Optional thumbnail URL.
|
||||||
* @returns {EmbedBuilder} The constructed embed.
|
* @returns {EmbedBuilder} The constructed embed.
|
||||||
*/
|
*/
|
||||||
const makeEmbed = (description, footerText, authorLabel = name) => {
|
const makeEmbed = (description, footerText, authorLabel = authorTitle, thumbnail = null) => {
|
||||||
const b = new EmbedBuilder()
|
const b = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setAuthor({ name: authorLabel })
|
.setAuthor({ name: authorLabel })
|
||||||
.setDescription(description);
|
.setDescription(description);
|
||||||
|
if (thumbnail) b.setThumbnail(thumbnail);
|
||||||
if (footerText) b.setFooter({ text: footerText });
|
if (footerText) b.setFooter({ text: footerText });
|
||||||
return b;
|
return b;
|
||||||
};
|
};
|
||||||
|
|
||||||
const nativeMsg = msg.message ?? msg;
|
const nativeMsg = msg.message ?? msg;
|
||||||
const rawMsg = await nativeMsg.reply(
|
const rawMsg = await nativeMsg.reply(
|
||||||
{ embeds: [makeEmbed(this.t(msg, "responses.search.loadingResults"), this.t(msg, "responses.play.searchingProvider", { provider: name }), this.t(msg, "responses.search.resultsTitle", { provider: name }))]},
|
{ embeds: [makeEmbed(this.t(msg, "responses.search.loadingResults"), this.t(msg, "responses.play.searchingProvider", { provider: name }), authorTitle)]},
|
||||||
{ ping: false }
|
{ ping: false }
|
||||||
).catch(() => null);
|
).catch(() => null);
|
||||||
if (!rawMsg) return;
|
if (!rawMsg) return;
|
||||||
@@ -93,20 +104,25 @@ export async function run(msg, data) {
|
|||||||
const results = p.searches.get(msg.authorId) ?? [];
|
const results = p.searches.get(msg.authorId) ?? [];
|
||||||
const reactions = NUMBER_EMOJIS.slice(0, res.count);
|
const reactions = NUMBER_EMOJIS.slice(0, res.count);
|
||||||
|
|
||||||
|
const cancelText = this.t(msg, "responses.search.cancelOption") || "Cancel";
|
||||||
let desc = "";
|
let desc = "";
|
||||||
results.forEach((v, i) => {
|
results.forEach((v, i) => {
|
||||||
const dur = v.duration ? p.getDuration(v.duration) : "?:??";
|
const dur = v.duration ? p.getDuration(v.duration) : "?:??";
|
||||||
const title = v.title || "Unknown";
|
const rawAuthor = v.artist || (typeof v.author === "object" ? v.author?.name : v.author);
|
||||||
const url = v.url || "";
|
const authorStr = rawAuthor ? ` • ${Utils.truncate(rawAuthor, 30)}` : "";
|
||||||
desc += `${NUMBER_EMOJIS[i]} [${title}](${url}) — \`${dur}\`\n`;
|
const title = Utils.truncate(v.title || this.t(msg, "responses.play.unknownTrack"), 50);
|
||||||
|
const url = v.url || "";
|
||||||
|
const titleFmt = url ? `[${title}](${url})` : title;
|
||||||
|
desc += `${NUMBER_EMOJIS[i]} **${titleFmt}**${authorStr} • \`${dur}\`\n\n`;
|
||||||
});
|
});
|
||||||
desc += `\n${CANCEL_EMOJI} Cancel`;
|
desc += `${CANCEL_EMOJI} ${cancelText}`;
|
||||||
|
|
||||||
await rawMsg.edit({
|
await rawMsg.edit({
|
||||||
embeds: [makeEmbed(
|
embeds: [makeEmbed(
|
||||||
desc,
|
desc.trim(),
|
||||||
this.t(msg, "responses.search.reactHint"),
|
this.t(msg, "responses.search.reactHint"),
|
||||||
this.t(msg, "responses.search.resultsTitle", { provider: name })
|
authorTitle,
|
||||||
|
results[0]?.thumbnail || null
|
||||||
)]
|
)]
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
|
|
||||||
@@ -142,8 +158,9 @@ export async function run(msg, data) {
|
|||||||
await clearReactions();
|
await clearReactions();
|
||||||
|
|
||||||
if (e.emoji_id === CANCEL_EMOJI) {
|
if (e.emoji_id === CANCEL_EMOJI) {
|
||||||
|
p.searches.delete(msg.authorId);
|
||||||
rawMsg.edit({
|
rawMsg.edit({
|
||||||
embeds: [makeEmbed(this.t(msg, "responses.search.cancelled"), null, this.t(msg, "responses.search.resultsTitle", { provider: name }))]
|
embeds: [makeEmbed(this.t(msg, "responses.search.cancelled"), null, authorTitle)]
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -158,7 +175,8 @@ export async function run(msg, data) {
|
|||||||
embeds: [makeEmbed(
|
embeds: [makeEmbed(
|
||||||
this.t(msg, "responses.search.added", { title: v.title, url: v.url }),
|
this.t(msg, "responses.search.added", { title: v.title, url: v.url }),
|
||||||
null,
|
null,
|
||||||
this.t(msg, "responses.search.resultsTitle", { provider: name })
|
authorTitle,
|
||||||
|
v.thumbnail || null
|
||||||
)]
|
)]
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
});
|
});
|
||||||
@@ -166,9 +184,10 @@ export async function run(msg, data) {
|
|||||||
const SESSION_MS = this.config?.timers?.searchSessionTimeout ?? 30_000;
|
const SESSION_MS = this.config?.timers?.searchSessionTimeout ?? 30_000;
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
unobserve();
|
unobserve();
|
||||||
|
p.searches.delete(msg.authorId);
|
||||||
clearReactions().catch(() => {});
|
clearReactions().catch(() => {});
|
||||||
rawMsg.edit({
|
rawMsg.edit({
|
||||||
embeds: [makeEmbed(this.t(msg, "responses.search.timedOut"), this.t(msg, "responses.search.sessionClosed"), this.t(msg, "responses.search.resultsTitle", { provider: name }))]
|
embeds: [makeEmbed(this.t(msg, "responses.search.timedOut"), this.t(msg, "responses.search.sessionClosed"), authorTitle)]
|
||||||
}).catch(() => {});
|
}).catch(() => {});
|
||||||
}, SESSION_MS);
|
}, SESSION_MS);
|
||||||
}
|
}
|
||||||
+42
-12
@@ -5,9 +5,7 @@
|
|||||||
|
|
||||||
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 { getGlobalColor } from "../src/ui/index.mjs";
|
|
||||||
import { Utils } from "../src/utils/Utils.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the seek command. */
|
/** @type {CommandBuilder} @description Command definition for the seek command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -34,41 +32,73 @@ export async function run(msg, data) {
|
|||||||
const p = await this.getPlayer(msg, true, true, false);
|
const p = await this.getPlayer(msg, true, true, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
|
|
||||||
|
const seekNotice = (desc) => new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `⏩ ${this.t(msg, "responses.seek.seekTitle")}` })
|
||||||
|
.setDescription(desc);
|
||||||
|
|
||||||
if (!p.queue?.getCurrent()) {
|
if (!p.queue?.getCurrent()) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.nothingPlaying"))] });
|
return msg.reply({ embeds: [seekNotice(this.t(msg, "responses.seek.nothingPlaying"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (p._paused) {
|
if (p._paused) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.paused"))] });
|
return msg.reply({ embeds: [seekNotice(this.t(msg, "responses.seek.paused"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const current = p.queue.getCurrent();
|
const current = p.queue.getCurrent();
|
||||||
|
|
||||||
if (current?.type === "radio" || current?.isLive || p._getTrackDurationMs(current) === 0) {
|
if (current?.type === "radio" || current?.isLive || p._getTrackDurationMs(current) === 0) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.live"))] });
|
return msg.reply({ embeds: [seekNotice(this.t(msg, "responses.seek.live"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
let seekMs = Utils.parseDuration(positionInput);
|
const trimmed = String(positionInput ?? "").trim();
|
||||||
if (!seekMs || seekMs < 0) {
|
const isZero = /^0+(:0+)?(:0+)?$/.test(trimmed);
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.invalidFormat"))] });
|
const seekMs = isZero ? 0 : Utils.parseDuration(trimmed);
|
||||||
|
if (seekMs === null || isNaN(seekMs) || seekMs < 0 || (!isZero && seekMs === 0)) {
|
||||||
|
return msg.reply({ embeds: [seekNotice(this.t(msg, "responses.seek.invalidFormat"))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const trackDuration = p._getTrackDurationMs(p.queue.getCurrent());
|
const trackDuration = p._getTrackDurationMs(p.queue.getCurrent());
|
||||||
|
|
||||||
if (trackDuration > 0 && seekMs >= trackDuration) {
|
if (trackDuration > 0 && seekMs >= trackDuration) {
|
||||||
const maxStr = Utils.prettifyMS(trackDuration);
|
const maxStr = Utils.prettifyMS(trackDuration);
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.exceedsDuration", { duration: maxStr }))] });
|
return msg.reply({ embeds: [seekNotice(this.t(msg, "responses.seek.exceedsDuration", { duration: maxStr }))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await p.seekToPosition(seekMs);
|
const result = await p.seekToPosition(seekMs);
|
||||||
if (result) {
|
if (result) {
|
||||||
const seekStr = Utils.prettifyMS(seekMs);
|
const seekStr = Utils.prettifyMS(seekMs);
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.seek.seeked", { position: seekStr }))] });
|
const totalStr = Utils.prettifyMS(trackDuration);
|
||||||
|
const trackUrl = current.spotifyUrl || current.url || null;
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
const progressBar = Utils.progressBar(seekMs, trackDuration, 18, "▬", "▬", "🔘");
|
||||||
|
|
||||||
|
let desc = trackUrl
|
||||||
|
? `**[${Utils.truncate(current.title || this.t(msg, "responses.play.unknownTrack"), 50)}](${trackUrl})**`
|
||||||
|
: `**${Utils.truncate(current.title || this.t(msg, "responses.play.unknownTrack"), 50)}**`;
|
||||||
|
|
||||||
|
if (rawAuthor) {
|
||||||
|
desc += `\n${this.t(msg, "responses.play.byAuthor", { author: rawAuthor })}`;
|
||||||
|
}
|
||||||
|
desc += `\n\n` + "`" + progressBar + "`";
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `⏩ ${this.t(msg, "responses.seek.seekTitle")}` })
|
||||||
|
.setTitle(this.t(msg, "responses.seek.seekSubtitle", { position: seekStr, duration: totalStr }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.seek.seeked", { position: seekStr }) });
|
||||||
|
|
||||||
|
if (current.thumbnail) {
|
||||||
|
embed.setThumbnail(current.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
} else {
|
} else {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.notSupported"))] });
|
return msg.reply({ embeds: [seekNotice(this.t(msg, "responses.seek.notSupported"))] });
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.failed", { error: err.message }))] });
|
return msg.reply({ embeds: [seekNotice(this.t(msg, "responses.seek.failed", { error: err.message }))] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+11
-8
@@ -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");
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -30,9 +31,10 @@ export async function run(msg) {
|
|||||||
if (guilds.length === 0) {
|
if (guilds.length === 0) {
|
||||||
const emptyEmbed = new EmbedBuilder()
|
const emptyEmbed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.servers.serversAuthor") })
|
||||||
.setTitle(this.t(msg, "responses.servers.title", { count: 0 }))
|
.setTitle(this.t(msg, "responses.servers.title", { count: 0 }))
|
||||||
.setDescription(this.t(msg, "responses.servers.noServers"))
|
.setDescription(this.t(msg, "responses.servers.noServers"))
|
||||||
;
|
.setFooter({ text: this.t(msg, "responses.servers.listComplete") });
|
||||||
return msg.reply({ embeds: [emptyEmbed] });
|
return msg.reply({ embeds: [emptyEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,7 +48,8 @@ export async function run(msg) {
|
|||||||
const g = guilds[i];
|
const g = guilds[i];
|
||||||
let name = g.name || "unknown";
|
let name = g.name || "unknown";
|
||||||
if (name.length > 40) name = name.slice(0, 37) + "...";
|
if (name.length > 40) name = name.slice(0, 37) + "...";
|
||||||
const line = `${i + 1}. **${name}** (\`${g.id}\`)`;
|
const num = String(i + 1).padStart(2, "0");
|
||||||
|
const line = `\`${num}.\` **${name}** \`(${g.id})\``;
|
||||||
const addedLen = line.length + (currentLines.length ? 1 : 0);
|
const addedLen = line.length + (currentLines.length ? 1 : 0);
|
||||||
|
|
||||||
if (currentLen + addedLen > MAX_DESC - 20 && currentLines.length > 0) {
|
if (currentLen + addedLen > MAX_DESC - 20 && currentLines.length > 0) {
|
||||||
@@ -73,16 +76,16 @@ export async function run(msg) {
|
|||||||
const buildPageContent = (pageIdx, expired = false) => {
|
const buildPageContent = (pageIdx, expired = false) => {
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(this.t(msg, "responses.servers.pageTitle", { count: guilds.length, page: pageIdx + 1, total: totalPages }))
|
.setAuthor({ name: this.t(msg, "responses.servers.serversAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.servers.serversTitle"))
|
||||||
.setDescription(pages[pageIdx])
|
.setDescription(pages[pageIdx])
|
||||||
.setFooter({
|
.setFooter({
|
||||||
text: expired
|
text: expired
|
||||||
? this.t(msg, "responses._common.controlsExpired")
|
? this.t(msg, "responses._common.controlsExpired")
|
||||||
: totalPages > 1
|
: totalPages > 1
|
||||||
? this.t(msg, "responses._common.navigateHint")
|
? this.t(msg, "responses.servers.serversTelemetryFooter", { page: pageIdx + 1, total: totalPages })
|
||||||
: this.t(msg, "responses.servers.listComplete")
|
: this.t(msg, "responses.servers.listComplete")
|
||||||
})
|
});
|
||||||
;
|
|
||||||
|
|
||||||
return { embeds: [embed] };
|
return { embeds: [embed] };
|
||||||
};
|
};
|
||||||
|
|||||||
+126
-45
@@ -7,8 +7,8 @@
|
|||||||
|
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/commands/index.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { getMessageGuildId } from "../src/ui/index.mjs";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { logger } from "../src/core/Logger.mjs";
|
import { getMessageGuildId, getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import {
|
import {
|
||||||
SHORTCUTS, BOOL_SETTINGS, VALID_LOCALES, setValidLocales,
|
SHORTCUTS, BOOL_SETTINGS, VALID_LOCALES, setValidLocales,
|
||||||
VOLUME_MIN, VOLUME_MAX,
|
VOLUME_MIN, VOLUME_MAX,
|
||||||
@@ -182,35 +182,77 @@ export async function run(message, data) {
|
|||||||
const desc = this.settingsMgr.descriptions?.[settingKey];
|
const desc = this.settingsMgr.descriptions?.[settingKey];
|
||||||
const resolvedDesc = desc ? desc.replace(/\$prefix/gi, prefix) : null;
|
const resolvedDesc = desc ? desc.replace(/\$prefix/gi, prefix) : null;
|
||||||
const label = prettifySettingLabel(settingKey, t247, guildId);
|
const label = prettifySettingLabel(settingKey, t247, guildId);
|
||||||
let reply = "**" + label + "**\nValue: " + displayValue(settingKey, val);
|
|
||||||
if (resolvedDesc) reply += "\n\n*" + resolvedDesc + "*";
|
const inspEmbed = new EmbedBuilder()
|
||||||
return message.reply(embed(reply));
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.settings.inspectorTitle") })
|
||||||
|
.setTitle(label)
|
||||||
|
.addFields(
|
||||||
|
{ name: this.t(message, "responses.settings.settingValueField"), value: displayValue(settingKey, val), inline: true }
|
||||||
|
);
|
||||||
|
if (resolvedDesc) {
|
||||||
|
inspEmbed.addFields({ name: this.t(message, "responses.settings.settingDescField"), value: `*${resolvedDesc}*`, inline: false });
|
||||||
|
}
|
||||||
|
inspEmbed.setFooter({ text: this.t(message, "responses.settings.inspectorFooter", { prefix, setting: settingKey }) });
|
||||||
|
return message.reply({ embeds: [inspEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
||||||
const lines = this.settingsMgr.getPublicKeys()
|
|
||||||
.map(k => {
|
|
||||||
if (k === "stay_247") {
|
|
||||||
return "\u2022 **24/7 mode** " + String.fromCharCode(8212) + " " + (channels.size > 0
|
|
||||||
? channels.size + " channel(s)"
|
|
||||||
: "\u274c disabled");
|
|
||||||
}
|
|
||||||
const label = prettifySettingLabel(k, t247, guildId);
|
|
||||||
return "\u2022 **" + label + "** " + String.fromCharCode(8212) + " " + displayValue(k, d[k]);
|
|
||||||
});
|
|
||||||
|
|
||||||
return message.reply(embed(
|
/* Category 1: General & Localization */
|
||||||
this.t(message, "responses.settings.serverHeader", { name: guildName }) + "\n\n" + lines.join("\n") + "\n\n" +
|
const prefixVal = d.prefix ?? "%";
|
||||||
this.t(message, "responses.settings.shortcutsHint", { prefix }),
|
const localeVal = d.locale ?? "en";
|
||||||
{ title: this.t(message, "responses.settings.serverTitle"), iconURL: iconUrl }
|
const pfpVal = d.pfp ?? "default";
|
||||||
));
|
const generalLines = [
|
||||||
|
`• **${prettifySettingLabel("prefix", t247, guildId)}**: \`${prefixVal}\``,
|
||||||
|
`• **${prettifySettingLabel("locale", t247, guildId)}**: \`${localeVal}\``,
|
||||||
|
`• **${prettifySettingLabel("pfp", t247, guildId)}**: \`${pfpVal}\``
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
/* Category 2: Audio & Playback */
|
||||||
|
const volVal = d.volume ?? 100;
|
||||||
|
const songAnnounce = d.songAnnouncements ?? true;
|
||||||
|
const normVal = d.normalize ?? true;
|
||||||
|
const voteSkipVal = d.voteSkip ?? true;
|
||||||
|
const voteLimit = d.voteSkipThreshold ?? 3;
|
||||||
|
const audioLines = [
|
||||||
|
`• **${prettifySettingLabel("volume", t247, guildId)}**: \`${volVal}%\``,
|
||||||
|
`• **${prettifySettingLabel("normalize", t247, guildId)}**: ${normVal ? "✅ enabled (EBU R128)" : "❌ disabled"}`,
|
||||||
|
`• **${prettifySettingLabel("songAnnouncements", t247, guildId)}**: ${songAnnounce ? "✅ enabled" : "❌ disabled"}`,
|
||||||
|
`• **${prettifySettingLabel("voteSkip", t247, guildId)}**: ${voteSkipVal ? `✅ enabled (≥${voteLimit})` : "❌ disabled"}`
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
/* Category 3: 24/7 Voice Connection */
|
||||||
|
let voice247Text = "❌ disabled";
|
||||||
|
if (channels.size > 0) {
|
||||||
|
const chList = [...channels].map(id => `<#${id}>`).join(", ");
|
||||||
|
voice247Text = `🔊 ${chList} — **${this.t(message, "responses.settings.statusActive247")}**`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const dashEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(message, "responses.settings.dashboardTitle") })
|
||||||
|
.setTitle(guildName)
|
||||||
|
.addFields(
|
||||||
|
{ name: this.t(message, "responses.settings.categoryGeneral"), value: generalLines, inline: false },
|
||||||
|
{ name: this.t(message, "responses.settings.categoryAudio"), value: audioLines, inline: false },
|
||||||
|
{ name: this.t(message, "responses.settings.categoryVoice247"), value: voice247Text, inline: false }
|
||||||
|
)
|
||||||
|
.setFooter({ text: this.t(message, "responses.settings.dashboardFooter", { prefix }) });
|
||||||
|
|
||||||
|
if (iconUrl) {
|
||||||
|
dashEmbed.setThumbnail(iconUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
return message.reply({ embeds: [dashEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cmd === "resetSettings") {
|
if (cmd === "resetSettings") {
|
||||||
@@ -231,15 +273,31 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
if (cmd === "helpSettings") {
|
if (cmd === "helpSettings") {
|
||||||
if (!settingKey) {
|
if (!settingKey) {
|
||||||
const keys = this.settingsMgr.getPublicKeys();
|
const keys = this.settingsMgr.getPublicKeys();
|
||||||
const keyList = keys.map(k => "`" + k + "`").join(", ");
|
const keyTags = keys.map(k => "`" + k + "`").join(" ");
|
||||||
return message.reply(embed(
|
const handbookEmbed = new EmbedBuilder()
|
||||||
this.t(message, "responses.settings.helpTitle") + "\n\n" +
|
.setColor(getGlobalColor())
|
||||||
this.t(message, "responses.settings.helpAvailable", { settings: keyList }) + "\n\n" +
|
.setAuthor({ name: this.t(message, "responses.settings.handbookAuthor") })
|
||||||
this.t(message, "responses.settings.helpSubcommands", { prefix }) + "\n\n" +
|
.setTitle(this.t(message, "responses.settings.handbookTitle"))
|
||||||
this.t(message, "responses.settings.helpShortcuts", { prefix }),
|
.setDescription(this.t(message, "responses.settings.handbookDesc"))
|
||||||
{ title: "\u2699\ufe0f Settings Help" }
|
.addFields(
|
||||||
));
|
{
|
||||||
|
name: `📋 ${this.t(message, "responses.settings.handbookParamsField")}`,
|
||||||
|
value: keyTags,
|
||||||
|
inline: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `⚡ ${this.t(message, "responses.settings.handbookOpsField")}`,
|
||||||
|
value:
|
||||||
|
`• \`${prefix}settings get\` — ${this.t(message, "responses.settings.handbookOpGet")}\n` +
|
||||||
|
`• \`${prefix}settings set <key> <val>\` — ${this.t(message, "responses.settings.handbookOpSet")}\n` +
|
||||||
|
`• \`${prefix}settings reset <key>\` — ${this.t(message, "responses.settings.handbookOpReset")}\n` +
|
||||||
|
`• \`${prefix}settings help <key>\` — ${this.t(message, "responses.settings.handbookOpHelp")}`,
|
||||||
|
inline: false,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.setFooter({ text: `${this.t(message, "responses.settings.handbookShortcutsField")}: ${prefix}247 · ${prefix}volume · ${prefix}prefix` });
|
||||||
|
return message.reply({ embeds: [handbookEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawDescription = this.settingsMgr.descriptions?.[settingKey] ?? this.t(message, "responses.settings.noDescription");
|
const rawDescription = this.settingsMgr.descriptions?.[settingKey] ?? this.t(message, "responses.settings.noDescription");
|
||||||
@@ -247,24 +305,47 @@ export async function run(message, data) {
|
|||||||
const currentVal = set.get(settingKey);
|
const currentVal = set.get(settingKey);
|
||||||
const defaultVal = this.settingsMgr.defaults?.[settingKey];
|
const defaultVal = this.settingsMgr.defaults?.[settingKey];
|
||||||
|
|
||||||
let extra = "";
|
let rangeInfo = "";
|
||||||
if (settingKey === "locale") {
|
if (settingKey === "locale") {
|
||||||
extra = "\n**Valid values:** " + [...VALID_LOCALES].map(l => "`" + l + "`").join(", ");
|
rangeInfo = [...VALID_LOCALES].map(l => "`" + l + "`").join(", ");
|
||||||
} else if (settingKey === "volume") {
|
} else if (settingKey === "volume") {
|
||||||
extra = "\n**Valid range:** " + VOLUME_MIN + "\u2013" + VOLUME_MAX;
|
rangeInfo = `${VOLUME_MIN} – ${VOLUME_MAX}`;
|
||||||
} else if (BOOL_SETTINGS.has(settingKey)) {
|
} else if (BOOL_SETTINGS.has(settingKey)) {
|
||||||
extra = "\n**Valid values:** `true`, `false`, `on`, `off`";
|
rangeInfo = "`true`, `false`, `on`, `off`";
|
||||||
} else if (settingKey === "stay_247") {
|
} else if (settingKey === "stay_247") {
|
||||||
extra = "\n**Usage:** Join a voice channel and use `247` to toggle.\n\nThe bot stays in that channel and auto-rejoins if disconnected.";
|
rangeInfo = `${prefix}247`;
|
||||||
}
|
}
|
||||||
|
|
||||||
const label = prettifySettingLabel(settingKey, t247, guildId);
|
const inspectorEmbed = new EmbedBuilder()
|
||||||
return message.reply(embed(
|
.setColor(getGlobalColor())
|
||||||
"**\u2699\ufe0f Setting: `" + settingKey + "`**\n\n" +
|
.setAuthor({ name: this.t(message, "responses.settings.inspectorTitle") })
|
||||||
description + extra + "\n\n" +
|
.setTitle(`⚙️ \`${settingKey}\``)
|
||||||
"**Current value:** " + displayValue(settingKey, currentVal) + "\n" +
|
.setDescription(description)
|
||||||
"**Default:** " + displayValue(settingKey, defaultVal),
|
.addFields(
|
||||||
{ title: "\u2699\ufe0f " + settingKey }
|
{
|
||||||
));
|
name: `📌 ${this.t(message, "responses.settings.settingValueField")}`,
|
||||||
|
value: displayValue(settingKey, currentVal),
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `🏷️ ${this.t(message, "responses.settings.settingDefaultField")}`,
|
||||||
|
value: displayValue(settingKey, defaultVal),
|
||||||
|
inline: true,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (rangeInfo) {
|
||||||
|
inspectorEmbed.addFields({
|
||||||
|
name: `🎯 ${this.t(message, "responses.settings.settingRangeField")}`,
|
||||||
|
value: rangeInfo,
|
||||||
|
inline: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
inspectorEmbed.setFooter({
|
||||||
|
text: this.t(message, "responses.settings.inspectorFooter", { prefix, setting: settingKey }),
|
||||||
|
});
|
||||||
|
|
||||||
|
return message.reply({ embeds: [inspectorEmbed] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
import { cleanId } from "../../src/ui/index.mjs";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { cleanId, getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
import { isPlayerConnectionDead } from "../../src/utils/Helpers247.mjs";
|
import { isPlayerConnectionDead } from "../../src/utils/Helpers247.mjs";
|
||||||
import { isValidFluxerId, MAX_247_CHANNELS, embed, tWrap } from "./utils.mjs";
|
import { isValidFluxerId, MAX_247_CHANNELS, embed, tWrap } from "./utils.mjs";
|
||||||
|
|
||||||
@@ -134,7 +135,7 @@ function build247PanelDescription(set, ctx, guildId, justToggledId = null) {
|
|||||||
.sort((a, b) => a.order - b.order);
|
.sort((a, b) => a.order - b.order);
|
||||||
|
|
||||||
const lines = statuses.map(s =>
|
const lines = statuses.map(s =>
|
||||||
s.line + (justToggledId && s.line.includes("<#" + cleanId(justToggledId) + ">") ? " \u2190" : "")
|
s.line + (justToggledId && s.line.includes("<#" + cleanId(justToggledId) + ">") ? " ←" : "")
|
||||||
);
|
);
|
||||||
|
|
||||||
const allConnected = statuses.every(s => s.state === "connected");
|
const allConnected = statuses.every(s => s.state === "connected");
|
||||||
@@ -161,11 +162,56 @@ function build247PanelDescription(set, ctx, guildId, justToggledId = null) {
|
|||||||
export function build247Panel(set, ctx, guildId, justToggledId = null) {
|
export function build247Panel(set, ctx, guildId, justToggledId = null) {
|
||||||
const t = tWrap(ctx, guildId);
|
const t = tWrap(ctx, guildId);
|
||||||
const prefix = ctx.handler.getPrefix(guildId);
|
const prefix = ctx.handler.getPrefix(guildId);
|
||||||
|
const channels = [...get247Channels(set)];
|
||||||
const panelKey = (k, vars = {}) => t("responses.settings.247Panel." + k, vars);
|
const panelKey = (k, vars = {}) => t("responses.settings.247Panel." + k, vars);
|
||||||
return embed(
|
|
||||||
build247PanelDescription(set, ctx, guildId, justToggledId),
|
const watchdog = ctx.gatewayHandler;
|
||||||
{ title: panelKey("title"), footer: panelKey("footerLine", { prefix }) }
|
const watchdogOn = watchdog?.isWatchdog247Running?.() === true;
|
||||||
);
|
const sweepSeconds = Math.round((watchdog?._247WatchdogInterval ?? 60_000) / 1000);
|
||||||
|
|
||||||
|
const panelEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: panelKey("watchdogAuthor") })
|
||||||
|
.setTitle(panelKey("watchdogTitle"))
|
||||||
|
.setFooter({ text: panelKey("watchdogFooter", { prefix }) });
|
||||||
|
|
||||||
|
if (channels.length === 0) {
|
||||||
|
panelEmbed.setDescription(
|
||||||
|
panelKey("disabledLine") + "\n\n" +
|
||||||
|
panelKey("allChannelsDisabled") + "\n\n" +
|
||||||
|
panelKey("disabledHint", { prefix })
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
const statuses = channels
|
||||||
|
.map(id => channelStatus(ctx, guildId, id, t))
|
||||||
|
.sort((a, b) => a.order - b.order);
|
||||||
|
|
||||||
|
const lines = statuses.map(s =>
|
||||||
|
s.line + (justToggledId && s.line.includes("<#" + cleanId(justToggledId) + ">") ? " ←" : "")
|
||||||
|
);
|
||||||
|
|
||||||
|
const allConnected = statuses.every(s => s.state === "connected");
|
||||||
|
const statusHeader = (channels.length === 1 && allConnected
|
||||||
|
? panelKey("enabledLine")
|
||||||
|
: panelKey(channels.length === 1 ? "activeChannels_one" : "activeChannels_other", { count: channels.length }));
|
||||||
|
|
||||||
|
panelEmbed.setDescription(statusHeader + "\n\n" + lines.join("\n"));
|
||||||
|
|
||||||
|
panelEmbed.addFields(
|
||||||
|
{
|
||||||
|
name: panelKey("watchdogFieldRecovery"),
|
||||||
|
value: watchdogOn ? panelKey("watchdogRecoveryArmed", { seconds: sweepSeconds }) : panelKey("autoRecoveryDisabledLine"),
|
||||||
|
inline: true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: panelKey("watchdogFieldInactivity"),
|
||||||
|
value: panelKey("watchdogInactivitySuppressed"),
|
||||||
|
inline: true
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { embeds: [panelEmbed] };
|
||||||
}
|
}
|
||||||
/**
|
/**
|
||||||
* Disable 24/7 mode for a specific channel.
|
* Disable 24/7 mode for a specific channel.
|
||||||
@@ -269,17 +315,19 @@ export async function handle247Toggle(ctx, message, set, guildId) {
|
|||||||
|
|
||||||
if (channels.has(id)) {
|
if (channels.has(id)) {
|
||||||
await disable247(ctx, set, guildId, userChannelId);
|
await disable247(ctx, set, guildId, userChannelId);
|
||||||
return message.reply(embed(
|
const panel = build247Panel(set, ctx, guildId, null);
|
||||||
panelKey("confirmDisabled", { channel: "<#" + id + ">" }) + "\n\n" +
|
panel.embeds[0].setDescription(
|
||||||
build247PanelDescription(set, ctx, guildId, null),
|
panelKey("confirmDisabled", { channel: "<#" + id + ">" }) + "\n\n" +
|
||||||
{ title: panelKey("title") }
|
panel.embeds[0].description
|
||||||
));
|
);
|
||||||
|
return message.reply(panel);
|
||||||
}
|
}
|
||||||
|
|
||||||
await enable247(ctx, set, guildId, userChannelId);
|
await enable247(ctx, set, guildId, userChannelId);
|
||||||
return message.reply(embed(
|
const panel = build247Panel(set, ctx, guildId, id);
|
||||||
panelKey("confirmEnabled", { channel: "<#" + id + ">" }) + "\n\n" +
|
panel.embeds[0].setDescription(
|
||||||
build247PanelDescription(set, ctx, guildId, id),
|
panelKey("confirmEnabled", { channel: "<#" + id + ">" }) + "\n\n" +
|
||||||
{ title: panelKey("title") }
|
panel.embeds[0].description
|
||||||
));
|
);
|
||||||
|
return message.reply(panel);
|
||||||
}
|
}
|
||||||
@@ -6,15 +6,16 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
import { cleanId, getMessageGuildId } from "../../src/ui/index.mjs";
|
import { cleanId, getMessageGuildId, getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import runnables from "../../settings/runnables.mjs";
|
import runnables from "../../settings/runnables.mjs";
|
||||||
import {
|
import {
|
||||||
parseBool, displayValue, getGuildName, embed, tWrap, prettifySettingLabel,
|
parseBool, displayValue, embed, tWrap, prettifySettingLabel,
|
||||||
BOOL_SETTINGS, VALID_LOCALES, VOLUME_MIN, VOLUME_MAX, PREFIX_MAX, SHORTCUTS,
|
BOOL_SETTINGS, VALID_LOCALES, VOLUME_MIN, VOLUME_MAX, PREFIX_MAX,
|
||||||
VOTE_SKIP_THRESHOLD_MIN, VOTE_SKIP_THRESHOLD_MAX,
|
VOTE_SKIP_THRESHOLD_MIN, VOTE_SKIP_THRESHOLD_MAX,
|
||||||
} from "./utils.mjs";
|
} from "./utils.mjs";
|
||||||
import {
|
import {
|
||||||
get247Channels, save247Channels, build247Panel, disable247, handle247Toggle,
|
save247Channels, disable247, handle247Toggle,
|
||||||
} from "./channels247.mjs";
|
} from "./channels247.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -81,7 +82,7 @@ export async function applySet(ctx, message, set, key, rawValue) {
|
|||||||
|
|
||||||
if (runnables[key]) {
|
if (runnables[key]) {
|
||||||
const err = runnables[key].call(ctx, rawValue, { msg: message });
|
const err = runnables[key].call(ctx, rawValue, { msg: message });
|
||||||
if (err) return "\u274c " + err;
|
if (err) return "❌ " + err;
|
||||||
}
|
}
|
||||||
|
|
||||||
set.set(key, rawValue);
|
set.set(key, rawValue);
|
||||||
@@ -109,7 +110,30 @@ export async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
|||||||
}
|
}
|
||||||
const val = set.get(settingKey);
|
const val = set.get(settingKey);
|
||||||
const label = prettifySettingLabel(settingKey, t247, guildId);
|
const label = prettifySettingLabel(settingKey, t247, guildId);
|
||||||
return message.reply(embed("**" + label + "**\nValue: " + displayValue(settingKey, val)));
|
const defaultVal = ctx.settingsMgr?.defaults?.[settingKey];
|
||||||
|
const shortcutEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: ctx.t(message, "responses.settings.shortcutAuthor") })
|
||||||
|
.setTitle(`⚙️ \`${settingKey}\` — ${label}`)
|
||||||
|
.addFields(
|
||||||
|
{
|
||||||
|
name: `📌 ${ctx.t(message, "responses.settings.shortcutValueField")}`,
|
||||||
|
value: displayValue(settingKey, val),
|
||||||
|
inline: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: `🏷️ ${ctx.t(message, "responses.settings.shortcutDefaultField")}`,
|
||||||
|
value: displayValue(settingKey, defaultVal),
|
||||||
|
inline: true,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
.setFooter({
|
||||||
|
text: ctx.t(message, "responses.settings.shortcutHintFooter", {
|
||||||
|
prefix: ctx.handler?.getPrefix(guildId) ?? "%",
|
||||||
|
shortcut: settingKey,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
return message.reply({ embeds: [shortcutEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawValue = valueTokens.join(" ");
|
const rawValue = valueTokens.join(" ");
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ const BOOL_TRUE = new Set(["true", "1", "yes", "on", "enable", "enabled"]);
|
|||||||
/** @private @type {Set<string>} Strings that evaluate to boolean false. */
|
/** @private @type {Set<string>} Strings that evaluate to boolean false. */
|
||||||
const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]);
|
const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]);
|
||||||
/** @private @type {Set<string>} Setting keys that use boolean display formatting. */
|
/** @private @type {Set<string>} Setting keys that use boolean display formatting. */
|
||||||
export const BOOL_SETTINGS = new Set(["songAnnouncements", "voteSkip"]);
|
export const BOOL_SETTINGS = new Set(["songAnnouncements", "voteSkip", "normalize"]);
|
||||||
|
|
||||||
/** @private @type {Set<string>} Available locale codes, populated at load time. */
|
/** @private @type {Set<string>} Available locale codes, populated at load time. */
|
||||||
export let VALID_LOCALES = new Set(["en"]);
|
export let VALID_LOCALES = new Set(["en"]);
|
||||||
@@ -83,7 +83,7 @@ export function parseBool(str) {
|
|||||||
* @returns {string} Formatted display string.
|
* @returns {string} Formatted display string.
|
||||||
*/
|
*/
|
||||||
export function displayValue(key, value) {
|
export function displayValue(key, value) {
|
||||||
if (BOOL_SETTINGS.has(key)) return value ? "\u2705 enabled" : "\u274c disabled";
|
if (BOOL_SETTINGS.has(key)) return value ? "✅ enabled" : "❌ disabled";
|
||||||
if (value === null || value === undefined || value === "none") return "none";
|
if (value === null || value === undefined || value === "none") return "none";
|
||||||
return "`" + value + "`";
|
return "`" + value + "`";
|
||||||
}
|
}
|
||||||
@@ -138,6 +138,7 @@ export function prettifySettingLabel(key, t, guildId) {
|
|||||||
locale: "responses.settings.labelLocale",
|
locale: "responses.settings.labelLocale",
|
||||||
stay_247: "responses.settings.label247",
|
stay_247: "responses.settings.label247",
|
||||||
volume: "responses.settings.labelVolume",
|
volume: "responses.settings.labelVolume",
|
||||||
|
normalize: "responses.settings.labelNormalize",
|
||||||
voteSkip: "responses.settings.labelVoteSkip",
|
voteSkip: "responses.settings.labelVoteSkip",
|
||||||
voteSkipThreshold: "responses.settings.labelVoteSkipThreshold",
|
voteSkipThreshold: "responses.settings.labelVoteSkipThreshold",
|
||||||
};
|
};
|
||||||
@@ -149,6 +150,7 @@ export function prettifySettingLabel(key, t, guildId) {
|
|||||||
locale: "Locale",
|
locale: "Locale",
|
||||||
stay_247: "24/7 mode",
|
stay_247: "24/7 mode",
|
||||||
volume: "Default volume",
|
volume: "Default volume",
|
||||||
|
normalize: "Volume normalization",
|
||||||
voteSkip: "Vote to skip",
|
voteSkip: "Vote to skip",
|
||||||
voteSkipThreshold: "Vote to skip threshold",
|
voteSkipThreshold: "Vote to skip threshold",
|
||||||
};
|
};
|
||||||
|
|||||||
+35
-5
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
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 { getGlobalColor } from "../src/ui/index.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
@@ -26,10 +26,40 @@ export const command = new CommandBuilder()
|
|||||||
export async function run(message) {
|
export async function run(message) {
|
||||||
const p = await this.getPlayer(message, false, true, false);
|
const p = await this.getPlayer(message, false, true, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const res = p.shuffle();
|
|
||||||
|
if (p.isEmpty()) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `🔀 ${this.t(message, "responses.shuffle.shuffledTitle")}` })
|
||||||
|
.setDescription(this.t(message, "responses._common.nothingPlaying"));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
p.queue.shuffle();
|
||||||
|
p.emit("update", "queue");
|
||||||
|
|
||||||
|
const totalTracks = p.queue.size();
|
||||||
|
const pluralStr = totalTracks === 1 ? this.t(message, "responses.play.trackSingle") : this.t(message, "responses.play.trackPlural");
|
||||||
|
const nextTrack = p.queue.data?.[0];
|
||||||
|
const nextTitle = nextTrack?.title ? Utils.truncate(nextTrack.title, 40) : null;
|
||||||
|
const rawAuthor = nextTrack ? (nextTrack.artist || (typeof nextTrack.author === "object" ? nextTrack.author?.name : nextTrack.author)) : null;
|
||||||
|
const prefix = this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) || "%";
|
||||||
|
|
||||||
|
let desc = `**${this.t(message, "responses.shuffle.shuffledSummary", { count: totalTracks, plural: pluralStr })}**`;
|
||||||
|
if (nextTitle) {
|
||||||
|
const authorStr = rawAuthor ? ` • ${rawAuthor}` : "";
|
||||||
|
desc += `\n\n▶️ **${this.t(message, "responses.shuffle.newUpNext")}:**\n${nextTitle}${authorStr}`;
|
||||||
|
}
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setDescription(res)
|
.setAuthor({ name: `🔀 ${this.t(message, "responses.shuffle.shuffledTitle")}` })
|
||||||
;
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(message, "responses.shuffle.viewOrderFooter", { prefix }) });
|
||||||
|
|
||||||
|
if (nextTrack?.thumbnail) {
|
||||||
|
embed.setThumbnail(nextTrack.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
message.reply({ embeds: [embed] }).catch(() => {});
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+47
-9
@@ -7,8 +7,9 @@
|
|||||||
|
|
||||||
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 { getGlobalColor, cleanId } from "../src/ui/index.mjs";
|
import { cleanId } from "../src/ui/index.mjs";
|
||||||
import { countHumansInChannel } from "../src/voice/VoiceStateResolver.mjs";
|
import { countHumansInChannel } from "../src/voice/VoiceStateResolver.mjs";
|
||||||
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the skip command. */
|
/** @type {CommandBuilder} @description Command definition for the skip command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -22,18 +23,50 @@ async function doSkip(ctx, message, p) {
|
|||||||
const current = p.queue.getCurrent();
|
const current = p.queue.getCurrent();
|
||||||
const skippedTitle = current?.title ?? null;
|
const skippedTitle = current?.title ?? null;
|
||||||
const skippedLink = current ? (current.spotifyUrl || current.url || "") : "";
|
const skippedLink = current ? (current.spotifyUrl || current.url || "") : "";
|
||||||
|
const rawAuthor = current ? (current.artist || (typeof current.author === "object" ? current.author?.name : current.author)) : null;
|
||||||
|
const skippedThumb = current?.thumbnail || null;
|
||||||
|
const elapsed = p.getCurrentElapsedDuration();
|
||||||
|
|
||||||
const err = p.skip();
|
const err = p.skip();
|
||||||
if (!p.connection || !current) {
|
if (!p.connection || !current) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(err);
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `⏭️ ${ctx.t(message, "responses.skip.skippedTitle")}` })
|
||||||
|
.setDescription(err);
|
||||||
return message.reply({ embeds: [embed] });
|
return message.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
const desc = skippedTitle
|
const nextTrack = p.queue.data?.[0];
|
||||||
? ctx.t(message, "responses.skip.skippedTrack", { title: skippedTitle, url: skippedLink })
|
const nextTitle = nextTrack?.title ? Utils.truncate(nextTrack.title, 40) : null;
|
||||||
: ctx.t(message, "responses.skip.skipped");
|
const queueCount = p.queue.size();
|
||||||
|
const pluralStr = queueCount === 1 ? ctx.t(message, "responses.play.trackSingle") : ctx.t(message, "responses.play.trackPlural");
|
||||||
|
|
||||||
message.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }).catch(() => {});
|
const authorLabel = `⏭️ ${ctx.t(message, "responses.skip.skippedTitle")}`;
|
||||||
|
const titleDisplay = skippedTitle ? Utils.truncate(skippedTitle, 50) : ctx.t(message, "responses.play.unknownTrack");
|
||||||
|
|
||||||
|
let desc = skippedLink ? `**[${titleDisplay}](${skippedLink})**` : `**${titleDisplay}**`;
|
||||||
|
if (rawAuthor) {
|
||||||
|
desc += `\n${ctx.t(message, "responses.play.byAuthor", { author: rawAuthor })}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const footerParts = [];
|
||||||
|
if (nextTitle) {
|
||||||
|
footerParts.push(`▶️ ${ctx.t(message, "responses.skip.upNext")}: ${nextTitle}`);
|
||||||
|
}
|
||||||
|
footerParts.push(ctx.t(message, "responses.skip.queueRemaining", { count: queueCount, plural: pluralStr }));
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: authorLabel })
|
||||||
|
.setTitle(ctx.t(message, "responses.skip.skippedAt", { time: elapsed }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: footerParts.join(" • ") });
|
||||||
|
|
||||||
|
if (skippedThumb) {
|
||||||
|
embed.setThumbnail(skippedThumb);
|
||||||
|
}
|
||||||
|
|
||||||
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -51,7 +84,10 @@ export async function run(message) {
|
|||||||
|
|
||||||
const current = p.queue.getCurrent();
|
const current = p.queue.getCurrent();
|
||||||
if (!p.connection || !current) {
|
if (!p.connection || !current) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses._common.nothingPlaying"));
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `⏭️ ${this.t(message, "responses.skip.skippedTitle")}` })
|
||||||
|
.setDescription(this.t(message, "responses._common.nothingPlaying"));
|
||||||
return message.reply({ embeds: [embed] });
|
return message.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,7 +117,8 @@ export async function run(message) {
|
|||||||
const needed = Math.floor(humanCount / 2) + 1;
|
const needed = Math.floor(humanCount / 2) + 1;
|
||||||
|
|
||||||
if (p._skipVotes.has(userId)) {
|
if (p._skipVotes.has(userId)) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
const embed = new EmbedBuilder().setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `🗳️ ${this.t(message, "responses.skip.skippedTitle")}` })
|
||||||
.setDescription(this.t(message, "responses.skip.alreadyVoted", { votes: p._skipVotes.size, needed }));
|
.setDescription(this.t(message, "responses.skip.alreadyVoted", { votes: p._skipVotes.size, needed }));
|
||||||
return message.reply({ embeds: [embed] }).catch(() => {});
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -93,7 +130,8 @@ export async function run(message) {
|
|||||||
return doSkip(this, message, p);
|
return doSkip(this, message, p);
|
||||||
}
|
}
|
||||||
|
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
const embed = new EmbedBuilder().setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `🗳️ ${this.t(message, "responses.skip.skippedTitle")}` })
|
||||||
.setDescription(this.t(message, "responses.skip.voteAdded", { votes: p._skipVotes.size, needed }));
|
.setDescription(this.t(message, "responses.skip.voteAdded", { votes: p._skipVotes.size, needed }));
|
||||||
message.reply({ embeds: [embed] }).catch(() => {});
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/skipto
|
||||||
|
* @description Skip directly to a specific track position in the queue.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
|
/** @type {CommandBuilder} @description Command definition for the skipto command. */
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("skipto")
|
||||||
|
.setDescription("Skip directly to a specific track in the queue.", "commands.skipto")
|
||||||
|
.addAliases("jump", "jumpto")
|
||||||
|
.setCategory("music")
|
||||||
|
.addNumberOption(opt =>
|
||||||
|
opt.setName("position")
|
||||||
|
.setDescription("The track number in the queue to jump to.", "options.skipto.position")
|
||||||
|
.setRequired(true)
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* Run handler for the skipto command.
|
||||||
|
* Skips all tracks prior to the target position and advances playback immediately.
|
||||||
|
* @param {object} message - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data containing the position option.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message, data) {
|
||||||
|
const p = await this.getPlayer(message, true, true, false);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
const queueSize = p.queue?.size() ?? 0;
|
||||||
|
if (queueSize === 0) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setDescription(this.t(message, "responses.skipto.emptyQueue"));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawPosition = data.get("position")?.value;
|
||||||
|
const position = parseInt(rawPosition, 10);
|
||||||
|
|
||||||
|
if (isNaN(position) || position < 1 || position > queueSize) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setDescription(this.t(message, "responses.skipto.invalidPosition", { max: queueSize }));
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Preview targeted track before splicing */
|
||||||
|
const targetTrack = p.queue.data[position - 1];
|
||||||
|
const skippedCount = position;
|
||||||
|
|
||||||
|
p.skipTo(position);
|
||||||
|
|
||||||
|
const titleDisplay = targetTrack?.title ? Utils.truncate(targetTrack.title, 50) : this.t(message, "responses.play.unknownTrack");
|
||||||
|
const trackLink = targetTrack?.spotifyUrl || targetTrack?.url || "";
|
||||||
|
const rawAuthor = targetTrack?.artist || (typeof targetTrack?.author === "object" ? targetTrack.author?.name : targetTrack?.author);
|
||||||
|
const remainingInQueue = Math.max(0, queueSize - position);
|
||||||
|
|
||||||
|
let desc = trackLink ? `**[${titleDisplay}](${trackLink})**` : `**${titleDisplay}**`;
|
||||||
|
if (rawAuthor) {
|
||||||
|
desc += `\n${this.t(message, "responses.play.byAuthor", { author: rawAuthor })}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `⏭️ ${this.t(message, "responses.skipto.author")}` })
|
||||||
|
.setTitle(this.t(message, "responses.skipto.title", { position, count: skippedCount }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(message, "responses.skipto.footer", { remaining: remainingInQueue }) });
|
||||||
|
|
||||||
|
if (targetTrack?.thumbnail) {
|
||||||
|
embed.setThumbnail(targetTrack.thumbnail);
|
||||||
|
}
|
||||||
|
|
||||||
|
return message.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/speed
|
||||||
|
* @description Adjust real-time playback speed (0.5× to 2.0×) using timescale DSP filters.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @type {CommandBuilder}
|
||||||
|
* @description Command definition for the speed command.
|
||||||
|
*/
|
||||||
|
export const command = new CommandBuilder()
|
||||||
|
.setName("speed")
|
||||||
|
.setDescription("Adjust the playback speed of the current track (0.5× to 2.0×).", "commands.speed")
|
||||||
|
.setCategory("music")
|
||||||
|
.addNumberOption(o =>
|
||||||
|
o.setName("rate")
|
||||||
|
.setDescription("Playback speed multiplier between 0.5 and 2.0 (e.g. 1.25). Omit to reset to 1.0×.", "options.speed.rate")
|
||||||
|
.setRequired(false)
|
||||||
|
)
|
||||||
|
.addAliases("rate", "tempo");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run handler for the speed command.
|
||||||
|
*
|
||||||
|
* @param {object} message - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function run(message, data) {
|
||||||
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
const current = p.queue?.getCurrent();
|
||||||
|
const rawRate = data.get("rate")?.value;
|
||||||
|
const prefix = this.handler?.getPrefix?.(message.message?.guildId ?? message.guild?.id) ?? "%";
|
||||||
|
const embed = new EmbedBuilder().setColor(0xe9196c);
|
||||||
|
|
||||||
|
if (rawRate === null || rawRate === undefined || isNaN(Number(rawRate))) {
|
||||||
|
const currentTimescale = p.activeFilterPayload?.timescale;
|
||||||
|
const currentSpeed = currentTimescale?.speed ?? 1.0;
|
||||||
|
if (currentSpeed !== 1.0) {
|
||||||
|
const existingPayload = { ...(p.activeFilterPayload || {}) };
|
||||||
|
delete existingPayload.timescale;
|
||||||
|
await p.applyFilter(existingPayload, Object.keys(existingPayload).length > 0 ? p.activeFilter : null);
|
||||||
|
embed.setAuthor({ name: `⏩ ${this.t(message, "responses.speed.speedTitle")}` })
|
||||||
|
.setTitle(this.t(message, "responses.speed.normalRate"))
|
||||||
|
.setDescription(this.t(message, "responses.speed.reset"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.speed.resetHint", { prefix }) });
|
||||||
|
} else {
|
||||||
|
embed.setAuthor({ name: `⏩ ${this.t(message, "responses.speed.speedTitle")}` })
|
||||||
|
.setTitle(this.t(message, "responses.speed.normalRate"))
|
||||||
|
.setDescription(this.t(message, "responses.speed.current", { speed: "1.0", prefix }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.speed.resetHint", { prefix }) });
|
||||||
|
}
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const speed = Utils.clamp(Number(rawRate), 0.5, 2.0);
|
||||||
|
|
||||||
|
const existingTimescale = p.activeFilterPayload?.timescale || {};
|
||||||
|
const newTimescale = {
|
||||||
|
...existingTimescale,
|
||||||
|
speed,
|
||||||
|
pitch: existingTimescale.pitch ?? 1.0,
|
||||||
|
rate: 1.0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
...(p.activeFilterPayload || {}),
|
||||||
|
timescale: newTimescale,
|
||||||
|
};
|
||||||
|
|
||||||
|
const filterMeta = {
|
||||||
|
key: `speed_${speed}`,
|
||||||
|
label: `${speed}× Speed`,
|
||||||
|
emoji: speed > 1 ? "⚡" : "🐢",
|
||||||
|
};
|
||||||
|
|
||||||
|
const res = await p.applyFilter(payload, filterMeta);
|
||||||
|
if (!res.ok) {
|
||||||
|
embed.setDescription(this.t(message, "responses.speed.failed", { reason: res.reason || "Unknown error" }));
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
let desc = this.t(message, "responses.speed.applied", { emoji: filterMeta.emoji, speed });
|
||||||
|
if (current?.title) {
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
const authorStr = rawAuthor ? ` • ${rawAuthor}` : "";
|
||||||
|
desc += `\n**${Utils.truncate(current.title, 45)}**${authorStr}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
embed.setAuthor({ name: `⏩ ${this.t(message, "responses.speed.speedTitle")}` })
|
||||||
|
.setTitle(this.t(message, "responses.speed.speedMultiplier", { speed }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(message, "responses.speed.resetHint", { prefix }) });
|
||||||
|
|
||||||
|
if (current?.thumbnail) embed.setThumbnail(current.thumbnail);
|
||||||
|
|
||||||
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
+155
-46
@@ -10,6 +10,8 @@ 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 { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { logger } from "../src/core/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
import * as ShardingUtils from "../src/utils/ShardingUtils.mjs";
|
||||||
|
import { TrackStats } from "../src/music/TrackStats.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
@@ -18,7 +20,7 @@ import { logger } from "../src/core/Logger.mjs";
|
|||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
.setName("stats")
|
.setName("stats")
|
||||||
.setDescription("Display stats about the bot like the uptime.", "commands.stats")
|
.setDescription("Display stats about the bot like the uptime.", "commands.stats")
|
||||||
.addAliases("info")
|
.addAliases("info", "botinfo", "about")
|
||||||
.setCategory("util");
|
.setCategory("util");
|
||||||
|
|
||||||
/** Cache is considered fresh for this long; older values trigger a background refresh. */
|
/** Cache is considered fresh for this long; older values trigger a background refresh. */
|
||||||
@@ -226,61 +228,110 @@ async function withRateLimitRetry(fn, label = "send") {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Count players with active voice connections.
|
* Gather real-time music playback and player statistics.
|
||||||
|
* Deduplicates active players by instance and computes connected, playing,
|
||||||
|
* total queued tracks, and 24/7 radio sessions.
|
||||||
* @private
|
* @private
|
||||||
* @param {Map} playerMap - The player map from PlayerManager.
|
* @param {Map} playerMap - The player map from PlayerManager.
|
||||||
* @returns {number} Number of live connected players.
|
* @returns {{totalPlayers: number, playingCount: number, queuedTracks: number, radios247: number}}
|
||||||
*/
|
*/
|
||||||
function getLivePlayerCount(playerMap) {
|
function getMusicStats(playerMap) {
|
||||||
let live = 0;
|
const uniquePlayers = new Set();
|
||||||
|
if (playerMap) {
|
||||||
for (const [mapKey, player] of playerMap ?? []) {
|
for (const player of playerMap.values()) {
|
||||||
if (!player || player._destroyed || player.leaving) continue;
|
if (!player || player._destroyed || player.leaving || player._isJoining) continue;
|
||||||
if (player._isJoining) continue;
|
const conn = player.connection;
|
||||||
|
if (conn) {
|
||||||
const conn = player.connection;
|
const room = conn.room;
|
||||||
if (conn) {
|
if (room) {
|
||||||
const room = conn.room;
|
const isConnected = room.isConnected;
|
||||||
if (room) {
|
const connectionState = room.connectionState;
|
||||||
const isConnected = room.isConnected;
|
if (!isConnected && (connectionState === 0 || connectionState === "disconnected")) continue;
|
||||||
const connectionState = room.connectionState;
|
}
|
||||||
if (!isConnected && (connectionState === 0 || connectionState === "disconnected")) continue;
|
} else {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
} else {
|
uniquePlayers.add(player);
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
live++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return live;
|
let totalPlayers = uniquePlayers.size;
|
||||||
|
let playingCount = 0;
|
||||||
|
let queuedTracks = 0;
|
||||||
|
let radios247 = 0;
|
||||||
|
|
||||||
|
for (const player of uniquePlayers) {
|
||||||
|
const cur = player.queue?.getCurrent?.();
|
||||||
|
const isPlaying = !!cur && !player.paused;
|
||||||
|
if (isPlaying) playingCount++;
|
||||||
|
|
||||||
|
const qSize = (player.queue?.size?.() ?? 0) + (cur ? 1 : 0);
|
||||||
|
queuedTracks += qSize;
|
||||||
|
|
||||||
|
if (player._is247Enabled?.()) {
|
||||||
|
radios247++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalPlayers,
|
||||||
|
playingCount,
|
||||||
|
queuedTracks,
|
||||||
|
radios247,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Translate with a hardcoded fallback. Locale lookups that miss (custom or
|
* Resolve the current shard assignment string (e.g. "0/2" when sharded, or "0" in single-process mode).
|
||||||
* outdated locale files make translate() return the raw dot-notation key)
|
* @private
|
||||||
|
* @param {object} client - The bot client instance.
|
||||||
|
* @param {string|null} guildId - The guild ID where the command was invoked.
|
||||||
|
* @returns {string} Formatted shard info.
|
||||||
|
*/
|
||||||
|
function getShardInfo(client, guildId) {
|
||||||
|
try {
|
||||||
|
const isSharded = ShardingUtils.isShardedProcess();
|
||||||
|
const currentShard = ShardingUtils.shardIdForGuild(client, guildId);
|
||||||
|
const totalShards = isSharded ? (Number(process.env.FLUXER_SHARD_COUNT) || 1) : 1;
|
||||||
|
return `${currentShard}/${totalShards}`;
|
||||||
|
} catch (_) {
|
||||||
|
return "0/1";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translate with a hardcoded fallback and optional placeholders. Locale lookups
|
||||||
|
* that miss (custom or outdated locale files make translate() return the raw dot-notation key)
|
||||||
* render the readable fallback instead of an ugly key path in the embed.
|
* render the readable fallback instead of an ugly key path in the embed.
|
||||||
* @private
|
* @private
|
||||||
* @param {Function} t - Translation function.
|
* @param {Function} t - Translation function.
|
||||||
* @param {object} msg - The command message wrapper.
|
* @param {object} msg - The command message wrapper.
|
||||||
* @param {string} key - Locale key.
|
* @param {string} key - Locale key.
|
||||||
* @param {string} fallback - Label used when the key is missing.
|
* @param {string} fallback - Label used when the key is missing.
|
||||||
|
* @param {object} [vars={}] - Optional interpolation variables.
|
||||||
* @returns {string}
|
* @returns {string}
|
||||||
*/
|
*/
|
||||||
function tOr(t, msg, key, fallback) {
|
function tOr(t, msg, key, fallback, vars = {}) {
|
||||||
const value = t(msg, key);
|
const value = t(msg, key, vars);
|
||||||
return value === key ? fallback : value;
|
return value === key ? fallback : value;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build the stats embed with all bot information.
|
* Build the stats embed with all bot information.
|
||||||
|
* Uses a clean multi-column grid layout (addFields) with category sections
|
||||||
|
* and a top-right bot avatar thumbnail.
|
||||||
* @private
|
* @private
|
||||||
* @param {Function} t - Translation function.
|
* @param {Function} t - Translation function.
|
||||||
* @param {object} msg - The command message wrapper.
|
* @param {object} msg - The command message wrapper.
|
||||||
* @param {object} s - Statistics data object.
|
* @param {object} s - Statistics data object.
|
||||||
* @param {number} s.guildCount - Number of guilds.
|
* @param {number} s.guildCount - Number of guilds.
|
||||||
* @param {number} s.userCount - Number of users.
|
* @param {number} s.userCount - Number of users.
|
||||||
* @param {number} s.playerCount - Number of active players.
|
* @param {number} s.playerCount - Number of active connected players.
|
||||||
|
* @param {number} s.playingCount - Number of players actively streaming.
|
||||||
|
* @param {number} s.queuedTracks - Total tracks across all player queues.
|
||||||
|
* @param {number} s.radios247 - Number of active 24/7 radio sessions.
|
||||||
|
* @param {string} s.shard - Shard assignment string.
|
||||||
|
* @param {string|null} [s.botIcon] - Bot avatar URL.
|
||||||
* @param {number} s.scrobbleCount - Total Last.fm scrobbles.
|
* @param {number} s.scrobbleCount - Total Last.fm scrobbles.
|
||||||
* @param {number} s.linkedUsers - Number of Last.fm linked users.
|
* @param {number} s.linkedUsers - Number of Last.fm linked users.
|
||||||
* @param {number} s.ping - Bot response ping in ms (REST reply round trip).
|
* @param {number} s.ping - Bot response ping in ms (REST reply round trip).
|
||||||
@@ -298,38 +349,75 @@ function buildEmbed(t, msg, s, pending = []) {
|
|||||||
const num = (v) => Utils.formatNumber(v);
|
const num = (v) => Utils.formatNumber(v);
|
||||||
const field = (key, value) => `\`${pending.includes(key) ? "..." : value}\``;
|
const field = (key, value) => `\`${pending.includes(key) ? "..." : value}\``;
|
||||||
|
|
||||||
const description = [
|
const playerVal = s.playingCount > 0
|
||||||
|
? tOr(t, msg, "responses.stats.playersWithPlaying", `${num(s.playerCount)} (${num(s.playingCount)} playing)`, {
|
||||||
|
total: num(s.playerCount),
|
||||||
|
playing: num(s.playingCount),
|
||||||
|
})
|
||||||
|
: num(s.playerCount);
|
||||||
|
|
||||||
|
const sections = [
|
||||||
|
`### ${tOr(t, msg, "responses.stats.categoryOverview", "📊 Overview")}`,
|
||||||
`${t(msg, "responses.stats.servers")} — ${field("guilds", num(s.guildCount))}`,
|
`${t(msg, "responses.stats.servers")} — ${field("guilds", num(s.guildCount))}`,
|
||||||
`${t(msg, "responses.stats.users")} — ${field("users", num(s.userCount))}`,
|
`${t(msg, "responses.stats.users")} — ${field("users", num(s.userCount))}`,
|
||||||
`${t(msg, "responses.stats.players")} — ${field("players", num(s.playerCount))}`,
|
`${tOr(t, msg, "responses.stats.shard", "🧩 **Shard**")} — \`${s.shard}\``,
|
||||||
|
``,
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const musicLines = [
|
||||||
|
`### ${tOr(t, msg, "responses.stats.categoryMusic", "🎧 Music Activity")}`,
|
||||||
|
`${t(msg, "responses.stats.players")} — ${field("players", playerVal)}`,
|
||||||
|
`${tOr(t, msg, "responses.stats.tracksPlayed", "▶️ **Tracks Played**")} — ${field("tracksPlayed", num(s.tracksPlayed))}`,
|
||||||
|
];
|
||||||
|
if (s.queuedTracks > 0) {
|
||||||
|
musicLines.push(`${tOr(t, msg, "responses.stats.queuedTracks", "🎶 **Queued Tracks**")} — ${field("queuedTracks", num(s.queuedTracks))}`);
|
||||||
|
}
|
||||||
|
if (s.radios247 > 0) {
|
||||||
|
musicLines.push(`${tOr(t, msg, "responses.stats.radios", "📻 **24/7 Radios**")} — ${field("radios", num(s.radios247))}`);
|
||||||
|
}
|
||||||
|
musicLines.push(``);
|
||||||
|
sections.push(...musicLines);
|
||||||
|
|
||||||
if (s.lastfmEnabled) {
|
if (s.lastfmEnabled) {
|
||||||
description.push(
|
sections.push(
|
||||||
`${t(msg, "responses.stats.scrobbles")} — ${field("scrobbles", num(s.scrobbleCount))}`,
|
`### ${tOr(t, msg, "responses.stats.categoryLastfm", "🎵 Last.fm")}`,
|
||||||
`${t(msg, "responses.stats.linkedUsers")} — ${field("linkedUsers", num(s.linkedUsers))}`,
|
`${t(msg, "responses.stats.scrobbles")} — ${field("scrobbles", num(s.scrobbleCount))}`,
|
||||||
|
`${t(msg, "responses.stats.linkedUsers")} — ${field("linkedUsers", num(s.linkedUsers))}`,
|
||||||
|
``,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
description.push(
|
const perfLines = [
|
||||||
`${t(msg, "responses.stats.ping")} — ${field("ping", `${num(s.ping)}ms`)}`,
|
`### ${tOr(t, msg, "responses.stats.categoryPerformance", "⚡ System & Network")}`,
|
||||||
s.gatewayPing >= 0 ? `${tOr(t, msg, "responses.stats.gateway", GATEWAY_FALLBACK_LABEL)} — \`${num(s.gatewayPing)}ms\`` : null,
|
`${t(msg, "responses.stats.ping")} — ${field("ping", `${num(s.ping)}ms`)}`,
|
||||||
`${t(msg, "responses.stats.uptime")} — \`${s.uptime}\``,
|
];
|
||||||
`${t(msg, "responses.stats.build")} — [\`${s.comHash}\`](${s.comLink})`,
|
if (s.gatewayPing >= 0) {
|
||||||
s.reason ? `${t(msg, "responses.stats.lastRestart")} — \`${s.reason}\`` : null,
|
perfLines.push(`${tOr(t, msg, "responses.stats.gateway", GATEWAY_FALLBACK_LABEL)} — \`${num(s.gatewayPing)}ms\``);
|
||||||
``,
|
}
|
||||||
t(msg, "responses.stats.supportKofi"),
|
perfLines.push(`${t(msg, "responses.stats.uptime")} — \`${s.uptime}\``, ``);
|
||||||
t(msg, "responses.stats.community"),
|
sections.push(...perfLines);
|
||||||
|
|
||||||
|
sections.push(
|
||||||
|
`${t(msg, "responses.stats.build")} — [\`${s.comHash}\`](${s.comLink})` +
|
||||||
|
(s.reason ? ` • ${t(msg, "responses.stats.lastRestart")} — \`${s.reason}\`` : ""),
|
||||||
|
`${t(msg, "responses.stats.supportKofi")} • ${t(msg, "responses.stats.community")}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
const desc = description.filter(l => l !== null).join("\n");
|
const authorOptions = { name: t(msg, "responses.stats.title") };
|
||||||
|
if (typeof s.botIcon === "string" && s.botIcon.startsWith("http")) {
|
||||||
|
authorOptions.iconURL = s.botIcon;
|
||||||
|
}
|
||||||
|
|
||||||
const builder = new EmbedBuilder()
|
const builder = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setAuthor({ name: t(msg, "responses.stats.title") })
|
.setAuthor(authorOptions)
|
||||||
.setDescription(desc)
|
.setDescription(sections.join("\n"))
|
||||||
.setFooter({ text: s.footer || t(msg, "responses.stats.title") });
|
.setFooter({ text: s.footer || t(msg, "responses.stats.title") });
|
||||||
|
|
||||||
|
if (typeof s.botIcon === "string" && s.botIcon.startsWith("http")) {
|
||||||
|
try { builder.setThumbnail(s.botIcon); } catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
@@ -349,6 +437,14 @@ export async function run(message) {
|
|||||||
const t = (...a) => this.t(...a);
|
const t = (...a) => this.t(...a);
|
||||||
|
|
||||||
const totals = getTotals(this.client);
|
const totals = getTotals(this.client);
|
||||||
|
const music = getMusicStats(this.players?.playerMap);
|
||||||
|
const shard = getShardInfo(this.client, message.guildId ?? message.guild?.id);
|
||||||
|
const tracksPlayed = await TrackStats.getTracksPlayed();
|
||||||
|
let botIcon = null;
|
||||||
|
try {
|
||||||
|
const raw = this.client?.user?.displayAvatarURL?.() || this.client?.user?.avatarURL?.();
|
||||||
|
if (typeof raw === "string" && raw.startsWith("http")) botIcon = raw;
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
scheduleBackgroundRefresh(this.client, lastfmEnabled ? lastfm : null);
|
scheduleBackgroundRefresh(this.client, lastfmEnabled ? lastfm : null);
|
||||||
|
|
||||||
@@ -363,7 +459,13 @@ export async function run(message) {
|
|||||||
const embedData = {
|
const embedData = {
|
||||||
guildCount: totals.guildCount,
|
guildCount: totals.guildCount,
|
||||||
userCount: totals.userCount,
|
userCount: totals.userCount,
|
||||||
playerCount: getLivePlayerCount(this.players.playerMap),
|
playerCount: music.totalPlayers,
|
||||||
|
playingCount: music.playingCount,
|
||||||
|
queuedTracks: music.queuedTracks,
|
||||||
|
radios247: music.radios247,
|
||||||
|
tracksPlayed,
|
||||||
|
shard,
|
||||||
|
botIcon,
|
||||||
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
|
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
|
||||||
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
||||||
lastfmEnabled,
|
lastfmEnabled,
|
||||||
@@ -405,11 +507,18 @@ export async function run(message) {
|
|||||||
persistCache();
|
persistCache();
|
||||||
}
|
}
|
||||||
|
|
||||||
const fresh = getTotals(this.client);
|
const fresh = getTotals(this.client);
|
||||||
|
const freshMusic = getMusicStats(this.players?.playerMap);
|
||||||
|
const freshTracks = await TrackStats.getTracksPlayed();
|
||||||
const fill = {
|
const fill = {
|
||||||
...embedData,
|
...embedData,
|
||||||
guildCount: fresh.guildCount,
|
guildCount: fresh.guildCount,
|
||||||
userCount: fresh.userCount,
|
userCount: fresh.userCount,
|
||||||
|
playerCount: freshMusic.totalPlayers,
|
||||||
|
playingCount: freshMusic.playingCount,
|
||||||
|
queuedTracks: freshMusic.queuedTracks,
|
||||||
|
radios247: freshMusic.radios247,
|
||||||
|
tracksPlayed: freshTracks,
|
||||||
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
|
scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0,
|
||||||
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
||||||
ping: lastPing ?? 0,
|
ping: lastPing ?? 0,
|
||||||
|
|||||||
@@ -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] });
|
||||||
|
}
|
||||||
+12
-5
@@ -21,12 +21,19 @@ export const command = new CommandBuilder()
|
|||||||
* @returns {void}
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
export function run(msg) {
|
export function run(msg) {
|
||||||
|
const botUser = this.client?.user;
|
||||||
|
const botIcon = botUser?.displayAvatarURL?.() || null;
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(this.t(msg, "responses.support.title"))
|
.setAuthor({
|
||||||
.setDescription(
|
name: this.t(msg, "responses.support.title"),
|
||||||
this.t(msg, "responses.support.description")
|
iconURL: botIcon
|
||||||
)
|
})
|
||||||
;
|
.setTitle("Remix HQ (fluxer.gg/remix)")
|
||||||
|
.setDescription(this.t(msg, "responses.support.description"))
|
||||||
|
.setFooter({ text: "fluxer.gg/remix" });
|
||||||
|
|
||||||
|
if (botIcon) embed.setThumbnail(botIcon);
|
||||||
msg.reply({ embeds: [embed] }).catch(() => {});
|
msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+11
-3
@@ -26,7 +26,10 @@ export const command = new CommandBuilder()
|
|||||||
export async function run(msg, data) {
|
export async function run(msg, data) {
|
||||||
const guild = msg.channel?.channel?.guild ?? msg.message?.guild;
|
const guild = msg.channel?.channel?.guild ?? msg.message?.guild;
|
||||||
if (!guild) {
|
if (!guild) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.test.notInServer"));
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.test.author") })
|
||||||
|
.setDescription(this.t(msg, "responses.test.notInServer"));
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +57,11 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (channelCounts.size === 0) {
|
if (channelCounts.size === 0) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.test.noOneInVoice"));
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.test.author") })
|
||||||
|
.setDescription(this.t(msg, "responses.test.noOneInVoice"))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.test.footerZero") });
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,8 +100,9 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.test.author") })
|
||||||
.setTitle(this.t(msg, "responses.test.title"))
|
.setTitle(this.t(msg, "responses.test.title"))
|
||||||
.setDescription(desc.trim().slice(0, 4096))
|
.setDescription(desc.trim().slice(0, 4096))
|
||||||
;
|
.setFooter({ text: this.t(msg, "responses.test.footerCount", { count: channelCounts.size }) });
|
||||||
msg.reply({ embeds: [embed] }).catch(() => {});
|
msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+33
-5
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
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 { getGlobalColor } from "../src/ui/index.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the thumbnail command. */
|
/** @type {CommandBuilder} @description Command definition for the thumbnail command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -24,12 +24,40 @@ export const command = new CommandBuilder()
|
|||||||
export async function run(msg) {
|
export async function run(msg) {
|
||||||
const p = await this.getPlayer(msg);
|
const p = await this.getPlayer(msg);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const data = await p.getThumbnail();
|
|
||||||
|
const current = p.queue?.getCurrent();
|
||||||
|
if (!current) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `🖼️ ${this.t(msg, "responses.thumbnail.thumbTitle")}` })
|
||||||
|
.setDescription(this.t(msg, "responses._common.nothingPlaying"));
|
||||||
|
return msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!current.thumbnail) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `🖼️ ${this.t(msg, "responses.thumbnail.thumbTitle")}` })
|
||||||
|
.setDescription(this.t(msg, "responses.thumbnail.noArtwork"));
|
||||||
|
return msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const trackUrl = current.spotifyUrl || current.url || null;
|
||||||
|
const rawAuthor = current.artist || (typeof current.author === "object" ? current.author?.name : current.author);
|
||||||
|
const titleDisplay = Utils.truncate(current.title || this.t(msg, "responses.play.unknownTrack"), 50);
|
||||||
|
|
||||||
|
let desc = trackUrl ? `**[${titleDisplay}](${trackUrl})**` : `**${titleDisplay}**`;
|
||||||
|
if (rawAuthor) {
|
||||||
|
desc += `\n${this.t(msg, "responses.play.byAuthor", { author: rawAuthor })}`;
|
||||||
|
}
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(0xe9196c)
|
||||||
.setDescription(data.msg);
|
.setAuthor({ name: `🖼️ ${this.t(msg, "responses.thumbnail.thumbTitle")}` })
|
||||||
if (data.image) embed.setImage(data.image);
|
.setTitle(this.t(msg, "responses.thumbnail.highRes"))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setImage(current.thumbnail)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.thumbnail.expandHint") });
|
||||||
|
|
||||||
msg.reply({ embeds: [embed] }).catch(() => {});
|
msg.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
+107
-19
@@ -60,6 +60,30 @@ export const command = new CommandBuilder()
|
|||||||
)
|
)
|
||||||
.addAlias("to");
|
.addAlias("to");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Build a text-based ASCII timeline representation of the cut window.
|
||||||
|
* @param {number} startMs - Start time in milliseconds.
|
||||||
|
* @param {number} endMs - End time in milliseconds.
|
||||||
|
* @param {number} totalMs - Total track duration in milliseconds.
|
||||||
|
* @returns {string} Formatted timeline string.
|
||||||
|
*/
|
||||||
|
function buildTimelineBar(startMs, endMs, totalMs) {
|
||||||
|
if (!totalMs || totalMs <= 0) return `\`${Utils.prettifyMS(startMs)}\` ➔ \`${endMs > 0 ? Utils.prettifyMS(endMs) : "end"}\``;
|
||||||
|
const totalSlots = 18;
|
||||||
|
const startSlot = Math.min(totalSlots - 1, Math.floor((startMs / totalMs) * totalSlots));
|
||||||
|
const effectiveEnd = endMs > 0 ? endMs : totalMs;
|
||||||
|
const endSlot = Math.min(totalSlots, Math.max(startSlot + 1, Math.ceil((effectiveEnd / totalMs) * totalSlots)));
|
||||||
|
|
||||||
|
let bar = "";
|
||||||
|
for (let i = 0; i < totalSlots; i++) {
|
||||||
|
if (i < startSlot) bar += "─";
|
||||||
|
else if (i >= startSlot && i < endSlot) bar += "■";
|
||||||
|
else bar += "─";
|
||||||
|
}
|
||||||
|
return `\`${Utils.prettifyMS(startMs)}\` \`[${bar}]\` \`${Utils.prettifyMS(effectiveEnd)}\``;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @private
|
* @private
|
||||||
* Extract an alias:name token from a parts array, mutating the array in place.
|
* Extract an alias:name token from a parts array, mutating the array in place.
|
||||||
@@ -157,14 +181,30 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const endLabel = endMs > 0 ? Utils.prettifyMS(endMs) : "full track";
|
const endLabel = endMs > 0 ? Utils.prettifyMS(endMs) : "full track";
|
||||||
let desc;
|
const timeline = buildTimelineBar(startMs, endMs, trackDuration);
|
||||||
if (result.alias === DEFAULT_ALIAS) {
|
const setEmbed = new EmbedBuilder()
|
||||||
desc = this.t(msg, "responses.trackopt.saved", { title: current.title, aliasLabel: "", start: Utils.prettifyMS(startMs), end: endLabel });
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.trackopt.savedAuthor") })
|
||||||
|
.setTitle(current.title?.slice(0, 256) || "Track Trim")
|
||||||
|
.setDescription(
|
||||||
|
result.alias === DEFAULT_ALIAS
|
||||||
|
? this.t(msg, "responses.trackopt.saved", { title: current.title, aliasLabel: "", start: Utils.prettifyMS(startMs), end: endLabel })
|
||||||
|
: this.t(msg, "responses.trackopt.savedAlias", { title: current.title, alias: result.alias, start: Utils.prettifyMS(startMs), end: endLabel, prefix })
|
||||||
|
)
|
||||||
|
.addFields(
|
||||||
|
{ name: this.t(msg, "responses.trackopt.playbackWindowField"), value: timeline, inline: false },
|
||||||
|
{ name: this.t(msg, "responses.trackopt.aliasField"), value: `\`${result.alias}\``, inline: true },
|
||||||
|
{ name: this.t(msg, "responses.trackopt.activeTrimField"), value: `${Utils.prettifyMS(startMs)} ➔ ${endLabel}`, inline: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
if (current.thumbnail) setEmbed.setThumbnail(current.thumbnail);
|
||||||
|
if (result.alias !== DEFAULT_ALIAS) {
|
||||||
|
setEmbed.setFooter({ text: this.t(msg, "responses.trackopt.playHintFooter", { prefix, alias: result.alias }) });
|
||||||
} else {
|
} else {
|
||||||
desc = this.t(msg, "responses.trackopt.savedAlias", { title: current.title, alias: result.alias, start: Utils.prettifyMS(startMs), end: endLabel, prefix });
|
setEmbed.setFooter({ text: this.t(msg, "responses.trackopt.autoApplyFooter", { prefix }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
|
return msg.reply({ embeds: [setEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (subCommand === "get") {
|
if (subCommand === "get") {
|
||||||
@@ -173,15 +213,27 @@ export async function run(msg, data) {
|
|||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notSet", { title: current.title }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notSet", { title: current.title }))] });
|
||||||
}
|
}
|
||||||
|
|
||||||
let desc = this.t(msg, "responses.trackopt.current", { title: current.title, count: rows.length }) + "\n\n";
|
const trackDuration = p._getTrackDurationMs(current);
|
||||||
for (const row of rows) {
|
const getEmbed = new EmbedBuilder()
|
||||||
const aliasLabel = row.alias === DEFAULT_ALIAS ? "default" : row.alias;
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.trackopt.savedListAuthor") })
|
||||||
|
.setTitle(current.title?.slice(0, 256) || "Track Trims")
|
||||||
|
.setFooter({ text: this.t(msg, "responses.trackopt.trimProfilesFooter", { count: rows.length, plural: rows.length === 1 ? "" : "s", prefix }) });
|
||||||
|
|
||||||
|
if (current.thumbnail) getEmbed.setThumbnail(current.thumbnail);
|
||||||
|
|
||||||
|
for (const row of rows.slice(0, 10)) {
|
||||||
|
const aliasLabel = row.alias === DEFAULT_ALIAS ? "default (auto-apply)" : row.alias;
|
||||||
const endStr = row.end_ms > 0 ? Utils.prettifyMS(row.end_ms) : "end";
|
const endStr = row.end_ms > 0 ? Utils.prettifyMS(row.end_ms) : "end";
|
||||||
const autoTag = row.alias === DEFAULT_ALIAS ? " ← auto" : "";
|
const timeline = buildTimelineBar(row.start_ms, row.end_ms, trackDuration);
|
||||||
desc += this.t(msg, "responses.trackopt.currentEntry", { alias: aliasLabel, start: Utils.prettifyMS(row.start_ms), end: endStr, autoTag }) + "\n";
|
getEmbed.addFields({
|
||||||
|
name: `🏷️ ${aliasLabel}`,
|
||||||
|
value: `${timeline}\n${Utils.prettifyMS(row.start_ms)} ➔ ${endStr}`,
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
|
return msg.reply({ embeds: [getEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (subCommand === "play") {
|
if (subCommand === "play") {
|
||||||
@@ -217,7 +269,20 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
const aliasLabel = safeAlias === DEFAULT_ALIAS ? "default" : safeAlias;
|
const aliasLabel = safeAlias === DEFAULT_ALIAS ? "default" : safeAlias;
|
||||||
const endStr = result.endMs > 0 ? Utils.prettifyMS(result.endMs) : "end";
|
const endStr = result.endMs > 0 ? Utils.prettifyMS(result.endMs) : "end";
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.applied", { alias: aliasLabel, start: Utils.prettifyMS(result.startMs), end: endStr }))] });
|
const trackDuration = p._getTrackDurationMs(current);
|
||||||
|
const timeline = buildTimelineBar(result.startMs, result.endMs, trackDuration);
|
||||||
|
|
||||||
|
const playEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.trackopt.appliedAuthor") })
|
||||||
|
.setTitle(current.title?.slice(0, 256) || "Track Trim")
|
||||||
|
.setDescription(this.t(msg, "responses.trackopt.applied", { alias: aliasLabel, start: Utils.prettifyMS(result.startMs), end: endStr }))
|
||||||
|
.addFields({ name: this.t(msg, "responses.trackopt.activeCutRangeField"), value: timeline, inline: false })
|
||||||
|
.setFooter({ text: this.t(msg, "responses.trackopt.playFooterHint", { prefix }) });
|
||||||
|
|
||||||
|
if (current.thumbnail) playEmbed.setThumbnail(current.thumbnail);
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [playEmbed] });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: e.message }))] });
|
return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: e.message }))] });
|
||||||
}
|
}
|
||||||
@@ -240,19 +305,35 @@ export async function run(msg, data) {
|
|||||||
p._clearTrackEndTimer();
|
p._clearTrackEndTimer();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (aliasRaw) {
|
const removeDesc = aliasRaw
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.removedAlias", { alias: aliasRaw, title: current.title }))] });
|
? this.t(msg, "responses.trackopt.removedAlias", { alias: aliasRaw, title: current.title })
|
||||||
}
|
: this.t(msg, "responses.trackopt.removedAll", { title: current.title });
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.removedAll", { title: current.title }))] });
|
|
||||||
|
const removeEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.trackopt.removeAuthor") })
|
||||||
|
.setTitle(current.title?.slice(0, 256) || "Track Trim")
|
||||||
|
.setDescription(removeDesc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.trackopt.removeFooter", { prefix }) });
|
||||||
|
|
||||||
|
if (current.thumbnail) removeEmbed.setThumbnail(current.thumbnail);
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [removeEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (subCommand === "list") {
|
if (subCommand === "list") {
|
||||||
const rows = await trackOpts.list(userId);
|
const rows = await trackOpts.list(userId);
|
||||||
if (!rows || rows.length === 0) {
|
if (!rows || rows.length === 0) {
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.listEmpty", { prefix }))] });
|
const emptyEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.trackopt.listAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.trackopt.listTitleClean", { count: 0 }))
|
||||||
|
.setDescription(this.t(msg, "responses.trackopt.listEmpty", { prefix }))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.trackopt.listFooterHint", { prefix }) });
|
||||||
|
return msg.reply({ embeds: [emptyEmbed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
let desc = this.t(msg, "responses.trackopt.listTitle", { count: rows.length }) + "\n\n";
|
let desc = "";
|
||||||
let lastTrack = "";
|
let lastTrack = "";
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
const title = row.track_title || row.track_identifier;
|
const title = row.track_title || row.track_identifier;
|
||||||
@@ -268,6 +349,13 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
desc += "\n" + this.t(msg, "responses.trackopt.listHint", { prefix });
|
desc += "\n" + this.t(msg, "responses.trackopt.listHint", { prefix });
|
||||||
|
|
||||||
return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
|
const listEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.trackopt.listAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.trackopt.listTitleClean", { count: rows.length }))
|
||||||
|
.setDescription(desc.trim())
|
||||||
|
.setFooter({ text: this.t(msg, "responses.trackopt.listFooterHint", { prefix }) });
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [listEmbed] });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+36
-13
@@ -5,9 +5,7 @@
|
|||||||
|
|
||||||
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 { getGlobalColor } from "../src/ui/index.mjs";
|
import { MAX_VOLUME, ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||||
import { MAX_VOLUME } from "../src/utils/UI.mjs";
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
@@ -38,21 +36,46 @@ export async function run(message, data) {
|
|||||||
|
|
||||||
const volOption = data.get("volume");
|
const volOption = data.get("volume");
|
||||||
const raw = volOption?.value;
|
const raw = volOption?.value;
|
||||||
|
const prefix = this.handler.getPrefix(message.message?.guildId ?? message.channel?.guildId) || "%";
|
||||||
|
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor());
|
const makeVolumeBar = (pct) => {
|
||||||
|
const bars = Math.min(15, Math.max(0, Math.round(pct / 10)));
|
||||||
|
return "█".repeat(bars) + "░".repeat(15 - bars);
|
||||||
|
};
|
||||||
|
|
||||||
if (!volOption || raw === null || raw === undefined || isNaN(Number(raw))) {
|
if (!volOption || raw === null || raw === undefined || isNaN(Number(raw))) {
|
||||||
const current = Math.round((p.preferredVolume ?? 1) * 100);
|
const current = Math.round((p.preferredVolume ?? 1) * 100);
|
||||||
embed.setDescription(this.t(message, "responses.volume.current", { volume: current }));
|
const bar = makeVolumeBar(current);
|
||||||
} else {
|
|
||||||
const pct = Number(raw);
|
const embed = new EmbedBuilder()
|
||||||
if (pct < 0 || pct > MAX_VOLUME) {
|
.setColor(0xe9196c)
|
||||||
embed.setDescription(this.t(message, "responses.volume.outOfRange", { max: MAX_VOLUME }));
|
.setAuthor({ name: `🔊 ${this.t(message, "responses.volume.currentVolume")}` })
|
||||||
} else {
|
.setTitle(`\`${current}%\``)
|
||||||
p.setVolume(pct / 100);
|
.setDescription(`\`0%\` ${bar} \`${MAX_VOLUME}%\`\n\n${this.t(message, "responses.volume.current", { volume: current })}`)
|
||||||
embed.setDescription(this.t(message, "responses.volume.changed", { volume: pct }));
|
.setFooter({ text: this.t(message, "responses.volume.volumeHint", { prefix }) });
|
||||||
}
|
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pct = Number(raw);
|
||||||
|
if (pct < 0 || pct > MAX_VOLUME) {
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(ERROR_COLOR)
|
||||||
|
.setAuthor({ name: `🔊 ${this.t(message, "responses.volume.volumeAdjusted")}` })
|
||||||
|
.setDescription(this.t(message, "responses.volume.outOfRange", { max: MAX_VOLUME }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.volume.volumeHint", { prefix }) });
|
||||||
|
return message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
p.setVolume(pct / 100);
|
||||||
|
const bar = makeVolumeBar(pct);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(0xe9196c)
|
||||||
|
.setAuthor({ name: `🔊 ${this.t(message, "responses.volume.volumeAdjusted")}` })
|
||||||
|
.setTitle(`\`${pct}%\``)
|
||||||
|
.setDescription(`\`0%\` ${bar} \`${MAX_VOLUME}%\`\n\n${this.t(message, "responses.volume.changed", { volume: pct })}`)
|
||||||
|
.setFooter({ text: this.t(message, "responses.volume.volumeHint", { prefix }) });
|
||||||
|
|
||||||
message.reply({ embeds: [embed] }).catch(() => {});
|
message.reply({ embeds: [embed] }).catch(() => {});
|
||||||
}
|
}
|
||||||
+43
-10
@@ -7,7 +7,24 @@ 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 { PermissionFlags } from "@fluxerjs/core";
|
import { PermissionFlags } from "@fluxerjs/core";
|
||||||
import { MAX_VOLUME } from "../src/utils/UI.mjs";
|
import { MAX_VOLUME, ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Build an ASCII slider bar for volume display.
|
||||||
|
* @param {number} volume
|
||||||
|
* @param {number} max
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function buildVolumeSlider(volume, max = MAX_VOLUME) {
|
||||||
|
const totalSlots = 14;
|
||||||
|
const filled = Math.min(totalSlots, Math.max(0, Math.round((volume / max) * totalSlots)));
|
||||||
|
let bar = "";
|
||||||
|
for (let i = 0; i < totalSlots; i++) {
|
||||||
|
bar += i < filled ? "■" : "─";
|
||||||
|
}
|
||||||
|
return `\`0%\` \`[${bar}]\` \`${max}%\` • **${volume}%**`;
|
||||||
|
}
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the volumedefault command. */
|
/** @type {CommandBuilder} @description Command definition for the volumedefault command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -47,30 +64,46 @@ export async function run(message, data) {
|
|||||||
const raw = volOption?.value;
|
const raw = volOption?.value;
|
||||||
|
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor());
|
const embed = new EmbedBuilder().setColor(getGlobalColor());
|
||||||
|
const pfx = this.handler.getPrefix(message.channel?.guildId ?? message.message?.guildId);
|
||||||
|
|
||||||
if (!volOption || raw === null || raw === undefined || isNaN(Number(raw))) {
|
if (!volOption || raw === null || raw === undefined || isNaN(Number(raw))) {
|
||||||
const currentDefault = set?.get("volume") ?? 100;
|
const currentDefault = set?.get("volume") ?? 100;
|
||||||
const currentPlayerVol = Math.round((p.preferredVolume ?? 1) * 100);
|
const currentPlayerVol = Math.round((p.preferredVolume ?? 1) * 100);
|
||||||
const pfx = this.handler.getPrefix(message.channel?.guildId ?? message.message?.guildId);
|
|
||||||
embed
|
embed
|
||||||
|
.setAuthor({ name: this.t(message, "responses.volumedefault.author") })
|
||||||
.setTitle(this.t(message, "responses.volumedefault.title"))
|
.setTitle(this.t(message, "responses.volumedefault.title"))
|
||||||
.setDescription(
|
.setDescription(
|
||||||
this.t(message, "responses.volumedefault.serverDefault", { volume: currentDefault }) + "\n" +
|
hasManage
|
||||||
this.t(message, "responses.volumedefault.currentVolume", { volume: currentPlayerVol }) + "\n\n" +
|
|
||||||
(hasManage
|
|
||||||
? this.t(message, "responses.volumedefault.changeHint", { prefix: pfx, max: MAX_VOLUME })
|
? this.t(message, "responses.volumedefault.changeHint", { prefix: pfx, max: MAX_VOLUME })
|
||||||
: this.t(message, "responses.volumedefault.noPermission"))
|
: this.t(message, "responses.volumedefault.noPermission")
|
||||||
);
|
)
|
||||||
|
.addFields(
|
||||||
|
{ name: this.t(message, "responses.volumedefault.fieldDefault"), value: buildVolumeSlider(currentDefault), inline: false },
|
||||||
|
{ name: this.t(message, "responses.volumedefault.fieldActive"), value: `${currentPlayerVol}%`, inline: true }
|
||||||
|
)
|
||||||
|
.setFooter({ text: this.t(message, "responses.volumedefault.footerHint", { prefix: pfx, max: MAX_VOLUME }) });
|
||||||
} else if (!hasManage) {
|
} else if (!hasManage) {
|
||||||
embed.setDescription(this.t(message, "responses.volumedefault.noPermissionSet"));
|
embed
|
||||||
|
.setColor(ERROR_COLOR)
|
||||||
|
.setAuthor({ name: this.t(message, "responses.volumedefault.author") })
|
||||||
|
.setDescription(this.t(message, "responses.volumedefault.noPermissionSet"))
|
||||||
|
.setFooter({ text: this.t(message, "responses.volumedefault.footerHint", { prefix: pfx, max: MAX_VOLUME }) });
|
||||||
} else {
|
} else {
|
||||||
const pct = Number(raw);
|
const pct = Number(raw);
|
||||||
if (pct < 0 || pct > MAX_VOLUME) {
|
if (pct < 0 || pct > MAX_VOLUME) {
|
||||||
embed.setDescription(this.t(message, "responses.volumedefault.outOfRange", { max: MAX_VOLUME }));
|
embed
|
||||||
|
.setColor(ERROR_COLOR)
|
||||||
|
.setAuthor({ name: this.t(message, "responses.volumedefault.author") })
|
||||||
|
.setDescription(this.t(message, "responses.volumedefault.outOfRange", { max: MAX_VOLUME }))
|
||||||
|
.setFooter({ text: this.t(message, "responses.volumedefault.footerHint", { prefix: pfx, max: MAX_VOLUME }) });
|
||||||
} else {
|
} else {
|
||||||
p.setVolume(pct / 100);
|
p.setVolume(pct / 100);
|
||||||
if (set) set.set("volume", pct);
|
if (set) set.set("volume", pct);
|
||||||
embed.setDescription(this.t(message, "responses.volumedefault.saved", { volume: pct }));
|
embed
|
||||||
|
.setAuthor({ name: this.t(message, "responses.volumedefault.authorSaved") })
|
||||||
|
.setDescription(this.t(message, "responses.volumedefault.saved", { volume: pct }))
|
||||||
|
.addFields({ name: this.t(message, "responses.volumedefault.fieldNewDefault"), value: buildVolumeSlider(pct), inline: false })
|
||||||
|
.setFooter({ text: this.t(message, "responses.volumedefault.footerHint", { prefix: pfx, max: MAX_VOLUME }) });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+37
-15
@@ -51,7 +51,10 @@ function notConfigured(t, guildId) {
|
|||||||
return {
|
return {
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(ERROR_COLOR)
|
.setColor(ERROR_COLOR)
|
||||||
.setDescription(t(guildId, "responses.vote.notConfigured"))]
|
.setAuthor({ name: t(guildId, "responses.vote.voteAuthor") })
|
||||||
|
.setTitle(t(guildId, "responses.vote.notConfiguredTitle"))
|
||||||
|
.setDescription(t(guildId, "responses.vote.notConfigured"))
|
||||||
|
.setFooter({ text: t(guildId, "responses.vote.voteFooterHint", { prefix: "%" }) })]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,7 +71,10 @@ function noResourceId(type, prefix, t, guildId) {
|
|||||||
return {
|
return {
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(ERROR_COLOR)
|
.setColor(ERROR_COLOR)
|
||||||
.setDescription(t(guildId, "responses.vote.noResourceId", { type, prefix }))]
|
.setAuthor({ name: t(guildId, "responses.vote.voteAuthor") })
|
||||||
|
.setTitle(t(guildId, "responses.vote.noResourceIdTitle"))
|
||||||
|
.setDescription(t(guildId, "responses.vote.noResourceId", { type, prefix }))
|
||||||
|
.setFooter({ text: t(guildId, "responses.vote.voteFooterHint", { prefix }) })]
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -112,6 +118,7 @@ function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: t(guildId, "responses.vote.voteVotersAuthor") })
|
||||||
.setTitle(`${title}`)
|
.setTitle(`${title}`)
|
||||||
.setDescription(desc)
|
.setDescription(desc)
|
||||||
.setFooter({ text: footerText });
|
.setFooter({ text: footerText });
|
||||||
@@ -146,8 +153,10 @@ export async function run(msg, data) {
|
|||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.vote.voteAuthor") })
|
||||||
.setTitle(this.t(msg, "responses.vote.infoTitle"))
|
.setTitle(this.t(msg, "responses.vote.infoTitle"))
|
||||||
.setDescription(this.t(msg, "responses.vote.infoDescription", { siteUrl: FLUXERLIST.SITE_URL, prefix }))]
|
.setDescription(this.t(msg, "responses.vote.infoDescription", { siteUrl: FLUXERLIST.SITE_URL, prefix }))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.vote.voteFooterHint", { prefix }) })]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,8 +178,10 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
const embed = new EmbedBuilder()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.vote.voteAuthor") })
|
||||||
.setTitle(this.t(msg, "responses.vote.voteTitle"))
|
.setTitle(this.t(msg, "responses.vote.voteTitle"))
|
||||||
.setDescription(descLines.join("\n"));
|
.setDescription(descLines.join("\n"))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.vote.voteFooterHint", { prefix }) });
|
||||||
|
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
@@ -190,16 +201,21 @@ export async function run(msg, data) {
|
|||||||
const resolvedType = type || "bot";
|
const resolvedType = type || "bot";
|
||||||
const voted = await fluxerlist.hasVoted(userId);
|
const voted = await fluxerlist.hasVoted(userId);
|
||||||
|
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor());
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.vote.voteCheckAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.vote.voteCheckTitle"));
|
||||||
|
|
||||||
if (voted === null) {
|
if (voted === null) {
|
||||||
embed.setDescription(this.t(msg, "responses.vote.checkUnknown"));
|
embed.setDescription(this.t(msg, "responses.vote.checkUnknown"));
|
||||||
} else if (voted) {
|
} else if (voted) {
|
||||||
embed.setDescription(this.t(msg, "responses.vote.checkYes", { type: resolvedType }));
|
embed.setDescription(this.t(msg, "responses.vote.voteCheckYesDesc", { type: resolvedType }));
|
||||||
} else {
|
} else {
|
||||||
const slug = resourceId || (resolvedType === "server" ? fluxerlist.serverSlug : fluxerlist.botSlug);
|
const slug = resourceId || (resolvedType === "server" ? fluxerlist.serverSlug : fluxerlist.botSlug);
|
||||||
const voteUrl = slug ? buildVoteLink(resolvedType, slug) : FLUXERLIST.SITE_URL;
|
const voteUrl = slug ? buildVoteLink(resolvedType, slug) : FLUXERLIST.SITE_URL;
|
||||||
embed.setDescription(this.t(msg, "responses.vote.checkNo", { type: resolvedType, url: voteUrl }));
|
embed.setDescription(this.t(msg, "responses.vote.voteCheckNoDesc", { type: resolvedType, url: voteUrl }));
|
||||||
}
|
}
|
||||||
|
embed.setFooter({ text: this.t(msg, "responses.vote.voteCheckFooter", { prefix }) });
|
||||||
return msg.reply({ embeds: [embed] });
|
return msg.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,7 +242,10 @@ export async function run(msg, data) {
|
|||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setDescription(this.t(msg, "responses.vote.noVotersYet", { type: resolvedType }))]
|
.setAuthor({ name: this.t(msg, "responses.vote.voteVotersAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.vote.noVotersTitle"))
|
||||||
|
.setDescription(this.t(msg, "responses.vote.noVotersYet", { type: resolvedType }))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.vote.voteFooterHint", { prefix }) })]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,7 +273,7 @@ export async function run(msg, data) {
|
|||||||
const replyMsg = await msg.reply(buildPage(currentPage, voterData));
|
const replyMsg = await msg.reply(buildPage(currentPage, voterData));
|
||||||
if (!replyMsg?.message) return;
|
if (!replyMsg?.message) return;
|
||||||
|
|
||||||
const navEmojis = ["\u25C0\uFE0F", "\u25B6\uFE0F", "\u274C"];
|
const navEmojis = ["◀️", "▶️", "❌"];
|
||||||
for (const emoji of navEmojis) {
|
for (const emoji of navEmojis) {
|
||||||
await replyMsg.message.react(emoji).catch(() => {});
|
await replyMsg.message.react(emoji).catch(() => {});
|
||||||
}
|
}
|
||||||
@@ -290,7 +309,7 @@ export async function run(msg, data) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||||
if (e.emoji_id === "\u274C") {
|
if (e.emoji_id === "❌") {
|
||||||
clearTimeout(emojiTimeout);
|
clearTimeout(emojiTimeout);
|
||||||
unobserve?.();
|
unobserve?.();
|
||||||
await replyMsg.message.delete().catch(() => {});
|
await replyMsg.message.delete().catch(() => {});
|
||||||
@@ -299,9 +318,9 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
resetTimer();
|
resetTimer();
|
||||||
|
|
||||||
if (e.emoji_id === "\u25C0\uFE0F") {
|
if (e.emoji_id === "◀️") {
|
||||||
currentPage = currentPage > 1 ? currentPage - 1 : totalPages;
|
currentPage = currentPage > 1 ? currentPage - 1 : totalPages;
|
||||||
} else if (e.emoji_id === "\u25B6\uFE0F") {
|
} else if (e.emoji_id === "▶️") {
|
||||||
currentPage = currentPage < totalPages ? currentPage + 1 : 1;
|
currentPage = currentPage < totalPages ? currentPage + 1 : 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,14 +342,17 @@ export async function run(msg, data) {
|
|||||||
return msg.reply({
|
return msg.reply({
|
||||||
embeds: [new EmbedBuilder()
|
embeds: [new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.vote.voteAuthor") })
|
||||||
|
.setTitle(this.t(msg, "responses.vote.defaultTitle"))
|
||||||
.setDescription([
|
.setDescription([
|
||||||
this.t(msg, "responses.vote.defaultCommandsTitle"),
|
this.t(msg, "responses.vote.defaultCommandsTitle"),
|
||||||
``,
|
"",
|
||||||
this.t(msg, "responses.vote.defaultCommandsList", { prefix }),
|
this.t(msg, "responses.vote.defaultCommandsList", { prefix }),
|
||||||
``,
|
"",
|
||||||
this.t(msg, "responses.vote.optionsTitle"),
|
this.t(msg, "responses.vote.optionsTitle"),
|
||||||
this.t(msg, "responses.vote.optionsList", { prefix }),
|
this.t(msg, "responses.vote.optionsList", { prefix }),
|
||||||
].join("\n"))]
|
].join("\n"))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.vote.voteFooterHint", { prefix }) })]
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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] });
|
||||||
|
}
|
||||||
+22
-8
@@ -1,9 +1,11 @@
|
|||||||
{
|
{
|
||||||
"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-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
|
||||||
}
|
}
|
||||||
@@ -18,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.",
|
||||||
@@ -55,14 +66,8 @@
|
|||||||
"requestTimeout": 60000,
|
"requestTimeout": 60000,
|
||||||
"Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors. All audio sources (Spotify, Deezer, Apple Music, etc.) are resolved by NodeLink, so configure source credentials in nodelink.config.json, not here."
|
"Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors. All audio sources (Spotify, Deezer, Apple Music, etc.) are resolved by NodeLink, so configure source credentials in nodelink.config.json, not here."
|
||||||
},
|
},
|
||||||
"restore": {
|
|
||||||
"maxAgeHours": 12,
|
|
||||||
"Comment": "After a restart the bot resumes the players it saved in MySQL. Snapshots whose last heartbeat is older than maxAgeHours (measured by the database clock) are discarded instead of resumed. Optional extras: spacingMs (pause between guilds, default 1500), spawnTimeoutMs (voice-join limit per guild, default 60000)."
|
|
||||||
},
|
|
||||||
"audio": {
|
"audio": {
|
||||||
"allowLoadstream": false,
|
"allowLoadstream": false,
|
||||||
"allowPrivateUrls": false,
|
|
||||||
"CommentPrivateUrls": "Direct audio URLs typed into %play are fetched by the bot itself. By default addresses on private networks (127.0.0.0/8, 10/8, 172.16/12, 192.168/16, 169.254/16, ...) are refused, including via redirects, so users cannot make the bot probe your internal services. Set true ONLY if you deliberately stream from your LAN (e.g. a home Icecast). Radio stations from config.radio and the local Bilibili proxy are always allowed.",
|
|
||||||
"Comment": "Playback runs on NodeLink's /v4/trackstream endpoint only: WebM/Opus zero-re-encode passthrough, stale URLs auto-retried with a fresh resolve, and seeks handled in-process by the bot (no FFmpeg anywhere). Leave allowLoadstream = false unless you specifically need the legacy /v4/loadstream route. Set it to true only if your audio node exposes /v4/loadstream — it re-enables: server-side audio filters (bassboost, nightcore, ...), MP3/AAC/PCM sources (radio stations, Bilibili's AAC audio), and NodeLink-side seeking. loadstream is what required FFmpeg in the past."
|
"Comment": "Playback runs on NodeLink's /v4/trackstream endpoint only: WebM/Opus zero-re-encode passthrough, stale URLs auto-retried with a fresh resolve, and seeks handled in-process by the bot (no FFmpeg anywhere). Leave allowLoadstream = false unless you specifically need the legacy /v4/loadstream route. Set it to true only if your audio node exposes /v4/loadstream — it re-enables: server-side audio filters (bassboost, nightcore, ...), MP3/AAC/PCM sources (radio stations, Bilibili's AAC audio), and NodeLink-side seeking. loadstream is what required FFmpeg in the past."
|
||||||
},
|
},
|
||||||
"bilibili": {
|
"bilibili": {
|
||||||
@@ -101,7 +106,16 @@
|
|||||||
"port": 3306,
|
"port": 3306,
|
||||||
"user": "youruser",
|
"user": "youruser",
|
||||||
"password": "password of your user",
|
"password": "password of your user",
|
||||||
"database": "name of the target database"
|
"database": "name of the target database",
|
||||||
|
"connectionLimit": 15,
|
||||||
|
"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,
|
||||||
|
|||||||
+6
-10
@@ -7,19 +7,15 @@ MYSQL_DATABASE=remix
|
|||||||
MYSQL_USER=remix
|
MYSQL_USER=remix
|
||||||
MYSQL_PASSWORD=remix_pw
|
MYSQL_PASSWORD=remix_pw
|
||||||
|
|
||||||
# --- NodeLink (audio node) ---
|
# --- Host port mappings ---
|
||||||
# REQUIRED. Use the same value in config.json -> nodelink.password. NodeLink is reachable from the
|
# Port exposed on the host for the bot (dashboard backend / health endpoint)
|
||||||
# compose network only (no host port is published), but still pick something unguessable.
|
WEB_PORT=8080
|
||||||
NODELINK_PASSWORD=change-me-nodelink
|
# Port exposed on the host for NodeLink (audio node)
|
||||||
# Optional: git tag or commit of https://github.com/PerformanC/NodeLink to build (default v3.9.0).
|
NODELINK_PORT=3000
|
||||||
# NODELINK_REF=v3.9.0
|
|
||||||
|
|
||||||
# --- Optional: commit shown by the bot (the image has no .git). CI passes the commit SHA. ---
|
|
||||||
# GIT_SHA=
|
|
||||||
|
|
||||||
# --- Timezone applied to all containers ---
|
# --- Timezone applied to all containers ---
|
||||||
TZ=UTC
|
TZ=UTC
|
||||||
|
|
||||||
# --- Optional: raw JSON config written to /app/config.json on first boot ---
|
# --- Optional: raw JSON config written to /app/config.json on first boot ---
|
||||||
# Takes precedence over docker/config_example.json when no config.json is mounted.
|
# Takes precedence over docker/config_example.json when no config.json is mounted.
|
||||||
# CONFIG_JSON={"token":"YOUR_TOKEN","mysql":{"host":"mysql","port":3306,"user":"remix","password":"remix_pw","database":"remix"},"nodelink":{"host":"nodelink","port":3000,"password":"change-me-nodelink"}}
|
# CONFIG_JSON={"token":"YOUR_TOKEN","mysql":{"host":"mysql","port":3306,"user":"remix","password":"remix_pw","database":"remix"},"nodelink":{"host":"nodelink","port":3000,"password":"youshallnotpass"}}
|
||||||
+9
-17
@@ -5,20 +5,18 @@ FROM node:22-bookworm-slim AS builder
|
|||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
# .npmrc carries legacy-peer-deps (the @fluxerjs peer ranges conflict); package-lock.json pins versions.
|
COPY package.json package-lock.json* ./
|
||||||
COPY package.json package-lock.json* .npmrc ./
|
|
||||||
|
|
||||||
RUN npm ci --omit=dev --legacy-peer-deps || npm install --omit=dev --legacy-peer-deps
|
RUN npm ci --omit=dev --legacy-peer-deps 2>/dev/null || npm install --omit=dev --legacy-peer-deps
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# ---- Runtime stage: minimal image ----
|
# ---- Runtime stage: minimal image with ffmpeg ----
|
||||||
# No ffmpeg: audio goes through NodeLink and the in-process Opus/WebM pipeline; ffprobe comes from
|
|
||||||
# the bundled ffprobe-static package.
|
|
||||||
FROM node:22-bookworm-slim AS runtime
|
FROM node:22-bookworm-slim AS runtime
|
||||||
|
|
||||||
RUN apt-get update && \
|
RUN apt-get update && \
|
||||||
apt-get install -y --no-install-recommends \
|
apt-get install -y --no-install-recommends \
|
||||||
|
ffmpeg \
|
||||||
tini \
|
tini \
|
||||||
curl \
|
curl \
|
||||||
ca-certificates \
|
ca-certificates \
|
||||||
@@ -34,19 +32,13 @@ COPY --from=builder --chown=10001:10001 /app ./
|
|||||||
RUN chmod +x docker/docker-entrypoint.sh && \
|
RUN chmod +x docker/docker-entrypoint.sh && \
|
||||||
mkdir -p /app/storage && chown -R 10001:10001 /app
|
mkdir -p /app/storage && chown -R 10001:10001 /app
|
||||||
|
|
||||||
# Commit shown by the bot (the image has no .git). CI passes it with --build-arg GIT_SHA=<sha>.
|
|
||||||
ARG GIT_SHA=""
|
|
||||||
ENV GIT_SHA=${GIT_SHA}
|
|
||||||
|
|
||||||
# The bot touches this file every 15s while its event loop is running and it is logged in.
|
|
||||||
# docker/healthcheck.mjs reports unhealthy when it is missing or stale (no procps needed).
|
|
||||||
ENV HEARTBEAT_FILE=/tmp/remix-heartbeat
|
|
||||||
|
|
||||||
USER 10001:10001
|
USER 10001:10001
|
||||||
|
|
||||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
EXPOSE 80
|
||||||
CMD ["node", "docker/healthcheck.mjs"]
|
|
||||||
|
HEALTHCHECK --interval=15s --timeout=5s --start-period=45s --retries=3 \
|
||||||
|
CMD node -e "const fs = require('fs'); try { const diff = Date.now() - fs.statSync('/tmp/.remix-health').mtimeMs; process.exit(diff < 30000 ? 0 : 1); } catch { process.exit(1); }"
|
||||||
|
|
||||||
ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"]
|
ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"]
|
||||||
|
|
||||||
CMD ["node", "index.mjs"]
|
CMD ["node", "shard.mjs"]
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"token": "YOUR_BOT_TOKEN_HERE",
|
"token": "YOUR_BOT_TOKEN_HERE",
|
||||||
|
"instanceUrl": null,
|
||||||
"prefix": "%",
|
"prefix": "%",
|
||||||
"embedColor": "0xe9196c",
|
"embedColor": "0xe9196c",
|
||||||
"owners": [],
|
"owners": [],
|
||||||
@@ -8,12 +9,13 @@
|
|||||||
"port": 3306,
|
"port": 3306,
|
||||||
"user": "remix",
|
"user": "remix",
|
||||||
"password": "remix_pw",
|
"password": "remix_pw",
|
||||||
"database": "remix"
|
"database": "remix",
|
||||||
|
"connectionLimit": 15
|
||||||
},
|
},
|
||||||
"nodelink": {
|
"nodelink": {
|
||||||
"host": "nodelink",
|
"host": "nodelink",
|
||||||
"port": 3000,
|
"port": 3000,
|
||||||
"password": "change-me-nodelink",
|
"password": "youshallnotpass",
|
||||||
"requestTimeout": 60000
|
"requestTimeout": 60000
|
||||||
},
|
},
|
||||||
"lastfm": {
|
"lastfm": {
|
||||||
|
|||||||
+23
-26
@@ -3,11 +3,9 @@ services:
|
|||||||
build:
|
build:
|
||||||
context: ..
|
context: ..
|
||||||
dockerfile: docker/Dockerfile
|
dockerfile: docker/Dockerfile
|
||||||
args:
|
|
||||||
# Baked into the image so the bot can show a working commit link (the image has no .git).
|
|
||||||
GIT_SHA: ${GIT_SHA:-}
|
|
||||||
container_name: remix-bot
|
container_name: remix-bot
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
command: node shard.mjs
|
||||||
depends_on:
|
depends_on:
|
||||||
mysql:
|
mysql:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
@@ -20,12 +18,19 @@ services:
|
|||||||
- ../storage:/app/storage
|
- ../storage:/app/storage
|
||||||
environment:
|
environment:
|
||||||
- TZ=${TZ:-UTC}
|
- TZ=${TZ:-UTC}
|
||||||
# No ports: the bot runs no HTTP server (the dashboard talks to it over Redis).
|
ports:
|
||||||
|
- "${WEB_PORT:-8080}:80"
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "node", "-e", "const fs = require('fs'); try { const diff = Date.now() - fs.statSync('/tmp/.remix-health').mtimeMs; process.exit(diff < 30000 ? 0 : 1); } catch { process.exit(1); }"]
|
||||||
|
interval: 15s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 45s
|
||||||
networks:
|
networks:
|
||||||
- remix-net
|
- remix-net
|
||||||
|
|
||||||
mysql:
|
mysql:
|
||||||
image: mysql:8.0
|
image: mysql:8.4
|
||||||
container_name: remix-mysql
|
container_name: remix-mysql
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
@@ -36,8 +41,7 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- mysql_data:/var/lib/mysql
|
- mysql_data:/var/lib/mysql
|
||||||
healthcheck:
|
healthcheck:
|
||||||
# Password via MYSQL_PWD (not on the command line, so it is not visible in `ps` or warned about).
|
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD:-remix_root_pw}"]
|
||||||
test: ["CMD-SHELL", "MYSQL_PWD=\"$$MYSQL_ROOT_PASSWORD\" mysqladmin ping -h localhost -u root"]
|
|
||||||
interval: 10s
|
interval: 10s
|
||||||
timeout: 5s
|
timeout: 5s
|
||||||
retries: 10
|
retries: 10
|
||||||
@@ -58,35 +62,28 @@ services:
|
|||||||
- remix-net
|
- remix-net
|
||||||
|
|
||||||
nodelink:
|
nodelink:
|
||||||
# NodeLink is NOT published on npm: it is built from the official repository using its own
|
image: ghcr.io/performanc/nodelink:dev
|
||||||
# Dockerfile. NODELINK_REF is a git tag or commit (v3.9.0 = commit cdb02c6814fd...).
|
|
||||||
# Configuration is done with NODELINK_* environment variables (see NodeLink's docker-compose.yml
|
|
||||||
# for the full list, e.g. cluster, logging and per-source settings).
|
|
||||||
build:
|
|
||||||
context: https://github.com/PerformanC/NodeLink.git#${NODELINK_REF:-v3.9.0}
|
|
||||||
dockerfile: Dockerfile
|
|
||||||
container_name: remix-nodelink
|
container_name: remix-nodelink
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
- TZ=${TZ:-UTC}
|
- TZ=${TZ:-UTC}
|
||||||
- NODELINK_SERVER_HOST=0.0.0.0
|
volumes:
|
||||||
- NODELINK_SERVER_PORT=3000
|
- nodelink_data:/app/.cache
|
||||||
- NODELINK_SERVER_PASSWORD=${NODELINK_PASSWORD:?Set NODELINK_PASSWORD in docker/.env (and the same value in config.json -> nodelink.password)}
|
- ./nodelink.config.json:/app/config.json:ro
|
||||||
# Reachable from the bot over the compose network only. It is deliberately NOT published on
|
ports:
|
||||||
# the host: anyone who can reach it with the password can use your server as an audio proxy.
|
- "${NODELINK_PORT:-3000}:3000"
|
||||||
expose:
|
|
||||||
- "3000"
|
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "node", "-e", "require('net').connect(3000,'127.0.0.1').on('connect',function(){process.exit(0)}).on('error',function(){process.exit(1)})"]
|
test: ["CMD-SHELL", "node -e \"require('net').connect(3000,'127.0.0.1').on('connect',function(){process.exit(0)}).on('error',function(){process.exit(1)})\""]
|
||||||
interval: 5s
|
interval: 10s
|
||||||
timeout: 3s
|
timeout: 5s
|
||||||
retries: 30
|
retries: 5
|
||||||
start_period: 60s
|
start_period: 20s
|
||||||
networks:
|
networks:
|
||||||
- remix-net
|
- remix-net
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
mysql_data:
|
mysql_data:
|
||||||
|
nodelink_data:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
remix-net:
|
remix-net:
|
||||||
|
|||||||
@@ -25,4 +25,8 @@ if [ "$1" = "node" ] && [ "$2" = "shard.mjs" ]; then
|
|||||||
echo "[Docker] Starting Remix bot (sharded supervisor)..."
|
echo "[Docker] Starting Remix bot (sharded supervisor)..."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ "$1" = "npm" ] && [ "$2" = "run" ] && [ "$3" = "shard" ]; then
|
||||||
|
echo "[Docker] Starting Remix bot (sharded supervisor via npm run shard)..."
|
||||||
|
fi
|
||||||
|
|
||||||
exec "$@"
|
exec "$@"
|
||||||
@@ -15,6 +15,12 @@
|
|||||||
"defaultSource": "ytmusic",
|
"defaultSource": "ytmusic",
|
||||||
"fallback": true
|
"fallback": true
|
||||||
},
|
},
|
||||||
|
"spotify": {
|
||||||
|
"playlistLoadLimit": 10
|
||||||
|
},
|
||||||
|
"soundcloud": {
|
||||||
|
"playlistLoadLimit": 10
|
||||||
|
},
|
||||||
"audio": {
|
"audio": {
|
||||||
"normalization": true
|
"normalization": true
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -8,12 +8,10 @@
|
|||||||
import { logger } from "./src/core/Logger.mjs";
|
import { logger } from "./src/core/Logger.mjs";
|
||||||
import Remix from "./src/core/Bot.mjs";
|
import Remix from "./src/core/Bot.mjs";
|
||||||
import { initErrorChannel, reportCrash } from "./src/core/ErrorChannel.mjs";
|
import { initErrorChannel, reportCrash } from "./src/core/ErrorChannel.mjs";
|
||||||
import { startHeartbeat } from "./src/core/Heartbeat.mjs";
|
|
||||||
|
|
||||||
const remix = new Remix();
|
const remix = new Remix();
|
||||||
startHeartbeat({ isReady: () => Boolean(remix.client?.user) });
|
|
||||||
|
|
||||||
initErrorChannel({ config: remix.config, client: remix.client });
|
initErrorChannel({ config: remix.config, client: remix.client, locale: remix.locale });
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check whether an error is a known-ignorable WebSocket transport crash from
|
* Check whether an error is a known-ignorable WebSocket transport crash from
|
||||||
@@ -43,6 +41,15 @@ const isIgnorableWsCrash = (err) => {
|
|||||||
const isBenignAudioStopRace = (err) =>
|
const isBenignAudioStopRace = (err) =>
|
||||||
String(err?.message ?? err ?? "").includes("AudioSource is closed");
|
String(err?.message ?? err ?? "").includes("AudioSource is closed");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Error} err - The error to check.
|
||||||
|
* @returns {boolean} True if the error is a benign demuxer stream error.
|
||||||
|
*/
|
||||||
|
const isBenignDemuxerError = (err) => {
|
||||||
|
const msg = String(err?.message ?? err ?? "");
|
||||||
|
return msg.includes("Did not find the EBML tag") || msg.includes("EBML tag");
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {Error} err - The error to check.
|
* @param {Error} err - The error to check.
|
||||||
* @returns {boolean} True if the error is the stream abort race.
|
* @returns {boolean} True if the error is the stream abort race.
|
||||||
@@ -109,6 +116,14 @@ process.on("uncaughtException", async (err, origin) => {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (isBenignDemuxerError(err)) {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - _lastAudioRaceLog > WS_CRASH_LOG_COOLDOWN) {
|
||||||
|
_lastAudioRaceLog = now;
|
||||||
|
logger.warn("[Error_Handling] Suppressed corrupt audio stream demuxer error (" + (err?.message ?? err) + ") — track will be skipped/retried.");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (isBenignStreamAbortRace(err)) {
|
if (isBenignStreamAbortRace(err)) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (now - _lastAudioRaceLog > WS_CRASH_LOG_COOLDOWN) {
|
if (now - _lastAudioRaceLog > WS_CRASH_LOG_COOLDOWN) {
|
||||||
@@ -134,6 +149,7 @@ process.on("uncaughtException", async (err, origin) => {
|
|||||||
process.on("uncaughtExceptionMonitor", (err, origin) => {
|
process.on("uncaughtExceptionMonitor", (err, origin) => {
|
||||||
if (isIgnorableWsCrash(err)) return;
|
if (isIgnorableWsCrash(err)) return;
|
||||||
if (isBenignAudioStopRace(err)) return;
|
if (isBenignAudioStopRace(err)) return;
|
||||||
|
if (isBenignDemuxerError(err)) return;
|
||||||
if (isBenignStreamAbortRace(err)) return;
|
if (isBenignStreamAbortRace(err)) return;
|
||||||
if (isBenignTransportError(err)) return;
|
if (isBenignTransportError(err)) return;
|
||||||
logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)");
|
logger.error("[Error_Handling] Uncaught Exception/Catch (MONITOR)");
|
||||||
@@ -142,64 +158,18 @@ process.on("uncaughtExceptionMonitor", (err, origin) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Graceful shutdown handler: destroys all active players, closes Lavalink,
|
* Graceful shutdown handler: flushes player queue snapshots to MySQL,
|
||||||
* Redis, and Dashboard DB connections, then exits.
|
* cleans up active players, services, and connections, then exits.
|
||||||
* @async
|
* @async
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
const saveAndExit = async () => {
|
const saveAndExit = async () => {
|
||||||
logger.recovery("\n[Shutdown] Cleaning up before exit...");
|
|
||||||
setTimeout(() => {
|
|
||||||
logger.warn("[Shutdown] Cleanup timed out, forcing exit");
|
|
||||||
process.exit(1);
|
|
||||||
}, 8000).unref();
|
|
||||||
try {
|
try {
|
||||||
await remix.playerState?.saveAllFrom?.(remix.players);
|
if (remix?.gracefulShutdown) {
|
||||||
} catch (e) {
|
await remix.gracefulShutdown();
|
||||||
logger.warn("[Shutdown] Player state save failed:", e?.message);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (remix.players?.playerMap) {
|
|
||||||
for (const [channelId, player] of remix.players.playerMap) {
|
|
||||||
try { player.destroy(); } catch (e) { logger.warn("[Shutdown] Player destroy error:", e?.message); }
|
|
||||||
}
|
|
||||||
remix.players.playerMap.clear();
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[Shutdown] Player cleanup error:", e?.message);
|
logger.error("[Shutdown] Error during graceful shutdown:", e?.message ?? e);
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (remix.lavalink) {
|
|
||||||
remix.lavalink.destroy();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.warn("[Shutdown] Lavalink cleanup error:", e?.message);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (remix.dashboard?.redis?.destroy) {
|
|
||||||
await remix.dashboard.redis.destroy();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.error("[Shutdown] Failed to close Redis:", e.message);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (remix.dashboard?.db?.close) {
|
|
||||||
await remix.dashboard.db.close();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.error("[Shutdown] Failed to close Dashboard DB:", e.message);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
remix.gatewayHandler?.stop247Watchdog?.();
|
|
||||||
} catch (e) {
|
|
||||||
logger.warn("[Shutdown] Watchdog stop error:", e?.message);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
if (remix.settingsMgr?.shutdown) {
|
|
||||||
await remix.settingsMgr.shutdown();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.error("[Shutdown] Settings flush failed:", e.message);
|
|
||||||
}
|
}
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
};
|
};
|
||||||
|
|||||||
+4
-5
@@ -4,7 +4,7 @@
|
|||||||
"node": ">=22.13.0"
|
"node": ">=22.13.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@fluxerjs/core": "^3.1.0",
|
"@fluxerjs/core": "^3.3.0",
|
||||||
"@fluxerjs/sharding": "^3.0.0",
|
"@fluxerjs/sharding": "^3.0.0",
|
||||||
"@fluxerjs/util": "^3.1.0",
|
"@fluxerjs/util": "^3.1.0",
|
||||||
"@fluxerjs/voice": "^3.1.0",
|
"@fluxerjs/voice": "^3.1.0",
|
||||||
@@ -12,15 +12,14 @@
|
|||||||
"ffprobe-static": "^3.1.0",
|
"ffprobe-static": "^3.1.0",
|
||||||
"lavalink-client": "^2.11.0",
|
"lavalink-client": "^2.11.0",
|
||||||
"mysql2": "^3.9.0",
|
"mysql2": "^3.9.0",
|
||||||
"opusscript": "^0.0.8",
|
"opusscript": "^0.1.1",
|
||||||
"prism-media": "^1.3.5",
|
"prism-media": "^1.3.5",
|
||||||
"redis": "^5.12.1"
|
"redis": "^6.3.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "node --inspect index.mjs --trace-warnings",
|
"dev": "node --inspect index.mjs --trace-warnings",
|
||||||
"start": "node index.mjs",
|
"start": "node index.mjs",
|
||||||
"shard": "node shard.mjs",
|
"shard": "node shard.mjs",
|
||||||
"migrate": "node settings/migrate.mjs",
|
"migrate": "node settings/migrate.mjs"
|
||||||
"check": "node scripts/check.mjs"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
/**
|
|
||||||
* Fast project gate for CI and local use (`npm run check`):
|
|
||||||
* 1. every .mjs file parses (node --check)
|
|
||||||
* 2. every module links (catches broken imports / missing exports without starting the bot)
|
|
||||||
* 3. every JSON file is valid
|
|
||||||
* 4. all translations have exactly the keys of en.json
|
|
||||||
* Exits 1 on any failure.
|
|
||||||
*/
|
|
||||||
import { spawnSync } from "node:child_process";
|
|
||||||
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
||||||
import { join, relative } from "node:path";
|
|
||||||
import { pathToFileURL } from "node:url";
|
|
||||||
|
|
||||||
const root = process.cwd();
|
|
||||||
const SKIP_DIRS = new Set(["node_modules", ".git", "test", "scripts"]);
|
|
||||||
const ENTRY_POINTS = new Set(["index.mjs", "shard.mjs", "settings/migrate.mjs", "settings/runnables.mjs", "docker/healthcheck.mjs"]);
|
|
||||||
|
|
||||||
function walk(dir, ext, out = []) {
|
|
||||||
for (const name of readdirSync(dir)) {
|
|
||||||
if (SKIP_DIRS.has(name) || name.startsWith(".")) continue;
|
|
||||||
const p = join(dir, name);
|
|
||||||
if (statSync(p).isDirectory()) walk(p, ext, out);
|
|
||||||
else if (name.endsWith(ext)) out.push(p);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
const rel = (p) => relative(root, p).split("\\").join("/");
|
|
||||||
const failures = [];
|
|
||||||
|
|
||||||
const mjs = walk(root, ".mjs").map(rel).sort();
|
|
||||||
for (const f of mjs) {
|
|
||||||
const r = spawnSync(process.execPath, ["--check", f], { encoding: "utf8" });
|
|
||||||
if (r.status !== 0) failures.push(`syntax ${f}: ${(r.stderr || "").split("\n").find((l) => l.trim()) ?? "error"}`);
|
|
||||||
}
|
|
||||||
console.log(`syntax ${mjs.length} files checked`);
|
|
||||||
|
|
||||||
let linked = 0;
|
|
||||||
const realExit = process.exit;
|
|
||||||
process.exit = (code) => { throw new Error(`called process.exit(${code}) while being imported`); };
|
|
||||||
for (const f of mjs.filter((f) => !ENTRY_POINTS.has(f))) {
|
|
||||||
try { await import(pathToFileURL(join(root, f)).href); linked++; }
|
|
||||||
catch (e) { failures.push(`link ${f}: ${String(e.message).split("\n")[0]}`); }
|
|
||||||
}
|
|
||||||
process.exit = realExit;
|
|
||||||
console.log(`link ${linked} modules loaded`);
|
|
||||||
|
|
||||||
const jsons = walk(root, ".json").map(rel).sort();
|
|
||||||
for (const f of jsons) {
|
|
||||||
try { JSON.parse(readFileSync(join(root, f), "utf8")); }
|
|
||||||
catch (e) { failures.push(`json ${f}: ${e.message}`); }
|
|
||||||
}
|
|
||||||
console.log(`json ${jsons.length} files checked`);
|
|
||||||
|
|
||||||
const localeDir = join(root, "storage", "locales", "bot");
|
|
||||||
try {
|
|
||||||
const flat = (o, p = "", out = {}) => { for (const [k, v] of Object.entries(o)) { const key = p ? p + "." + k : k; v && typeof v === "object" && !Array.isArray(v) ? flat(v, key, out) : (out[key] = v); } return out; };
|
|
||||||
const load = (f) => flat(JSON.parse(readFileSync(join(localeDir, f), "utf8")));
|
|
||||||
const base = load("en.json");
|
|
||||||
let locales = 0;
|
|
||||||
for (const f of readdirSync(localeDir).filter((f) => f.endsWith(".json") && f !== "en.json")) {
|
|
||||||
const d = load(f); locales++;
|
|
||||||
const missing = Object.keys(base).filter((k) => !(k in d));
|
|
||||||
if (missing.length) failures.push(`locale ${f}: ${missing.length} key(s) missing, e.g. ${missing.slice(0, 3).join(", ")}`);
|
|
||||||
}
|
|
||||||
console.log(`locales ${locales} translations compared with en.json (${Object.keys(base).length} keys)`);
|
|
||||||
} catch (e) { failures.push(`locale could not compare translations: ${e.message}`); }
|
|
||||||
|
|
||||||
if (failures.length) {
|
|
||||||
console.error(`\n${failures.length} problem(s):\n ` + failures.join("\n "));
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
console.log("\nall checks passed");
|
|
||||||
process.exit(0);
|
|
||||||
@@ -38,6 +38,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import * as fs from "node:fs";
|
import * as fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { ShardingManager } from "@fluxerjs/sharding";
|
import { ShardingManager } from "@fluxerjs/sharding";
|
||||||
import { logger } from "./src/core/Logger.mjs";
|
import { logger } from "./src/core/Logger.mjs";
|
||||||
@@ -126,18 +128,64 @@ manager.on("error", (err) => {
|
|||||||
logger.error("[Sharding] Manager error:", err?.message ?? err);
|
logger.error("[Sharding] Manager error:", err?.message ?? err);
|
||||||
});
|
});
|
||||||
|
|
||||||
/** Graceful shutdown: destroy all children, then exit.
|
/* Event loop health heartbeat for Docker container healthcheck (Issue #12) */
|
||||||
|
const healthFile = path.join(os.tmpdir(), ".remix-health");
|
||||||
|
const updateHealth = () => {
|
||||||
|
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(), () => {});
|
||||||
|
} catch (_) {}
|
||||||
|
};
|
||||||
|
updateHealth();
|
||||||
|
const healthInterval = setInterval(updateHealth, 10_000);
|
||||||
|
healthInterval.unref?.();
|
||||||
|
|
||||||
|
/** Graceful shutdown: signal shard children to flush queue snapshots, await exit, then destroy.
|
||||||
* @param {string} sig - The received signal name. */
|
* @param {string} sig - The received signal name. */
|
||||||
let shuttingDown = false;
|
let shuttingDown = false;
|
||||||
const shutdown = async (sig) => {
|
const shutdown = async (sig) => {
|
||||||
if (shuttingDown) return;
|
if (shuttingDown) return;
|
||||||
shuttingDown = true;
|
shuttingDown = true;
|
||||||
logger.recovery(`\n[Sharding] ${sig} received — destroying shard processes...`);
|
manager.respawn = false;
|
||||||
|
logger.recovery(`\n[Sharding] ${sig} received — waiting for shard processes to flush queue snapshots and exit...`);
|
||||||
|
|
||||||
|
// Send SIGTERM to all child processes so their saveAndExit / Bot.gracefulShutdown runs
|
||||||
|
const exitPromises = [];
|
||||||
|
if (manager.shards) {
|
||||||
|
for (const shard of manager.shards.values()) {
|
||||||
|
const cp = shard.process;
|
||||||
|
if (cp && !cp.killed) {
|
||||||
|
exitPromises.push(new Promise((resolve) => {
|
||||||
|
cp.once("exit", resolve);
|
||||||
|
setTimeout(resolve, 8000);
|
||||||
|
}));
|
||||||
|
try {
|
||||||
|
cp.kill("SIGTERM");
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (exitPromises.length > 0) {
|
||||||
|
await Promise.all(exitPromises);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await manager.destroy();
|
await manager.destroy();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[Sharding] destroy error:", e?.message);
|
logger.warn("[Sharding] destroy error:", e?.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
clearInterval(healthInterval);
|
||||||
|
fs.unlink(healthFile, () => {});
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
};
|
};
|
||||||
process.once("SIGINT", () => shutdown("SIGINT"));
|
process.once("SIGINT", () => shutdown("SIGINT"));
|
||||||
|
|||||||
@@ -33,8 +33,6 @@ export class CommandHandler extends EventEmitter {
|
|||||||
pingPrefix = true;
|
pingPrefix = true;
|
||||||
/** @type {string[]} Bot owner user IDs. */
|
/** @type {string[]} Bot owner user IDs. */
|
||||||
owners = [];
|
owners = [];
|
||||||
/** When false (default) messages from other bots/webhooks never trigger commands (set config.allowBotCommands = true to allow). */
|
|
||||||
allowBotCommands = false;
|
|
||||||
|
|
||||||
/** @type {import('../ui/MessageHandler.mjs').MessageHandler} */
|
/** @type {import('../ui/MessageHandler.mjs').MessageHandler} */
|
||||||
messages;
|
messages;
|
||||||
@@ -72,7 +70,10 @@ export class CommandHandler extends EventEmitter {
|
|||||||
this.helpHandler = new HelpHandler(this);
|
this.helpHandler = new HelpHandler(this);
|
||||||
this.helpCommand = "help";
|
this.helpCommand = "help";
|
||||||
this.replyHandler = (message, msg) => {
|
this.replyHandler = (message, msg) => {
|
||||||
msg.reply(this.format(message, msg.channel.channel.guildId));
|
const guildId = msg?.channel?.guildId ?? msg?.channel?.channel?.guildId ?? msg?.guildId ?? msg?.message?.guildId ?? null;
|
||||||
|
Promise.resolve(msg.reply(this.format(message, guildId))).catch(err => {
|
||||||
|
logger.warn("[CommandHandler] Failed to reply:", err?.message);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
this.messages.onMessage(this.messageHandler.bind(this));
|
this.messages.onMessage(this.messageHandler.bind(this));
|
||||||
}
|
}
|
||||||
@@ -133,8 +134,6 @@ export class CommandHandler extends EventEmitter {
|
|||||||
*/
|
*/
|
||||||
messageHandler(msg) {
|
messageHandler(msg) {
|
||||||
if (!msg || !msg.content) return;
|
if (!msg || !msg.content) return;
|
||||||
const author = msg.message?.author ?? msg.author;
|
|
||||||
if (author?.bot && !this.allowBotCommands) return;
|
|
||||||
const trimmed = msg.content.trim();
|
const trimmed = msg.content.trim();
|
||||||
if (/^<@!?\d+>$/.test(trimmed)) {
|
if (/^<@!?\d+>$/.test(trimmed)) {
|
||||||
const botId = this.client.user?.id;
|
const botId = this.client.user?.id;
|
||||||
@@ -144,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}>`;
|
||||||
@@ -163,7 +162,7 @@ export class CommandHandler extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!this.commandNames.includes(args[0].toLowerCase())) {
|
if (!this.commandNames.includes(args[0].toLowerCase())) {
|
||||||
this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix$helpCmd", guildId) }), msg);
|
this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: `${prefix}${args[0]}` }), msg);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
|
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
|
||||||
@@ -248,7 +247,7 @@ export class CommandHandler extends EventEmitter {
|
|||||||
* @param {boolean} [external=false] - When true, errors are returned instead of replied.
|
* @param {boolean} [external=false] - When true, errors are returned instead of replied.
|
||||||
* @returns {object|undefined} The command run payload.
|
* @returns {object|undefined} The command run payload.
|
||||||
*/
|
*/
|
||||||
processCommand(cmd, args, msg, previous = false, external = false, requirementsChecked = false) {
|
processCommand(cmd, args, msg, previous = false, external = false) {
|
||||||
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
||||||
|
|
||||||
if (!external) {
|
if (!external) {
|
||||||
@@ -270,10 +269,13 @@ export class CommandHandler extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cmd.requirements.length > 0 && !external && !requirementsChecked) {
|
if (cmd.requirements.length > 0 && !external) {
|
||||||
if (!this.assertRequirements(cmd, msg, args, previous)) return;
|
if (!this.assertRequirements(cmd, msg)) return;
|
||||||
|
}
|
||||||
|
if (previous === false) {
|
||||||
|
const prevGuildId = msg.channel?.guildId ?? msg.channel?.channel?.guildId ?? msg.message?.guildId ?? null;
|
||||||
|
previous = this.format("$prefix" + cmd.name, prevGuildId);
|
||||||
}
|
}
|
||||||
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
|
||||||
if (!external) this.emit("command", { command: cmd, message: msg });
|
if (!external) this.emit("command", { command: cmd, message: msg });
|
||||||
|
|
||||||
if (cmd.subcommands.length !== 0) {
|
if (cmd.subcommands.length !== 0) {
|
||||||
@@ -410,7 +412,10 @@ export class CommandHandler extends EventEmitter {
|
|||||||
const e = this._optionTypeError(errGuildId2, o, value, previous);
|
const e = this._optionTypeError(errGuildId2, o, value, previous);
|
||||||
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
||||||
}
|
}
|
||||||
if (o.empty(value)) value = o.defaultValue;
|
if (o.empty(value)) {
|
||||||
|
if (o.defaultValue === undefined) continue;
|
||||||
|
value = o.defaultValue;
|
||||||
|
}
|
||||||
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
|
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
|
||||||
usedOptions.push(o.uid);
|
usedOptions.push(o.uid);
|
||||||
previous += " " + value;
|
previous += " " + value;
|
||||||
@@ -448,7 +453,7 @@ export class CommandHandler extends EventEmitter {
|
|||||||
* @param {Message} msg
|
* @param {Message} msg
|
||||||
* @returns {boolean}
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
assertRequirements(cmd, msg, args = null, previous = false) {
|
assertRequirements(cmd, msg) {
|
||||||
const authorId = msg.message?.author?.id;
|
const authorId = msg.message?.author?.id;
|
||||||
const isOwner = this.owners.includes(authorId);
|
const isOwner = this.owners.includes(authorId);
|
||||||
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
@@ -481,19 +486,12 @@ export class CommandHandler extends EventEmitter {
|
|||||||
if (missing.length > 0) {
|
if (missing.length > 0) {
|
||||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||||
} else {
|
} else {
|
||||||
let dispatchArgs = args;
|
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
if (!dispatchArgs) {
|
const prefix2 = this.getPrefix(guildId2);
|
||||||
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
const rawContent = msg.message.content;
|
||||||
const prefix2 = this.getPrefix(guildId2);
|
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
||||||
const rawContent = msg.message.content;
|
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||||
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
this.processCommand(cmd, args, msg, false, true);
|
||||||
dispatchArgs = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
this.processCommand(cmd, dispatchArgs, msg, previous, false, true);
|
|
||||||
} catch (e) {
|
|
||||||
logger.error("[CommandHandler] Command failed after async permission check:", e);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -44,23 +44,57 @@ export class CommandLoader {
|
|||||||
this.commands.on("run", (data) => {
|
this.commands.on("run", (data) => {
|
||||||
if (!this.runnables.has(data.command.uid)) return;
|
if (!this.runnables.has(data.command.uid)) return;
|
||||||
const runFc = this.runnables.get(data.command.uid);
|
const runFc = this.runnables.get(data.command.uid);
|
||||||
|
const isPermError = (err) => {
|
||||||
|
return err?.code === "MISSING_PERMISSIONS" ||
|
||||||
|
err?.code === "COMMUNICATION_DISABLED" ||
|
||||||
|
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) => {
|
||||||
|
if (isPermError(e)) {
|
||||||
|
logger.warn(`[CommandHandler] Missing permissions in channel ${data.message?.channelId ?? data.message?.channel?.id}: ${e.code ?? e.message}`);
|
||||||
|
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();
|
||||||
|
logger.error("Error running command; error id #" + id, e);
|
||||||
|
sendErrorReply(id);
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
const result = runFc.call(this.context, data.message, data);
|
const result = runFc.call(this.context, data.message, data);
|
||||||
if (result && typeof result.catch === "function") {
|
if (result && typeof result.catch === "function") {
|
||||||
result.catch(e => {
|
result.catch(handleCmdError);
|
||||||
const id = Utils.uid();
|
|
||||||
logger.error("Error running command; error id #" + id, e);
|
|
||||||
sendErrorReply(id);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const id = Utils.uid();
|
handleCmdError(e);
|
||||||
logger.error("Error running command; error id #" + id, e);
|
|
||||||
sendErrorReply(id);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,8 @@
|
|||||||
|
|
||||||
import { PageBuilder } from "../ui/Paginators.mjs";
|
import { PageBuilder } from "../ui/Paginators.mjs";
|
||||||
import { Option, Flag } from "./Option.mjs";
|
import { Option, Flag } from "./Option.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../ui/index.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @class HelpHandler
|
* @class HelpHandler
|
||||||
@@ -152,52 +154,86 @@ export class HelpHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate detailed help text for a single command.
|
* Generate detailed help embed for a single command.
|
||||||
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
|
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
|
||||||
* @param {object} msg
|
* @param {object} msg
|
||||||
* @returns {string}
|
* @returns {object} Object with embeds array containing the EmbedBuilder.
|
||||||
*/
|
*/
|
||||||
getCommandHelp(command, msg) {
|
getCommandHelp(command, msg) {
|
||||||
const guildId = msg.message.guildId;
|
const guildId = msg.message?.guildId ?? msg.channel?.guildId;
|
||||||
let content = `${HelpHandler.capitalise(command.name)}\n`;
|
const prefix = this.commands.getPrefix(guildId);
|
||||||
content += this.commandDescription(command, msg) + "\n\n";
|
const category = command.category ? command.category.toLowerCase() : "general";
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.usage") + "\n💻 `" + this.commandUsage(command, msg) + "`\n\n";
|
|
||||||
if (command.examples.length > 0)
|
const embed = new EmbedBuilder()
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.examples") + "\n- `" + command.examples.map(e => this.commands.format(e, guildId)).join("`\n- `") + "`\n\n";
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.commands.t(guildId, "cmdHandler.help.commandInspectorAuthor", { prefix, name: command.name }) })
|
||||||
|
.setTitle(HelpHandler.capitalise(command.name))
|
||||||
|
.setDescription(this.commandDescription(command, msg) || "No description provided.")
|
||||||
|
.addFields({
|
||||||
|
name: `💻 ${this.commands.t(guildId, "cmdHandler.help.usage")}`,
|
||||||
|
value: `\`${this.commandUsage(command, msg)}\``,
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
|
||||||
|
if (command.examples.length > 0) {
|
||||||
|
embed.addFields({
|
||||||
|
name: `💡 ${this.commands.t(guildId, "cmdHandler.help.examples")}`,
|
||||||
|
value: command.examples.map(e => `\`${this.commands.format(e, guildId)}\``).join("\n"),
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (command.aliases.length > 1) {
|
if (command.aliases.length > 1) {
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.aliases") + "\n";
|
embed.addFields({
|
||||||
command.aliases.forEach(alias => { content += "- " + alias + "\n"; });
|
name: `🏷️ ${this.commands.t(guildId, "cmdHandler.help.aliases")}`,
|
||||||
content += "\n";
|
value: command.aliases.map(a => `\`${a}\``).join(", "),
|
||||||
|
inline: true
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (command.subcommands.length > 0) {
|
if (command.subcommands.length > 0) {
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.subcommands") + "\n";
|
const subs = command.subcommands.map(s => {
|
||||||
command.subcommands.forEach(s => {
|
const optCount = s.options.length > 0 ? ` (\`${s.options.length} options\`)` : "";
|
||||||
const optCount = s.options.length > 0 ? "; (`" + this.commands.t(guildId, "cmdHandler.help.optionCount", { $count: s.options.length }) + "`)" : "";
|
return `• **${s.name}**: ${(this.commandDescription(s, msg) || "").split("\n")[0]}${optCount}`;
|
||||||
content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + optCount + "\n";
|
}).join("\n");
|
||||||
|
embed.addFields({
|
||||||
|
name: `📂 ${this.commands.t(guildId, "cmdHandler.help.subcommands")}`,
|
||||||
|
value: subs.slice(0, 1024),
|
||||||
|
inline: false
|
||||||
});
|
});
|
||||||
content += "\n";
|
|
||||||
} else if (command.options.length > 0) {
|
} else if (command.options.length > 0) {
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.arguments") + "\n";
|
const optLines = command.options.map(o => {
|
||||||
command.options.forEach(o => {
|
const optional = o.required ? "" : " *(optional)*";
|
||||||
const optional = ((o.required) ? "" : "?");
|
|
||||||
const flag = (o instanceof Flag) ? "-" : "";
|
const flag = (o instanceof Flag) ? "-" : "";
|
||||||
|
const desc = (o.description || "").split("\n")[0];
|
||||||
if (o.type === "choice") {
|
if (o.type === "choice") {
|
||||||
const choiceDisplay = Option.formatChoicesInline(o.choices);
|
const choiceDisplay = Option.formatChoicesInline(o.choices);
|
||||||
const aliasDisplay = o.aliases.filter(a => a !== null).join('`, `');
|
return `• **${flag}${o.name}**${optional}: ${desc}\n └ Values: \`${choiceDisplay}\``;
|
||||||
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + ";\n - " + this.commands.t(guildId, "cmdHandler.help.allowedValues") + choiceDisplay + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + aliasDisplay + "`\n";
|
|
||||||
} else {
|
|
||||||
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + o.aliases.join("`, `") + "`\n";
|
|
||||||
}
|
}
|
||||||
content += "\n";
|
return `• **${flag}${o.name}**${optional}: ${desc}`;
|
||||||
|
}).join("\n");
|
||||||
|
embed.addFields({
|
||||||
|
name: `⚙️ ${this.commands.t(guildId, "cmdHandler.help.arguments")}`,
|
||||||
|
value: optLines.slice(0, 1024),
|
||||||
|
inline: false
|
||||||
});
|
});
|
||||||
content += "\n";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (command.requirements.length > 0) {
|
if (command.requirements.length > 0) {
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.requirements") + "\n";
|
const perms = command.requirements.map(r =>
|
||||||
command.requirements.forEach(r => {
|
r.getPermissions().map(e => this.commands.t(guildId, "cmdHandler.help.permission", { $permission: e })).join(", ")
|
||||||
content += "- " + r.getPermissions().map(e => this.commands.t(guildId, "cmdHandler.help.permission", { $permission: e })).join("\n- ");
|
).filter(Boolean).join(", ");
|
||||||
});
|
if (perms) {
|
||||||
|
embed.addFields({
|
||||||
|
name: `🔒 ${this.commands.t(guildId, "cmdHandler.help.requirements")}`,
|
||||||
|
value: perms.slice(0, 1024),
|
||||||
|
inline: false
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return content.trim();
|
|
||||||
|
embed.setFooter({ text: this.commands.t(guildId, "cmdHandler.help.commandInspectorFooter", { prefix, category }) });
|
||||||
|
|
||||||
|
return { embeds: [embed] };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -211,8 +211,11 @@ export class Option {
|
|||||||
case "text":
|
case "text":
|
||||||
case "string":
|
case "string":
|
||||||
return i;
|
return i;
|
||||||
case "number":
|
case "number": {
|
||||||
return parseFloat(i);
|
if (i === undefined || i === null || i === "") return null;
|
||||||
|
const parsed = parseFloat(i);
|
||||||
|
return Number.isFinite(parsed) ? parsed : null;
|
||||||
|
}
|
||||||
case "boolean":
|
case "boolean":
|
||||||
return i?.toLowerCase() === "true" || i === "1";
|
return i?.toLowerCase() === "true" || i === "1";
|
||||||
case "choice":
|
case "choice":
|
||||||
|
|||||||
+315
-31
@@ -7,6 +7,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import * as fs from "node:fs";
|
import * as fs from "node:fs";
|
||||||
|
import os from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import childProcess from "node:child_process";
|
import childProcess from "node:child_process";
|
||||||
import { Client, Events } from "@fluxerjs/core";
|
import { Client, Events } from "@fluxerjs/core";
|
||||||
@@ -20,15 +21,20 @@ 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 { PlayerManager } from "../music/PlayerManager.mjs";
|
import { PlayerManager } from "../music/PlayerManager.mjs";
|
||||||
import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
||||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||||
import { VoiceStateCache } from "../voice/VoiceStateCache.mjs";
|
import { VoiceStateCache } from "../voice/VoiceStateCache.mjs";
|
||||||
import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
|
import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
|
||||||
import { RejoinBackoff } from "../voice/gateway/RejoinBackoff.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 { 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";
|
||||||
@@ -135,11 +141,32 @@ class Remix {
|
|||||||
this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
|
this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
|
||||||
this.locale.load();
|
this.locale.load();
|
||||||
|
|
||||||
|
// Centralized MySQL connection pool (Issue #21)
|
||||||
|
const sharedPool = getSharedMysqlPool(config.mysql);
|
||||||
|
const sharedPromisePool = getSharedPromisePool(config.mysql);
|
||||||
|
|
||||||
|
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: config.mysql,
|
mysql: sharedPromisePool,
|
||||||
});
|
});
|
||||||
|
if (!this.redis.enabled && this.dashboard?.redis) {
|
||||||
|
TrackStats.setRedis(this.dashboard.redis);
|
||||||
|
GuildStats.setRedis(this.dashboard.redis);
|
||||||
|
}
|
||||||
|
|
||||||
const presenceContents = config.presenceContents ?? [];
|
const presenceContents = config.presenceContents ?? [];
|
||||||
const presenceInterval = config.presenceInterval ?? 30_000;
|
const presenceInterval = config.presenceInterval ?? 30_000;
|
||||||
@@ -157,7 +184,7 @@ class Remix {
|
|||||||
intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000,
|
intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000,
|
||||||
};
|
};
|
||||||
|
|
||||||
const client = new Client({
|
const clientOptions = {
|
||||||
waitForGuilds: true,
|
waitForGuilds: true,
|
||||||
cache: {
|
cache: {
|
||||||
guilds: 10_000,
|
guilds: 10_000,
|
||||||
@@ -168,7 +195,17 @@ class Remix {
|
|||||||
},
|
},
|
||||||
...config["fluxer.js"],
|
...config["fluxer.js"],
|
||||||
presence: presenceContents.length === 0 ? undefined : buildRuntimePresence(presenceContents[0]),
|
presence: presenceContents.length === 0 ? undefined : buildRuntimePresence(presenceContents[0]),
|
||||||
});
|
};
|
||||||
|
|
||||||
|
if (config.instanceUrl) {
|
||||||
|
const url = String(config.instanceUrl).trim().replace(/\/+$/, "");
|
||||||
|
if (url) {
|
||||||
|
clientOptions.instance = { api: url };
|
||||||
|
logger.info(`[Startup] Self-hosted instance configured: ${url}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = new Client(clientOptions);
|
||||||
|
|
||||||
client.setMaxListeners(50);
|
client.setMaxListeners(50);
|
||||||
this.client = client;
|
this.client = client;
|
||||||
@@ -183,10 +220,13 @@ class Remix {
|
|||||||
const messages = new MessageHandler(this.client);
|
const messages = new MessageHandler(this.client);
|
||||||
this.messages = messages;
|
this.messages = messages;
|
||||||
|
|
||||||
const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
|
const settings = new RemoteSettingsManager(sharedPool, "./storage/defaults.json");
|
||||||
this.settingsMgr = settings;
|
this.settingsMgr = settings;
|
||||||
|
|
||||||
this.playerState = new PlayerStateStore(settings.db);
|
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) {
|
||||||
@@ -209,24 +249,19 @@ 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
|
icon_url: (msg.channel?.channel?.guild?.icon || msg.server?.icon)
|
||||||
? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.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 ?? null,
|
title: msg.channel?.channel?.guild?.name ?? msg.server?.name ?? null,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
const ownerList = [].concat(config.owners ?? []);
|
commands.owners = config.owners ?? [];
|
||||||
if (ownerList.some((id) => typeof id === "number")) {
|
|
||||||
logger.warn("[Config] owners contains a JSON number. Snowflake IDs exceed 2^53 and are corrupted as numbers: write each ID as a quoted string.");
|
|
||||||
}
|
|
||||||
commands.owners = ownerList.map((id) => String(id).trim()).filter(Boolean);
|
|
||||||
commands.allowBotCommands = config.allowBotCommands === true;
|
|
||||||
|
|
||||||
this.lavalink = null;
|
this.lavalink = null;
|
||||||
let lavalinkInitialised = false;
|
let lavalinkInitialised = false;
|
||||||
@@ -247,21 +282,94 @@ class Remix {
|
|||||||
this.intentionalLeaves = new Map();
|
this.intentionalLeaves = new Map();
|
||||||
/** Bot-level 24/7 rejoin timers (channelId → Timeout). Owned by Remix, not by Players. */
|
/** Bot-level 24/7 rejoin timers (channelId → Timeout). Owned by Remix, not by Players. */
|
||||||
this._247RejoinTimers = new Map();
|
this._247RejoinTimers = new Map();
|
||||||
/** Escalating per-channel cool-down so the 24/7 watchdog stops hammering channels it cannot join. */
|
|
||||||
this.rejoinBackoff = new RejoinBackoff();
|
|
||||||
|
|
||||||
this.gatewayHandler = new GatewayHandler(this);
|
this.gatewayHandler = new GatewayHandler(this);
|
||||||
this.gatewayHandler.setupEventHandlers();
|
this.gatewayHandler.setupEventHandlers();
|
||||||
|
|
||||||
this.lastfm = new LastFmManager(config.lastfm, config.mysql);
|
this.lastfm = new LastFmManager(config.lastfm, sharedPromisePool);
|
||||||
this.fluxerlist = new FluxerListManager(config.fluxerlist);
|
this.fluxerlist = new FluxerListManager(config.fluxerlist);
|
||||||
this.trackOptions = new TrackOptionsManager(config.mysql);
|
this.trackOptions = new TrackOptionsManager(sharedPool);
|
||||||
|
this.playlists = new PlaylistManager(sharedPromisePool);
|
||||||
|
this.statusChannel = new StatusChannelManager(this, config.statusChannel);
|
||||||
|
|
||||||
|
/* 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 updateHealth = () => {
|
||||||
|
try {
|
||||||
|
/* 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 (_) {}
|
||||||
|
};
|
||||||
|
updateHealth();
|
||||||
|
this._healthInterval = setInterval(updateHealth, 10_000);
|
||||||
|
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
|
||||||
|
process.once("SIGINT", () => {
|
||||||
|
this.gracefulShutdown().then(() => process.exit(0)).catch(() => process.exit(1));
|
||||||
|
});
|
||||||
|
process.once("SIGTERM", () => {
|
||||||
|
this.gracefulShutdown().then(() => process.exit(0)).catch(() => process.exit(1));
|
||||||
|
});
|
||||||
|
|
||||||
settings.on("ready", () => this._onSettingsReady());
|
settings.on("ready", () => this._onSettingsReady());
|
||||||
|
|
||||||
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();
|
||||||
|
|
||||||
@@ -284,14 +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) {
|
||||||
|
this.players?.resumeAllOnNodeReconnect?.();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.lavalink.on("nodeReconnect", () => {
|
||||||
|
this.statusChannel?.resolveIncident("audioNode");
|
||||||
|
if (this._hasBooted) {
|
||||||
|
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.statusChannel?.start();
|
||||||
|
this.statusChannel?.resolveIncident("gateway");
|
||||||
|
|
||||||
this.fluxerlist?.startAutoStats?.(client);
|
this.fluxerlist?.startAutoStats?.(client);
|
||||||
|
|
||||||
@@ -323,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,
|
||||||
@@ -341,15 +498,9 @@ class Remix {
|
|||||||
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||||
this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const sha = process.env.GIT_SHA?.trim();
|
logger.warn("[Git] comhash error:", e?.message);
|
||||||
if (sha) {
|
this.comHash = "Newest";
|
||||||
this.comHash = sha.slice(0, 7);
|
this.comHashLong = null;
|
||||||
this.comHashLong = sha;
|
|
||||||
} else {
|
|
||||||
logger.warn("[Git] comhash error:", e?.message);
|
|
||||||
this.comHash = "Newest";
|
|
||||||
this.comHashLong = null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
||||||
@@ -553,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) => {
|
||||||
@@ -580,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);
|
||||||
}
|
}
|
||||||
@@ -614,6 +799,105 @@ class Remix {
|
|||||||
logger.warn("[WS] Failed to attach WS error handlers:", e.message);
|
logger.warn("[WS] Failed to attach WS error handlers:", e.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Graceful shutdown: flush player queue snapshots to MySQL (Issue #12),
|
||||||
|
* destroy players, close Lavalink, Redis, dashboard DB, settings, and pool.
|
||||||
|
* @async
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async gracefulShutdown() {
|
||||||
|
if (this._shuttingDown) return;
|
||||||
|
this._shuttingDown = true;
|
||||||
|
logger.recovery("\n[Shutdown] Cleaning up before exit...");
|
||||||
|
|
||||||
|
// 1. Flush active player queue snapshots to MySQL (Issue #12)
|
||||||
|
try {
|
||||||
|
if (this.playerState && this.players) {
|
||||||
|
await this.playerState.saveAllFrom(this.players);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Shutdown] Player state save failed:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Destroy live players
|
||||||
|
try {
|
||||||
|
if (this.players?.playerMap) {
|
||||||
|
for (const [channelId, player] of this.players.playerMap) {
|
||||||
|
try { player.destroy(); } catch (e) { logger.warn("[Shutdown] Player destroy error:", e?.message); }
|
||||||
|
}
|
||||||
|
this.players.playerMap.clear();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Shutdown] Player cleanup error:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Destroy Lavalink
|
||||||
|
try {
|
||||||
|
if (this.lavalink) {
|
||||||
|
this.lavalink.destroy();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Shutdown] Lavalink cleanup error:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
TrackStats.save();
|
||||||
|
GuildStats.flushAll();
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
/* 4. Close Redis */
|
||||||
|
try {
|
||||||
|
if (this.redis?.destroy) {
|
||||||
|
await this.redis.destroy();
|
||||||
|
} else if (this.dashboard?.redis?.destroy) {
|
||||||
|
await this.dashboard.redis.destroy();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.error("[Shutdown] Failed to close Redis:", e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Close Dashboard DB if present
|
||||||
|
try {
|
||||||
|
if (this.dashboard?.db?.close) {
|
||||||
|
await this.dashboard.db.close();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.error("[Shutdown] Failed to close Dashboard DB:", e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 6. Stop 24/7 watchdog and status channel */
|
||||||
|
try {
|
||||||
|
this.statusChannel?.destroy?.();
|
||||||
|
this.gatewayHandler?.stop247Watchdog?.();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Shutdown] Watchdog stop error:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. Flush pending settings writes
|
||||||
|
try {
|
||||||
|
if (this.settingsMgr?.shutdown) {
|
||||||
|
await this.settingsMgr.shutdown();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.error("[Shutdown] Settings flush failed:", e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 8. Close unified shared MySQL pool (Issue #21)
|
||||||
|
try {
|
||||||
|
await closeSharedMysqlPool();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Shutdown] MySQL pool close failed:", e?.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 9. Clean up event-loop health heartbeat and gateway watchdog */
|
||||||
|
try {
|
||||||
|
if (this._gatewayWatchdogInterval) clearInterval(this._gatewayWatchdogInterval);
|
||||||
|
if (this._healthInterval) clearInterval(this._healthInterval);
|
||||||
|
const healthFile = path.join(os.tmpdir(), ".remix-health");
|
||||||
|
fs.unlink(healthFile, () => {});
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
applyMixins(Remix, BotVoiceMixin);
|
applyMixins(Remix, BotVoiceMixin);
|
||||||
|
|||||||
+143
-94
@@ -17,15 +17,6 @@ import { remove247ChannelMode, isPlayerConnectionDead, detachPlayerFromManager,
|
|||||||
import { logger } from "./Logger.mjs";
|
import { logger } from "./Logger.mjs";
|
||||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||||
|
|
||||||
/** Reject if `promise` has not settled within `ms` (the timer is always cleared). */
|
|
||||||
function withTimeout(promise, ms, label) {
|
|
||||||
let timer;
|
|
||||||
return Promise.race([
|
|
||||||
promise,
|
|
||||||
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms); }),
|
|
||||||
]).finally(() => clearTimeout(timer));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {object}
|
* @type {object}
|
||||||
* @description Voice/channel mixin — applied to Remix.
|
* @description Voice/channel mixin — applied to Remix.
|
||||||
@@ -197,10 +188,24 @@ const BotVoiceMixin = {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const guild = this.client?.guilds?.get?.(cleanG);
|
||||||
|
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)`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const backoffRemaining = this.gatewayHandler?.rejoinBackoff?.remainingMs?.(cleanCh) ?? 0;
|
||||||
|
if (backoffRemaining > 0 && delayMs === null) {
|
||||||
|
logger.voice247(`[247] Channel ${cleanCh} in backoff cooldown (${Math.round(backoffRemaining / 1000)}s left) — skipping immediate rejoin`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
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(() => {
|
||||||
@@ -209,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);
|
||||||
|
|
||||||
@@ -380,6 +391,7 @@ const BotVoiceMixin = {
|
|||||||
: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)], allowedMentions: { parse: [] } };
|
: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)], allowedMentions: { parse: [] } };
|
||||||
ch.send(payload).catch(err => {
|
ch.send(payload).catch(err => {
|
||||||
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||||
|
player.textChannel = null;
|
||||||
logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`);
|
logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`);
|
||||||
} else {
|
} else {
|
||||||
logger.warn(`[_spawnPlayer] Failed to send announcement in channel ${ch.id}:`, err?.message ?? err);
|
logger.warn(`[_spawnPlayer] Failed to send announcement in channel ${ch.id}:`, err?.message ?? err);
|
||||||
@@ -399,7 +411,6 @@ const BotVoiceMixin = {
|
|||||||
|
|
||||||
this.players.playerMap.set(cleanChannelId, player);
|
this.players.playerMap.set(cleanChannelId, player);
|
||||||
this.players._indexPlayer(cleanGuildId, cleanChannelId);
|
this.players._indexPlayer(cleanGuildId, cleanChannelId);
|
||||||
this.rejoinBackoff?.recordSuccess(cleanChannelId);
|
|
||||||
if (this.players._pendingJoins) {
|
if (this.players._pendingJoins) {
|
||||||
this.players._pendingJoins.delete(cleanChannelId);
|
this.players._pendingJoins.delete(cleanChannelId);
|
||||||
}
|
}
|
||||||
@@ -417,12 +428,120 @@ const BotVoiceMixin = {
|
|||||||
this.players._pendingJoins.delete(cleanChannelId);
|
this.players._pendingJoins.delete(cleanChannelId);
|
||||||
}
|
}
|
||||||
this.players.playerMap.delete(cleanChannelId);
|
this.players.playerMap.delete(cleanChannelId);
|
||||||
try { player.destroy(); } catch(e) { logger.warn("[_spawnPlayer] Cleanup destroy error:", e?.message); }
|
try { player.destroy(); } catch(e) {}
|
||||||
logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message);
|
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
async _applyPlayerSnapshot(player, snap, { announce = true } = {}) {
|
||||||
|
const tcId = cleanId(snap.textChannelId);
|
||||||
|
if (tcId) {
|
||||||
|
const tc = this.client?.channels?.get?.(tcId);
|
||||||
|
if (tc) player.textChannel = tc;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Number.isFinite(snap.volume) && snap.volume > 0) {
|
||||||
|
try { player.setVolume(Math.min(Number(snap.volume), 2)); } catch (_) {}
|
||||||
|
}
|
||||||
|
player.queue.loop = !!snap.loop;
|
||||||
|
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 : [])
|
||||||
|
.filter((t) => t && (t.url || t.encoded));
|
||||||
|
|
||||||
|
let current = (snap.current && (snap.current.url || snap.current.encoded)) ? snap.current : null;
|
||||||
|
let pos = Math.max(0, Number(snap.positionMs) || 0);
|
||||||
|
const dur = Number(current?._durationMs) || 0;
|
||||||
|
if (current && dur > 0 && pos > dur * 0.9) {
|
||||||
|
if (snap.songLoop || snap.loop) pos = 0;
|
||||||
|
else current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current && !player._lastPlayedTrack) {
|
||||||
|
player._lastPlayedTrack = current;
|
||||||
|
}
|
||||||
|
|
||||||
|
player.queue.data = [];
|
||||||
|
if (current) player.queue.data.push(current);
|
||||||
|
for (const t of restoredQueue) player.queue.data.push(t);
|
||||||
|
|
||||||
|
const count = player.queue.data.length;
|
||||||
|
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) {
|
||||||
|
const restoreEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: player._t?.("responses._common.restoreAuthor") ?? "🔄 24/7 Voice Watchdog" })
|
||||||
|
.setTitle(player._t?.("responses._common.restoreTitle") ?? "Playback Session Restored")
|
||||||
|
.setDescription(
|
||||||
|
player._t?.("responses._common.queueRestored", { count })
|
||||||
|
?? `Bot restarted — restored **${count}** song(s) to the queue and reconnected to voice.`
|
||||||
|
)
|
||||||
|
.setFooter({ text: player._t?.("responses._common.restoreFooter") ?? "24/7 Voice Persistence • Playback resuming automatically" });
|
||||||
|
|
||||||
|
player.emit("message", {
|
||||||
|
embeds: [restoreEmbed],
|
||||||
|
system: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (current && pos > 0 && dur > 0) player._resumeSeekMs = pos;
|
||||||
|
if (!player.queue.getCurrent()) {
|
||||||
|
player.playNext().catch((e) => logger.warn(`[Restore] playNext failed for guild ${player._guildId}:`, e?.message ?? e));
|
||||||
|
} else if (player._resumeSeekMs > 0) {
|
||||||
|
const seekTo = player._resumeSeekMs;
|
||||||
|
player._resumeSeekMs = 0;
|
||||||
|
setTimeout(() => { player.seekToPosition(seekTo).catch(() => {}); }, 800).unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
return { count, pos };
|
||||||
|
},
|
||||||
|
|
||||||
|
async restorePlayerStateForChannel(guildId, channelId, player) {
|
||||||
|
const store = this.playerState;
|
||||||
|
if (!store || !player || player._destroyed) return 0;
|
||||||
|
if (player.queue?.getCurrent?.() || !player.queue?.isEmpty?.()) return 0;
|
||||||
|
|
||||||
|
let row = null;
|
||||||
|
try {
|
||||||
|
row = await store.load(guildId);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Restore] Could not load saved player state for rejoin:", e?.message);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (!row || cleanId(row.data?.channelId) !== cleanId(channelId)) return 0;
|
||||||
|
|
||||||
|
const applied = await this._applyPlayerSnapshot(player, row.data, { announce: false });
|
||||||
|
if (!applied.count) {
|
||||||
|
await store.clearSnapshot(guildId);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
logger.voice247(`[Restore] Rejoined ${channelId}: restored ${applied.count} track(s) from the previous player.`);
|
||||||
|
return applied.count;
|
||||||
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Restore music players saved before a restart/crash (PlayerStateStore).
|
* Restore music players saved before a restart/crash (PlayerStateStore).
|
||||||
* Called from GatewayHandler.onReady after the 24/7 boot recovery.
|
* Called from GatewayHandler.onReady after the 24/7 boot recovery.
|
||||||
@@ -454,29 +573,9 @@ const BotVoiceMixin = {
|
|||||||
logger.player(`[Restore] ${rows.length} saved player(s) found — restoring ${local.length} on this shard.`);
|
logger.player(`[Restore] ${rows.length} saved player(s) found — restoring ${local.length} on this shard.`);
|
||||||
if (!local.length) return;
|
if (!local.length) return;
|
||||||
|
|
||||||
const rc = this.config?.restore ?? {};
|
for (let i = 0; i < local.length; i++) {
|
||||||
const num = (v, d) => (Number.isFinite(Number(v)) && Number(v) >= 0 ? Number(v) : d);
|
const { guildId, data: snap } = local[i];
|
||||||
const spacingMs = num(rc.spacingMs, 1_500);
|
if (i > 0) await new Promise((r) => setTimeout(r, 1_500));
|
||||||
const startTimeoutMs = num(rc.startTimeoutMs, 20_000);
|
|
||||||
const seekSettleMs = num(rc.seekSettleMs, 800);
|
|
||||||
const spawnTimeoutMs = num(rc.spawnTimeoutMs, 60_000);
|
|
||||||
const rawHours = Number(rc.maxAgeHours);
|
|
||||||
const maxAgeHours = rawHours > 0 ? rawHours : 12;
|
|
||||||
|
|
||||||
const toRestore = [];
|
|
||||||
for (const r of local) {
|
|
||||||
if (Number.isFinite(r.ageMs) && r.ageMs > maxAgeHours * 3_600_000) {
|
|
||||||
logger.player(`[Restore] Snapshot for guild ${r.guildId} is ${(r.ageMs / 3_600_000).toFixed(1)}h old (limit ${maxAgeHours}h), dropping it.`);
|
|
||||||
try { await store.clearSnapshot(r.guildId); } catch (_) {}
|
|
||||||
} else {
|
|
||||||
toRestore.push(r);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!toRestore.length) return;
|
|
||||||
|
|
||||||
for (let i = 0; i < toRestore.length; i++) {
|
|
||||||
const { guildId, data: snap } = toRestore[i];
|
|
||||||
if (i > 0) await new Promise((r) => setTimeout(r, spacingMs));
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const channelId = cleanId(snap.channelId);
|
const channelId = cleanId(snap.channelId);
|
||||||
@@ -489,68 +588,18 @@ const BotVoiceMixin = {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const player = await withTimeout(this._spawnPlayer(guildId, channelId), spawnTimeoutMs, "Voice join");
|
const player = await this._spawnPlayer(guildId, channelId);
|
||||||
|
|
||||||
const tcId = cleanId(snap.textChannelId);
|
const applied = await this._applyPlayerSnapshot(player, snap, { announce: true });
|
||||||
if (tcId) {
|
if (!applied.count) {
|
||||||
const tc = this.client?.channels?.get?.(tcId);
|
|
||||||
if (tc) player.textChannel = tc;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Number.isFinite(snap.volume) && snap.volume > 0) {
|
|
||||||
try { player.setVolume(Math.min(Number(snap.volume), 2)); } catch (_) {}
|
|
||||||
}
|
|
||||||
player.queue.loop = !!snap.loop;
|
|
||||||
player.queue.songLoop = !!snap.songLoop;
|
|
||||||
|
|
||||||
const restoredQueue = (Array.isArray(snap.queue) ? snap.queue : [])
|
|
||||||
.filter((t) => t && (t.url || t.encoded));
|
|
||||||
|
|
||||||
let current = (snap.current && (snap.current.url || snap.current.encoded)) ? snap.current : null;
|
|
||||||
const pos = Math.max(0, Number(snap.positionMs) || 0);
|
|
||||||
const dur = Number(current?._durationMs) || 0;
|
|
||||||
if (current && dur > 0 && pos > dur * 0.9) current = null;
|
|
||||||
|
|
||||||
player.queue.data = [];
|
|
||||||
if (current) player.queue.data.push(current);
|
|
||||||
for (const t of restoredQueue) player.queue.data.push(t);
|
|
||||||
|
|
||||||
if (!player.queue.data.length) {
|
|
||||||
await store.clearSnapshot(guildId);
|
await store.clearSnapshot(guildId);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
player.emit("message", {
|
logger.player(`[Restore] Guild ${guildId}: ${applied.count} track(s) restored, resuming at ${applied.pos}ms.`);
|
||||||
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
|
||||||
player._t?.("responses._common.queueRestored", { count: player.queue.data.length })
|
|
||||||
?? `Bot restarted — restored **${player.queue.data.length}** song(s) to the queue.`)],
|
|
||||||
system: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
await new Promise((resolve) => {
|
|
||||||
const timer = setTimeout(() => { player.off("startplay", onStart); resolve(); }, startTimeoutMs);
|
|
||||||
const onStart = () => { clearTimeout(timer); player.off("startplay", onStart); resolve(); };
|
|
||||||
player.once("startplay", onStart);
|
|
||||||
player.playNext().then(onStart, (e) => {
|
|
||||||
logger.warn(`[Restore] playNext failed for guild ${guildId}:`, e?.message ?? e);
|
|
||||||
onStart();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
if (current && pos > 0 && dur > 0) {
|
|
||||||
(async () => {
|
|
||||||
const deadline = Date.now() + 15_000;
|
|
||||||
while (Date.now() < deadline && player._audioBridge?._playing !== true) {
|
|
||||||
await new Promise((r) => setTimeout(r, 250));
|
|
||||||
}
|
|
||||||
await new Promise((r) => setTimeout(r, seekSettleMs)); // let the bridge settle
|
|
||||||
try { await player.seekToPosition(pos); } catch (_) {}
|
|
||||||
})().catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.player(`[Restore] Guild ${guildId}: ${player.queue.data.length} track(s) restored, resuming at ${pos}ms.`);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn(`[Restore] Failed to restore guild ${guildId}:`, e?.message ?? e);
|
logger.warn(`[Restore] Failed to restore guild ${guildId}:`, e?.message ?? e);
|
||||||
|
await store.clearSnapshot(guildId).catch(() => {});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -690,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,
|
||||||
|
|||||||
+257
-39
@@ -29,9 +29,10 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import util from "node:util";
|
import util from "node:util";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { logger } from "./Logger.mjs";
|
import { logger } from "./Logger.mjs";
|
||||||
|
|
||||||
const 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;
|
||||||
@@ -40,10 +41,12 @@ const FAIL_LOG_COOLDOWN_MS = 30_000;
|
|||||||
const CONTENT_MAX = 1_900;
|
const CONTENT_MAX = 1_900;
|
||||||
const BODY_MAX = 1_500;
|
const BODY_MAX = 1_500;
|
||||||
|
|
||||||
|
let _apiBase = DEFAULT_API_BASE;
|
||||||
let _enabled = false;
|
let _enabled = false;
|
||||||
let _channelId = null;
|
let _channelId = null;
|
||||||
let _token = null;
|
let _token = null;
|
||||||
let _client = null;
|
let _client = null;
|
||||||
|
let _locale = null;
|
||||||
let _minIntervalMs = 1_500;
|
let _minIntervalMs = 1_500;
|
||||||
let _maxQueue = 40;
|
let _maxQueue = 40;
|
||||||
|
|
||||||
@@ -52,9 +55,33 @@ let _dropped = 0;
|
|||||||
let _flushing = false;
|
let _flushing = false;
|
||||||
let _announced = false;
|
let _announced = false;
|
||||||
|
|
||||||
const _forwardDedup = new Map();
|
let _forwardDedup = new Map();
|
||||||
const _crashDedup = new Map();
|
let _crashDedup = new Map();
|
||||||
let _lastFailLog = 0;
|
let _lastFailLog = 0;
|
||||||
|
let _rateLimitedUntil = 0;
|
||||||
|
let _consecutiveFailures = 0;
|
||||||
|
let _lastCrashReportTime = 0;
|
||||||
|
const CRASH_MIN_INTERVAL_MS = 5_000;
|
||||||
|
const MAX_CONSECUTIVE_FAILURES = 5;
|
||||||
|
|
||||||
|
/** @private Check if we are currently rate-limited before sending. */
|
||||||
|
function _isRateLimited() {
|
||||||
|
return Date.now() < _rateLimitedUntil;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @private Apply an explicit rate-limit backoff delay. */
|
||||||
|
function _applyRateLimit(seconds = 15) {
|
||||||
|
const ms = Math.max(10_000, Number(seconds) * 1_000);
|
||||||
|
_rateLimitedUntil = Date.now() + ms;
|
||||||
|
console.warn(`[ErrorChannel] Rate limit (429) active — backing off all error channel sends for ${Math.round(ms / 1000)}s.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @private Handle permanent permission failures (403/404) by permanently disabling the reporter. */
|
||||||
|
function _disablePermissionFailure(status) {
|
||||||
|
_enabled = false;
|
||||||
|
_queue = [];
|
||||||
|
console.error(`[ErrorChannel] FATAL: Bot lacks permission (HTTP ${status}) for channel ${_channelId}. ErrorChannel has been PERMANENTLY DISABLED to prevent API flooding.`);
|
||||||
|
}
|
||||||
|
|
||||||
const _originals = { error: null, warn: null, info: null };
|
const _originals = { error: null, warn: null, info: null };
|
||||||
|
|
||||||
@@ -65,15 +92,24 @@ const _originals = { error: null, warn: null, info: null };
|
|||||||
* @param {object} [opts.config] - Full bot configuration (uses config.errorLogChannel and config.token).
|
* @param {object} [opts.config] - Full bot configuration (uses config.errorLogChannel and config.token).
|
||||||
* @param {object} [opts.client] - The Fluxer client (provides client.rest.post for sending).
|
* @param {object} [opts.client] - The Fluxer client (provides client.rest.post for sending).
|
||||||
*/
|
*/
|
||||||
export function initErrorChannel({ config, client } = {}) {
|
export function initErrorChannel({ config, client, locale } = {}) {
|
||||||
const cfg = config?.errorLogChannel ?? {};
|
const cfg = config?.errorLogChannel ?? {};
|
||||||
_channelId = typeof cfg.channelId === "string" && cfg.channelId.trim() ? cfg.channelId.trim() : null;
|
_channelId = typeof cfg.channelId === "string" && cfg.channelId.trim() ? cfg.channelId.trim() : null;
|
||||||
_enabled = cfg.enabled === true && Boolean(_channelId);
|
_enabled = cfg.enabled === true && Boolean(_channelId);
|
||||||
_token = typeof config?.token === "string" ? config.token : null;
|
_token = typeof config?.token === "string" ? config.token : null;
|
||||||
_client = client ?? null;
|
_client = client ?? null;
|
||||||
|
_locale = locale ?? client?.locale ?? null;
|
||||||
_minIntervalMs = Number(cfg.minIntervalMs) > 0 ? Number(cfg.minIntervalMs) : 1_500;
|
_minIntervalMs = Number(cfg.minIntervalMs) > 0 ? Number(cfg.minIntervalMs) : 1_500;
|
||||||
_maxQueue = Number(cfg.maxQueue) > 0 ? Number(cfg.maxQueue) : 40;
|
_maxQueue = Number(cfg.maxQueue) > 0 ? Number(cfg.maxQueue) : 40;
|
||||||
|
|
||||||
|
const customBase = config?.apiBase ?? config?.["fluxer.js"]?.api ?? client?.options?.rest?.api ?? null;
|
||||||
|
if (typeof customBase === "string" && customBase.trim()) {
|
||||||
|
const trimmed = customBase.trim().replace(/\/+$/, "");
|
||||||
|
_apiBase = trimmed.endsWith("/v1") ? trimmed : `${trimmed}/v1`;
|
||||||
|
} else {
|
||||||
|
_apiBase = DEFAULT_API_BASE;
|
||||||
|
}
|
||||||
|
|
||||||
if (!_enabled) {
|
if (!_enabled) {
|
||||||
console.info(`[ErrorChannel] Disabled (${!_channelId ? "no channelId configured" : "enabled=false"}).`);
|
console.info(`[ErrorChannel] Disabled (${!_channelId ? "no channelId configured" : "enabled=false"}).`);
|
||||||
return;
|
return;
|
||||||
@@ -95,14 +131,41 @@ export function isLogChannelEnabled() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** @private Send the one-time startup confirmation through the real send path. */
|
/** @private Send the one-time startup confirmation through the real send path. */
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Resolve a localized string from the bot's configured locale or fallback.
|
||||||
|
* @param {string} key
|
||||||
|
* @param {Object} [vars={}]
|
||||||
|
* @param {string} [fallback=""]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function _t(key, vars = {}, fallback = "") {
|
||||||
|
try {
|
||||||
|
if (_locale && typeof _locale.translate === "function") {
|
||||||
|
const res = _locale.translate(null, `responses.errorChannel.${key}`, vars);
|
||||||
|
if (res && res !== `responses.errorChannel.${key}`) return res;
|
||||||
|
}
|
||||||
|
} catch (_) { }
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
function _announceOnce() {
|
function _announceOnce() {
|
||||||
if (_announced) return;
|
if (_announced) return;
|
||||||
_announced = true;
|
_announced = true;
|
||||||
const content =
|
const embed = new EmbedBuilder()
|
||||||
"✅ **Log channel connected** — from now on this channel receives:\n" +
|
.setColor(0x2ecc71)
|
||||||
"🔴 every error · 🟡 every warning · 🚨 crash reports (with uptime + memory)\n" +
|
.setAuthor({ name: _t("author", {}, "🛠️ Error Channel Telemetry") })
|
||||||
"Verify delivery any time with the `logtest` command.";
|
.setTitle(`✅ ${_t("connectedTitle", {}, "Log Channel Connected")}`)
|
||||||
_sendWithFallback(content).catch((e) => {
|
.setDescription(_t("connectedDesc", {},
|
||||||
|
"Real-time diagnostic and crash forwarding is now active for this channel.\n\n" +
|
||||||
|
"🔴 **Errors:** Database, player, audio node, and gateway exceptions\n" +
|
||||||
|
"🟡 **Warnings:** Rate-limits, recoverable reconnections, and warnings\n" +
|
||||||
|
"🚨 **Crash Reports:** Fatal process exceptions with memory and uptime stats"
|
||||||
|
))
|
||||||
|
.setFooter({ text: _t("connectedFooter", {}, "Remix Watchdog • Verify delivery anytime with %logtest") });
|
||||||
|
if (typeof embed.setTimestamp === "function") embed.setTimestamp();
|
||||||
|
|
||||||
|
_sendWithFallback(embed).catch((e) => {
|
||||||
console.error(
|
console.error(
|
||||||
`[ErrorChannel] Startup notice FAILED for channel ${_channelId}: ${e?.message ?? e}` +
|
`[ErrorChannel] Startup notice FAILED for channel ${_channelId}: ${e?.message ?? e}` +
|
||||||
" — check that the bot has View Channel + Send Messages permission there and that errorLogChannel.channelId is correct."
|
" — check that the bot has View Channel + Send Messages permission there and that errorLogChannel.channelId is correct."
|
||||||
@@ -123,23 +186,46 @@ function _announceOnce() {
|
|||||||
* @returns {Promise<boolean>} True when the message was delivered.
|
* @returns {Promise<boolean>} True when the message was delivered.
|
||||||
*/
|
*/
|
||||||
export async function reportCrash(title, err, { fatal = false } = {}) {
|
export async function reportCrash(title, err, { fatal = false } = {}) {
|
||||||
if (!_enabled || !_channelId) return false;
|
if (!_enabled || !_channelId || _isRateLimited()) return false;
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - _lastCrashReportTime < CRASH_MIN_INTERVAL_MS) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
_lastCrashReportTime = now;
|
||||||
try {
|
try {
|
||||||
const body = _formatArgs([err]).split("```").join("‹›");
|
const body = _formatArgs([err]).split("```").join("‹›");
|
||||||
const now = Date.now();
|
|
||||||
const key = body.slice(0, 300);
|
const key = body.slice(0, 300);
|
||||||
if (_crashDedup.get(key) && now - _crashDedup.get(key) < CRASH_DEDUP_MS) return false;
|
if (_crashDedup.get(key) && now - _crashDedup.get(key) < CRASH_DEDUP_MS) return false;
|
||||||
_crashDedup.set(key, now);
|
_crashDedup.set(key, now);
|
||||||
if (_crashDedup.size > 100) _crashDedup.delete(_crashDedup.keys().next().value);
|
if (_crashDedup.size > 100) _crashDedup.delete(_crashDedup.keys().next().value);
|
||||||
|
|
||||||
const mem = Math.round(process.memoryUsage().rss / 1_048_576);
|
const mem = Math.round(process.memoryUsage().rss / 1_048_576);
|
||||||
const content =
|
const embedColor = fatal ? 0xe74c3c : 0xf39c12;
|
||||||
`${fatal ? "🚨" : "⚠️"} **${title}**\n${body.slice(0, BODY_MAX)}\n— uptime ${_uptime()} · rss ${mem}MB`
|
const authorTitle = fatal
|
||||||
.slice(0, CONTENT_MAX);
|
? _t("crashFatalAuthor", {}, "🚨 Fatal Process Crash")
|
||||||
|
: _t("crashAlertAuthor", {}, "⚠️ Process Alert");
|
||||||
|
const embedTitle = fatal
|
||||||
|
? _t("crashFatalTitle", { title }, `🚨 Fatal Crash: ${title}`)
|
||||||
|
: _t("crashAlertTitle", { title }, `⚠️ Process Alert: ${title}`);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setAuthor({ name: authorTitle })
|
||||||
|
.setTitle(embedTitle)
|
||||||
|
.setDescription("```js\n" + body.slice(0, 1800) + "\n```")
|
||||||
|
.addFields(
|
||||||
|
{ name: _t("uptimeField", {}, "⏱️ Uptime"), value: `\`${_uptime()}\``, inline: true },
|
||||||
|
{ name: _t("memoryField", {}, "💾 Memory (RSS)"), value: `\`${mem} MB\``, inline: true }
|
||||||
|
)
|
||||||
|
.setFooter({ text: _t("crashFooter", {}, "Process Error Telemetry • Unhandled Exception") });
|
||||||
|
if (typeof embed.setTimestamp === "function") embed.setTimestamp();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await Promise.race([_sendWithFallback(content), _sleep(CRASH_SEND_BUDGET_MS)]);
|
const delivered = await Promise.race([
|
||||||
return true;
|
_sendWithFallback(embed).then(() => true),
|
||||||
|
_sleep(CRASH_SEND_BUDGET_MS).then(() => false),
|
||||||
|
]);
|
||||||
|
return Boolean(delivered);
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -164,6 +250,8 @@ export function _resetErrorChannelForTests() {
|
|||||||
_channelId = null;
|
_channelId = null;
|
||||||
_token = null;
|
_token = null;
|
||||||
_client = null;
|
_client = null;
|
||||||
|
_locale = null;
|
||||||
|
_apiBase = DEFAULT_API_BASE;
|
||||||
_queue = [];
|
_queue = [];
|
||||||
_dropped = 0;
|
_dropped = 0;
|
||||||
_flushing = false;
|
_flushing = false;
|
||||||
@@ -200,22 +288,62 @@ 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 emoji = level === "error" ? "🔴" : level === "info" ? "ℹ️" : "🟡";
|
|
||||||
const text = body ? `${emoji} **${tag}** ${body}` : `${emoji} **${tag}**`;
|
|
||||||
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);
|
||||||
if (last && now - last < FORWARD_DEDUP_MS) return;
|
if (last && now - last < FORWARD_DEDUP_MS) return;
|
||||||
_forwardDedup.set(key, now);
|
_forwardDedup.set(key, now);
|
||||||
if (_forwardDedup.size > 300) _forwardDedup.delete(_forwardDedup.keys().next().value);
|
if (_forwardDedup.size > 300) _forwardDedup.delete(_forwardDedup.keys().next().value);
|
||||||
_enqueue(text.slice(0, CONTENT_MAX));
|
|
||||||
|
const color = level === "error" ? 0xe74c3c : level === "info" ? 0x3498db : 0xf1c40f;
|
||||||
|
const author = level === "error"
|
||||||
|
? _t("forwardErrorAuthor", {}, "🔴 System Error")
|
||||||
|
: level === "info"
|
||||||
|
? _t("forwardInfoAuthor", {}, "ℹ️ System Info")
|
||||||
|
: _t("forwardWarnAuthor", {}, "🟡 System Warning");
|
||||||
|
|
||||||
|
let desc;
|
||||||
|
if (body) {
|
||||||
|
desc = body.length > 200
|
||||||
|
? "```\n" + body.slice(0, 3900) + "\n```"
|
||||||
|
: `**${body}**`;
|
||||||
|
} else {
|
||||||
|
desc = _t("forwardNoDetails", {}, "*No additional details provided.*");
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(color)
|
||||||
|
.setAuthor({ name: author })
|
||||||
|
.setTitle(tag)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: _t("forwardFooter", {}, "Logger Telemetry • Automatic Forwarding") });
|
||||||
|
if (typeof embed.setTimestamp === "function") embed.setTimestamp();
|
||||||
|
|
||||||
|
_enqueue(embed);
|
||||||
} catch (_) { }
|
} catch (_) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @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 "";
|
||||||
}
|
}
|
||||||
@@ -236,14 +364,30 @@ async function _runFlush() {
|
|||||||
_flushing = true;
|
_flushing = true;
|
||||||
try {
|
try {
|
||||||
while (_queue.length > 0) {
|
while (_queue.length > 0) {
|
||||||
|
if (!_enabled) {
|
||||||
|
_queue = [];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (_isRateLimited()) {
|
||||||
|
const waitMs = Math.max(1_000, _rateLimitedUntil - Date.now() + 500);
|
||||||
|
await _sleep(waitMs);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const content = _queue.shift();
|
const content = _queue.shift();
|
||||||
await _sendQuietly(content);
|
await _sendQuietly(content);
|
||||||
await _sleep(_minIntervalMs);
|
await _sleep(_minIntervalMs);
|
||||||
}
|
}
|
||||||
if (_dropped > 0) {
|
if (_dropped > 0 && _enabled) {
|
||||||
const n = _dropped;
|
const n = _dropped;
|
||||||
_dropped = 0;
|
_dropped = 0;
|
||||||
await _sendQuietly(`📦 ${n} additional error log message(s) were dropped during a flood to protect rate limits.`);
|
const floodEmbed = new EmbedBuilder()
|
||||||
|
.setColor(0xe67e22)
|
||||||
|
.setAuthor({ name: _t("floodAuthor", {}, "📦 Log Flood Gate") })
|
||||||
|
.setTitle(_t("floodTitle", {}, "Log Messages Dropped"))
|
||||||
|
.setDescription(_t("floodDesc", { count: n }, `⚠️ **${n}** additional log message(s) were dropped during a flood to protect API rate limits.`))
|
||||||
|
.setFooter({ text: _t("floodFooter", {}, "Rate Limit Guard • ErrorChannel") });
|
||||||
|
if (typeof floodEmbed.setTimestamp === "function") floodEmbed.setTimestamp();
|
||||||
|
await _sendQuietly(floodEmbed);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
_flushing = false;
|
_flushing = false;
|
||||||
@@ -263,37 +407,111 @@ async function _sendQuietly(content) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @private Send through the client's REST client when available, else raw fetch. */
|
/**
|
||||||
async function _send(content) {
|
* @private
|
||||||
const rest = _client?.rest;
|
* Normalize a send payload into { content, embeds } format expected by Fluxer API.
|
||||||
if (typeof rest?.post === "function") {
|
* @param {string|object|EmbedBuilder} data
|
||||||
await rest.post(`/channels/${_channelId}/messages`, { body: { content } });
|
* @returns {object}
|
||||||
return;
|
*/
|
||||||
|
function _normalizePayload(data) {
|
||||||
|
if (data instanceof EmbedBuilder) {
|
||||||
|
const raw = typeof data.toJSON === "function" ? data.toJSON() : data;
|
||||||
|
return { embeds: [raw] };
|
||||||
}
|
}
|
||||||
await _sendRaw(content);
|
if (data && typeof data === "object") {
|
||||||
|
if (Array.isArray(data.embeds)) {
|
||||||
|
const rawEmbeds = data.embeds.map(e => (typeof e?.toJSON === "function" ? e.toJSON() : e));
|
||||||
|
return { ...data, embeds: rawEmbeds };
|
||||||
|
}
|
||||||
|
if (data.embed) {
|
||||||
|
const raw = typeof data.embed.toJSON === "function" ? data.embed.toJSON() : data.embed;
|
||||||
|
return { embeds: [raw] };
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
return { content: String(data ?? "") };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @private Send through the client's REST client when available, else raw fetch. */
|
||||||
|
async function _send(payload) {
|
||||||
|
if (!_enabled || _isRateLimited()) return;
|
||||||
|
const rest = _client?.rest;
|
||||||
|
const body = _normalizePayload(payload);
|
||||||
|
if (typeof rest?.post === "function") {
|
||||||
|
try {
|
||||||
|
await rest.post(`/channels/${_channelId}/messages`, { body });
|
||||||
|
_consecutiveFailures = 0;
|
||||||
|
return;
|
||||||
|
} catch (err) {
|
||||||
|
const status = err?.statusCode ?? err?.status;
|
||||||
|
if (status === 403 || status === 404) {
|
||||||
|
_disablePermissionFailure(status);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
if (status === 429) {
|
||||||
|
const retryAfter = err?.retryAfter ?? 15;
|
||||||
|
_applyRateLimit(retryAfter);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await _sendRaw(payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @private Send via client REST, retrying once via raw fetch when that throws. */
|
/** @private Send via client REST, retrying once via raw fetch when that throws. */
|
||||||
async function _sendWithFallback(content) {
|
async function _sendWithFallback(payload) {
|
||||||
|
if (!_enabled || _isRateLimited()) return;
|
||||||
try {
|
try {
|
||||||
await _send(content);
|
await _send(payload);
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
await _sendRaw(content);
|
if (!_enabled || _isRateLimited()) return;
|
||||||
|
await _sendRaw(payload);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @private Send via a direct Fluxer REST call (Authorization: Bot <token>). */
|
/** @private Send via a direct Fluxer REST call (Authorization: Bot <token>). */
|
||||||
async function _sendRaw(content) {
|
async function _sendRaw(payload) {
|
||||||
const res = await fetch(`${API_BASE}/channels/${_channelId}/messages`, {
|
if (!_enabled || !_token || _isRateLimited()) return;
|
||||||
method: "POST",
|
const body = _normalizePayload(payload);
|
||||||
headers: { "Authorization": `Bot ${_token}`, "Content-Type": "application/json" },
|
let res;
|
||||||
body: JSON.stringify({ content }),
|
try {
|
||||||
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
res = await fetch(`${_apiBase}/channels/${_channelId}/messages`, {
|
||||||
});
|
method: "POST",
|
||||||
|
headers: { "Authorization": `Bot ${_token}`, "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
_consecutiveFailures++;
|
||||||
|
if (_consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
|
||||||
|
_applyRateLimit(30);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.status === 403 || res.status === 404) {
|
||||||
|
_disablePermissionFailure(res.status);
|
||||||
|
throw new Error(`Fluxer API HTTP ${res.status}: Permission denied or channel not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.status === 429) {
|
||||||
|
const rawRetry = res.headers.get("retry-after");
|
||||||
|
const retrySec = Number(rawRetry) || 15;
|
||||||
|
_applyRateLimit(retrySec);
|
||||||
|
throw new Error(`Fluxer API HTTP 429: Rate limited, retry after ${retrySec}s`);
|
||||||
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
|
_consecutiveFailures++;
|
||||||
|
if (_consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
|
||||||
|
_applyRateLimit(30);
|
||||||
|
}
|
||||||
const text = await res.text().catch(() => "");
|
const text = await res.text().catch(() => "");
|
||||||
throw new Error(`Fluxer API HTTP ${res.status}: ${text.slice(0, 200)}`);
|
throw new Error(`Fluxer API HTTP ${res.status}: ${text.slice(0, 200)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_consecutiveFailures = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @private Human-readable process uptime. */
|
/** @private Human-readable process uptime. */
|
||||||
|
|||||||
@@ -11,15 +11,12 @@
|
|||||||
* conversion helpers in Serializers.mjs — both are attached at the bottom of this file.
|
* conversion helpers in Serializers.mjs — both are attached at the bottom of this file.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder, CommandHandler, Option } from "../commands/index.mjs";
|
|
||||||
import { PermissionFlags } from "@fluxerjs/core";
|
|
||||||
import Player from "../music/player/index.mjs";
|
|
||||||
import { Utils, cleanId } from "../utils/Utils.mjs";
|
|
||||||
import { DatabaseManager } from "../db/DatabaseManager.mjs";
|
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 { iterateVoiceStates } from "../voice/VoiceStateResolver.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,
|
||||||
|
|||||||
+18
-11
@@ -5,9 +5,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { compare, genSalt, hash } from "bcryptjs";
|
import { compare, genSalt, hash } from "bcryptjs";
|
||||||
import { createPool } from "mysql2/promise";
|
import { attachMysqlPoolGuard } from "./MysqlGuard.mjs";
|
||||||
import { logger } from "../core/Logger.mjs";
|
import { getSharedPromisePool } from "./PoolManager.mjs";
|
||||||
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @class
|
* @class
|
||||||
@@ -17,14 +16,19 @@ import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
|
|||||||
export class DatabaseManager {
|
export class DatabaseManager {
|
||||||
/**
|
/**
|
||||||
* Create a new DatabaseManager.
|
* Create a new DatabaseManager.
|
||||||
* @param {object} config - mysql2 pool configuration (host, user, password, database, etc.).
|
* @param {object} config - mysql2 pool configuration or shared PromisePool instance.
|
||||||
*/
|
*/
|
||||||
constructor(config) {
|
constructor(config) {
|
||||||
this.db = createPool({
|
if (config && typeof config.execute === "function") {
|
||||||
...MYSQL_POOL_DEFAULTS,
|
this.db = config;
|
||||||
connectionLimit: 15,
|
this._ownsPool = false;
|
||||||
...config,
|
} else if (config && typeof config.promise === "function") {
|
||||||
});
|
this.db = config.promise();
|
||||||
|
this._ownsPool = false;
|
||||||
|
} else {
|
||||||
|
this.db = getSharedPromisePool(config);
|
||||||
|
this._ownsPool = false;
|
||||||
|
}
|
||||||
attachMysqlPoolGuard(this.db, "DashboardDB");
|
attachMysqlPoolGuard(this.db, "DashboardDB");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,10 +77,13 @@ export class DatabaseManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Close the underlying MySQL connection pool.
|
* Close the underlying MySQL connection pool (no-op if using a shared pool).
|
||||||
* @returns {Promise<void>}
|
* @returns {Promise<void>}
|
||||||
*/
|
*/
|
||||||
close() {
|
close() {
|
||||||
return this.db.end();
|
if (this._ownsPool && this.db?.end) {
|
||||||
|
return this.db.end();
|
||||||
|
}
|
||||||
|
return Promise.resolve();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,10 +40,19 @@ import { logger } from "../core/Logger.mjs";
|
|||||||
* `enableKeepAlive` is the critical one — without TCP keepalive probes, a
|
* `enableKeepAlive` is the critical one — without TCP keepalive probes, a
|
||||||
* connection parked in the pool behind a NAT/firewall is silently dropped and
|
* connection parked in the pool behind a NAT/firewall is silently dropped and
|
||||||
* the next query on it dies with read ETIMEDOUT.
|
* the next query on it dies with read ETIMEDOUT.
|
||||||
|
*
|
||||||
|
* `maxIdle` and `idleTimeout` switch on mysql2's idle-connection reaper, which
|
||||||
|
* only runs when `maxIdle` is below `connectionLimit` (by default they are
|
||||||
|
* equal, so it never starts). With them set, spare idle connections are closed
|
||||||
|
* client-side after 30s, before a short server-side `wait_timeout` can kill
|
||||||
|
* them (error 4031). Must stay above `keepAliveIntervalMs` (20s) so the pinged
|
||||||
|
* connection is never reaped.
|
||||||
*/
|
*/
|
||||||
const MYSQL_POOL_DEFAULTS = {
|
const MYSQL_POOL_DEFAULTS = {
|
||||||
enableKeepAlive: true,
|
enableKeepAlive: true,
|
||||||
keepAliveInitialDelay: 10_000,
|
keepAliveInitialDelay: 10_000,
|
||||||
|
maxIdle: 1,
|
||||||
|
idleTimeout: 30_000,
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+58
-11
@@ -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]);
|
||||||
@@ -207,16 +229,45 @@ export class PlayerStateStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async load(guildId) {
|
||||||
|
const gId = cleanId(guildId);
|
||||||
|
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();
|
||||||
|
const rows = await this._exec(
|
||||||
|
`SELECT guild_id, data, position_ms FROM player_state WHERE bot_id = ? AND guild_id = ?`,
|
||||||
|
[this.botId, gId]
|
||||||
|
);
|
||||||
|
const row = Array.isArray(rows) ? rows[0] : null;
|
||||||
|
if (!row) return null;
|
||||||
|
try {
|
||||||
|
const parsed = typeof row.data === "string" ? JSON.parse(row.data) : row.data;
|
||||||
|
if (parsed && parsed.channelId) {
|
||||||
|
return { guildId: String(row.guild_id), data: parsed, positionMs: Number(row.position_ms) || 0 };
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[PlayerState] Skipping malformed snapshot for guild", row.guild_id, ":", e?.message);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load every snapshot belonging to this bot.
|
* Load every snapshot belonging to this bot.
|
||||||
* @returns {Promise<Array<{guildId: string, data: object, positionMs: number, ageMs: number|null}>>}
|
* @returns {Promise<Array<{guildId: string, data: object, positionMs: number}>>}
|
||||||
* ageMs = time since the row was last written, measured by the DATABASE clock (immune to
|
|
||||||
* bot/DB clock skew); null when it cannot be determined.
|
|
||||||
*/
|
*/
|
||||||
async loadAll() {
|
async loadAll() {
|
||||||
await this.init();
|
await this.init();
|
||||||
const rows = await this._exec(
|
const rows = await this._exec(
|
||||||
`SELECT guild_id, data, position_ms, TIMESTAMPDIFF(SECOND, updated_at, NOW()) AS age_s FROM player_state WHERE bot_id = ?`,
|
`SELECT guild_id, data, position_ms FROM player_state WHERE bot_id = ?`,
|
||||||
[this.botId]
|
[this.botId]
|
||||||
);
|
);
|
||||||
const out = [];
|
const out = [];
|
||||||
@@ -224,11 +275,7 @@ export class PlayerStateStore {
|
|||||||
try {
|
try {
|
||||||
const parsed = typeof row.data === "string" ? JSON.parse(row.data) : row.data;
|
const parsed = typeof row.data === "string" ? JSON.parse(row.data) : row.data;
|
||||||
if (parsed && parsed.channelId) {
|
if (parsed && parsed.channelId) {
|
||||||
const ageS = row.age_s == null ? NaN : Number(row.age_s);
|
out.push({ guildId: String(row.guild_id), data: parsed, positionMs: Number(row.position_ms) || 0 });
|
||||||
out.push({
|
|
||||||
guildId: String(row.guild_id), data: parsed, positionMs: Number(row.position_ms) || 0,
|
|
||||||
ageMs: Number.isFinite(ageS) ? Math.max(0, ageS) * 1000 : null,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[PlayerState] Skipping malformed snapshot for guild", row.guild_id, ":", e?.message);
|
logger.warn("[PlayerState] Skipping malformed snapshot for guild", row.guild_id, ":", e?.message);
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* @module src/db/PoolManager
|
||||||
|
* @description Centralized MySQL connection pool manager for the Remix bot.
|
||||||
|
* Provides a single shared connection pool instance across all services (Settings,
|
||||||
|
* TrackOptions, Last.fm, Dashboard, PlayerStateStore), preventing connection exhaustion.
|
||||||
|
* Supports both callback-style queries and Promise-based execution via `pool.promise()`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import mysql from "mysql2";
|
||||||
|
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
|
/** @type {import('mysql2').Pool|null} */
|
||||||
|
let _sharedPool = null;
|
||||||
|
|
||||||
|
/** @type {import('mysql2/promise').Pool|null} */
|
||||||
|
let _sharedPromisePool = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get or create the shared MySQL callback-style pool.
|
||||||
|
* If config is omitted, returns the existing pool if one was already initialized.
|
||||||
|
* @param {object} [config] - MySQL configuration (host, user, password, database, connectionLimit, etc.)
|
||||||
|
* @returns {import('mysql2').Pool}
|
||||||
|
*/
|
||||||
|
export function getSharedMysqlPool(config = null) {
|
||||||
|
if (_sharedPool) return _sharedPool;
|
||||||
|
if (!config || !config.host) {
|
||||||
|
throw new Error("[PoolManager] Cannot initialize MySQL pool: missing host or config.");
|
||||||
|
}
|
||||||
|
const connectionLimit = Number(config.connectionLimit) > 0 ? Number(config.connectionLimit) : 15;
|
||||||
|
const poolConfig = {
|
||||||
|
...MYSQL_POOL_DEFAULTS,
|
||||||
|
...config,
|
||||||
|
connectionLimit,
|
||||||
|
};
|
||||||
|
|
||||||
|
_sharedPool = mysql.createPool(poolConfig);
|
||||||
|
attachMysqlPoolGuard(_sharedPool, "SharedMySQL");
|
||||||
|
_sharedPool.on("error", (err) => {
|
||||||
|
logger.error("[MySQL] Shared pool error:", err.code ?? err.message);
|
||||||
|
});
|
||||||
|
logger.db?.(`[PoolManager] Initialized shared MySQL pool (connectionLimit=${connectionLimit}).`);
|
||||||
|
return _sharedPool;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the Promise-based wrapper around the shared MySQL pool (`pool.promise()`).
|
||||||
|
* Shares the exact same underlying connections as the callback pool.
|
||||||
|
* @param {object} [config] - MySQL configuration if not yet initialized.
|
||||||
|
* @returns {import('mysql2/promise').Pool}
|
||||||
|
*/
|
||||||
|
export function getSharedPromisePool(config = null) {
|
||||||
|
if (_sharedPromisePool) return _sharedPromisePool;
|
||||||
|
const pool = getSharedMysqlPool(config);
|
||||||
|
_sharedPromisePool = pool.promise();
|
||||||
|
return _sharedPromisePool;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gracefully close the shared MySQL pool on shutdown.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function closeSharedMysqlPool() {
|
||||||
|
if (_sharedPool) {
|
||||||
|
try {
|
||||||
|
await new Promise((resolve) => _sharedPool.end(() => resolve()));
|
||||||
|
logger.recovery?.("[PoolManager] Shared MySQL pool closed.");
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn?.("[PoolManager] Error closing shared MySQL pool:", e?.message);
|
||||||
|
}
|
||||||
|
_sharedPool = null;
|
||||||
|
_sharedPromisePool = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
+64
-22
@@ -8,7 +8,8 @@
|
|||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import mysql from "mysql2";
|
import mysql from "mysql2";
|
||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
import { MYSQL_POOL_DEFAULTS, attachMysqlPoolGuard } from "./MysqlGuard.mjs";
|
import { attachMysqlPoolGuard } from "./MysqlGuard.mjs";
|
||||||
|
import { getSharedMysqlPool } from "./PoolManager.mjs";
|
||||||
import { logger } from "../core/Logger.mjs";
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -172,24 +173,33 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
/** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */
|
/** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */
|
||||||
_debounceTimers = new Map();
|
_debounceTimers = new Map();
|
||||||
|
|
||||||
/** @private @type {Map<string, Set<string>>} Keys changed since the last flush, per guild: one debounce window can span several keys. */
|
/** @private @type {Map<string, Set<string>>} Pending changed setting keys per guild ID. */
|
||||||
_dirtyKeys = new Map();
|
_pendingKeys = new Map();
|
||||||
|
|
||||||
/** @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 configuration (host, user, password, database).
|
* @param {object} config - mysql2 pool or configuration (host, user, password, database).
|
||||||
* @param {string} defaultsPath - Path to a JSON file with default values and descriptions.
|
* @param {string} defaultsPath - Path to a JSON file with default values and descriptions.
|
||||||
* @param {string|null} [botId=null] - The bot user ID for multi-bot support.
|
* @param {string|null} [botId=null] - The bot user ID for multi-bot support.
|
||||||
*/
|
*/
|
||||||
constructor(config, defaultsPath, botId = null) {
|
constructor(config, defaultsPath, botId = null) {
|
||||||
super();
|
super();
|
||||||
this.botId = botId;
|
this.botId = botId;
|
||||||
this.db = mysql.createPool({ ...MYSQL_POOL_DEFAULTS, connectionLimit: 15, ...config });
|
if (config && typeof config.query === "function") {
|
||||||
|
this.db = config;
|
||||||
|
this._ownsPool = false;
|
||||||
|
} else {
|
||||||
|
this.db = getSharedMysqlPool(config);
|
||||||
|
this._ownsPool = false;
|
||||||
|
}
|
||||||
attachMysqlPoolGuard(this.db, "DB");
|
attachMysqlPoolGuard(this.db, "DB");
|
||||||
this.db.on('error', (err) => {
|
this.db.on?.('error', (err) => {
|
||||||
logger.error('[DB] MySQL pool error:', err.code ?? err.message);
|
logger.error('[DB] MySQL pool error:', err.code ?? err.message);
|
||||||
});
|
});
|
||||||
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
|
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
|
||||||
@@ -213,13 +223,13 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
for (const [, timer] of this._debounceTimers) clearTimeout(timer);
|
for (const [, timer] of this._debounceTimers) clearTimeout(timer);
|
||||||
this._debounceTimers.clear();
|
this._debounceTimers.clear();
|
||||||
this._dirtyKeys?.clear();
|
this._pendingKeys.clear();
|
||||||
if (pendingServers.length > 0) {
|
if (pendingServers.length > 0) {
|
||||||
logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`);
|
logger.info("Settings", `Flushing ${pendingServers.length} pending write(s) on shutdown...`);
|
||||||
}
|
}
|
||||||
await Promise.allSettled(pendingServers.map(server => this._doSave(server)));
|
await Promise.allSettled(pendingServers.map(server => this._doSave(server)));
|
||||||
try {
|
try {
|
||||||
if (this.db?.end) {
|
if (this._ownsPool && this.db?.end) {
|
||||||
await new Promise(r => this.db.end(() => r()));
|
await new Promise(r => this.db.end(() => r()));
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
@@ -236,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.
|
||||||
@@ -244,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'`
|
||||||
@@ -344,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()}`);
|
||||||
}
|
}
|
||||||
@@ -354,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++;
|
||||||
@@ -454,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();
|
||||||
@@ -479,29 +512,38 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
}
|
}
|
||||||
const s = this.guilds.get(server.id);
|
const s = this.guilds.get(server.id);
|
||||||
s.data[key] = server.data[key];
|
s.data[key] = server.data[key];
|
||||||
this._dirtyKeys ??= new Map();
|
|
||||||
if (key === 'stay_247') {
|
if (key === 'stay_247') {
|
||||||
const existing = this._debounceTimers.get(server.id);
|
const existing = this._debounceTimers.get(server.id);
|
||||||
if (existing) { clearTimeout(existing); this._debounceTimers.delete(server.id); }
|
if (existing) { clearTimeout(existing); this._debounceTimers.delete(server.id); }
|
||||||
this._dirtyKeys.delete(server.id);
|
this._pendingKeys.delete(server.id);
|
||||||
this.remoteSave(s).catch(e => logger.error('[Settings] immediate save error:', e.message));
|
this.remoteSave(s).catch(e => logger.error('[Settings] immediate save error:', e.message));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let dirty = this._dirtyKeys.get(server.id);
|
|
||||||
if (!dirty) { dirty = new Set(); this._dirtyKeys.set(server.id, dirty); }
|
if (!this._pendingKeys.has(server.id)) {
|
||||||
dirty.add(key);
|
this._pendingKeys.set(server.id, new Set());
|
||||||
|
}
|
||||||
|
this._pendingKeys.get(server.id).add(key);
|
||||||
|
|
||||||
const existing = this._debounceTimers.get(server.id);
|
const existing = this._debounceTimers.get(server.id);
|
||||||
if (existing) clearTimeout(existing);
|
if (existing) clearTimeout(existing);
|
||||||
this._debounceTimers.set(server.id, setTimeout(() => {
|
this._debounceTimers.set(server.id, setTimeout(async () => {
|
||||||
this._debounceTimers.delete(server.id);
|
this._debounceTimers.delete(server.id);
|
||||||
const keys = [...(this._dirtyKeys.get(server.id) ?? [])];
|
const pending = this._pendingKeys.get(server.id);
|
||||||
this._dirtyKeys.delete(server.id);
|
this._pendingKeys.delete(server.id);
|
||||||
|
|
||||||
const target = this.guilds.get(server.id);
|
const target = this.guilds.get(server.id);
|
||||||
if (!target) return;
|
if (!target || !pending || pending.size === 0) return;
|
||||||
for (const k of keys) {
|
|
||||||
this.remoteUpdate(target, k).catch(e =>
|
try {
|
||||||
logger.error(`[Settings] debounced update error (guild ${server.id}, key "${k}"):`, e?.message)
|
if (pending.size === 1) {
|
||||||
);
|
const [singleKey] = pending;
|
||||||
|
await this.remoteUpdate(target, singleKey);
|
||||||
|
} else {
|
||||||
|
await this.remoteSave(target);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(`[Settings] debounced update error (guild ${server.id}):`, e?.message);
|
||||||
}
|
}
|
||||||
}, 80));
|
}, 80));
|
||||||
}
|
}
|
||||||
@@ -541,7 +583,7 @@ export class RemoteSettingsManager extends SettingsManager {
|
|||||||
removeServer(id) {
|
removeServer(id) {
|
||||||
const timer = this._debounceTimers.get(id);
|
const timer = this._debounceTimers.get(id);
|
||||||
if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); }
|
if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); }
|
||||||
this._dirtyKeys?.delete(id);
|
this._pendingKeys.delete(id);
|
||||||
this.guilds.delete(id);
|
this.guilds.delete(id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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();
|
||||||
@@ -32,10 +32,6 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
this._client = client;
|
this._client = client;
|
||||||
const requestSignalTimeoutMS = Number(nodeCfg.requestTimeout ?? 60_000);
|
const requestSignalTimeoutMS = Number(nodeCfg.requestTimeout ?? 60_000);
|
||||||
|
|
||||||
if (["youshallnotpass", "change-me-nodelink"].includes(nodeCfg.password ?? "youshallnotpass")) {
|
|
||||||
logger.warn("[Lavalink] NodeLink is using a well-known/placeholder password. Set a strong one in config.json (nodelink.password) and as NODELINK_PASSWORD in docker/.env.");
|
|
||||||
}
|
|
||||||
|
|
||||||
this.lavalink = new LavalinkClientManager({
|
this.lavalink = new LavalinkClientManager({
|
||||||
nodes: [
|
nodes: [
|
||||||
{
|
{
|
||||||
@@ -45,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,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -72,19 +69,27 @@ 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;
|
||||||
logger.lavalink("[Lavalink] Node connected (nodeManager): " + node.id);
|
logger.lavalink("[Lavalink] Node connected (nodeManager): " + node.id);
|
||||||
|
this.emit("nodeConnect", node);
|
||||||
});
|
});
|
||||||
nodeMgr.on("disconnect", (node, reason) => {
|
nodeMgr.on("disconnect", (node, reason) => {
|
||||||
this._nodeConnected = false;
|
this._nodeConnected = false;
|
||||||
logger.warn("[Lavalink] Node disconnected (nodeManager):", node?.id, reason);
|
logger.warn("[Lavalink] Node disconnected (nodeManager):", node?.id, reason);
|
||||||
|
this.emit("nodeDisconnect", node, reason);
|
||||||
});
|
});
|
||||||
nodeMgr.on("reconnect", (node) => {
|
nodeMgr.on("reconnect", (node) => {
|
||||||
this._nodeConnected = true;
|
this._nodeConnected = true;
|
||||||
logger.lavalink("[Lavalink] Node reconnecting (nodeManager): " + node.id);
|
logger.lavalink("[Lavalink] Node reconnecting (nodeManager): " + node.id);
|
||||||
|
this.emit("nodeReconnect", node);
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[Lavalink] nodeManager event setup error:", e?.message);
|
logger.warn("[Lavalink] nodeManager event setup error:", e?.message);
|
||||||
@@ -96,20 +101,28 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
this.lavalink.on("nodeConnect", (node) => {
|
this.lavalink.on("nodeConnect", (node) => {
|
||||||
this._nodeConnected = true;
|
this._nodeConnected = true;
|
||||||
logger.lavalink("[Lavalink] Node connected (manager): " + node.id);
|
logger.lavalink("[Lavalink] Node connected (manager): " + node.id);
|
||||||
|
this.emit("nodeConnect", node);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.lavalink.on("nodeReconnect", (node) => {
|
this.lavalink.on("nodeReconnect", (node) => {
|
||||||
this._nodeConnected = true;
|
this._nodeConnected = true;
|
||||||
logger.lavalink("[Lavalink] Node reconnecting (manager): " + node.id);
|
logger.lavalink("[Lavalink] Node reconnecting (manager): " + node.id);
|
||||||
|
this.emit("nodeReconnect", node);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.lavalink.on("nodeDisconnect", (node, reason) => {
|
this.lavalink.on("nodeDisconnect", (node, reason) => {
|
||||||
this._nodeConnected = false;
|
this._nodeConnected = false;
|
||||||
logger.warn("[Lavalink] Node disconnected (manager):", node.id, reason);
|
logger.warn("[Lavalink] Node disconnected (manager):", node.id, reason);
|
||||||
|
this.emit("nodeDisconnect", node, reason);
|
||||||
});
|
});
|
||||||
|
|
||||||
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);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
@@ -420,6 +433,7 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
"[Lavalink] Node ready: " + node.id + " | session: " + this._sessionId
|
"[Lavalink] Node ready: " + node.id + " | session: " + this._sessionId
|
||||||
);
|
);
|
||||||
this.emit("ready", this._sessionId);
|
this.emit("ready", this._sessionId);
|
||||||
|
this.emit("nodeConnect", node);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
"[Lavalink] nodeConnect handler error:",
|
"[Lavalink] nodeConnect handler error:",
|
||||||
@@ -429,6 +443,10 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
};
|
};
|
||||||
|
|
||||||
this.lavalink.on("nodeConnect", onNodeConnect);
|
this.lavalink.on("nodeConnect", onNodeConnect);
|
||||||
|
this.lavalink.on("nodeReconnect", (node) => {
|
||||||
|
onNodeConnect(node);
|
||||||
|
this.emit("nodeReconnect", node);
|
||||||
|
});
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (!this._nodeConnected) {
|
if (!this._nodeConnected) {
|
||||||
@@ -444,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. */
|
||||||
|
|||||||
@@ -13,6 +13,8 @@
|
|||||||
import { cleanId } from "../utils/Utils.mjs";
|
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 { 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) {
|
||||||
@@ -95,6 +97,44 @@ const PlayerEventsMixin = {
|
|||||||
emit("streamStartPlay", Date.now());
|
emit("streamStartPlay", Date.now());
|
||||||
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
||||||
|
|
||||||
|
if (!player._radioReconnects) {
|
||||||
|
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) {
|
||||||
|
const humans = player._getHumanParticipantIdentities?.() ?? [];
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (this._lastfm?.enabled && song) {
|
if (this._lastfm?.enabled && song) {
|
||||||
this._handleLastFmStartPlay(player, song);
|
this._handleLastFmStartPlay(player, song);
|
||||||
}
|
}
|
||||||
@@ -258,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;
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import { get247ChannelMode, isPlayerConnectionDead, detachPlayerFromManager, res
|
|||||||
import { EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
|
import { EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
|
||||||
import { getVoiceManager } from "@fluxerjs/voice";
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
import { getGlobalColor, getMessageGuildId } from "../ui/index.mjs";
|
import { getGlobalColor, getMessageGuildId } from "../ui/index.mjs";
|
||||||
|
import { ERROR_COLOR } from "../utils/UI.mjs";
|
||||||
import { hasHumansInChannel, iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
import { hasHumansInChannel, iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
||||||
import { getPlayerChannelId } from "./PlayerEventsMixin.mjs";
|
import { getPlayerChannelId } from "./PlayerEventsMixin.mjs";
|
||||||
|
|
||||||
@@ -148,7 +149,11 @@ const PlayerLifecycleMixin = {
|
|||||||
const cleanGuildId = cleanId(guildId);
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
|
||||||
if (!cleanGuildId) {
|
if (!cleanGuildId) {
|
||||||
await msg.reply(this._t(msg, "responses._common.serverOnlyForMusic")).catch(() => {});
|
const serverOnlyEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this._t(msg, "responses.join.selectVCAuthor") || "🔊 Voice Channel Setup" })
|
||||||
|
.setDescription(this._t(msg, "responses._common.serverOnlyForMusic"));
|
||||||
|
await msg.reply({ embeds: [serverOnlyEmbed] }).catch(() => {});
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,9 +176,13 @@ const PlayerLifecycleMixin = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const hint = this._t(msg, "responses._common.voiceSelectionHint");
|
const hint = this._t(msg, "responses._common.voiceSelectionHint");
|
||||||
const selectionMsg = await msg.reply(
|
const promptEmbed = new EmbedBuilder()
|
||||||
(channelSelection ? channelSelection + "\n**..or** " + hint : "Please " + hint)
|
.setColor(getGlobalColor())
|
||||||
);
|
.setAuthor({ name: this._t(msg, "responses.join.selectVCAuthor") })
|
||||||
|
.setDescription(channelSelection ? channelSelection + "\n**..or** " + hint : "Please " + hint)
|
||||||
|
.setFooter({ text: this._t(msg, "responses.join.selectVCFooter") });
|
||||||
|
|
||||||
|
const selectionMsg = await msg.reply({ embeds: [promptEmbed] });
|
||||||
|
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
let unsubscribeReactions;
|
let unsubscribeReactions;
|
||||||
@@ -187,7 +196,11 @@ const PlayerLifecycleMixin = {
|
|||||||
|
|
||||||
const timeout = setTimeout(() => {
|
const timeout = setTimeout(() => {
|
||||||
cleanup();
|
cleanup();
|
||||||
msg.reply(this._t(msg, "responses._common.voiceSelectionTimedOut"));
|
const timeoutEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this._t(msg, "responses.join.selectVCAuthor") || "🔊 Voice Channel Setup" })
|
||||||
|
.setDescription(this._t(msg, "responses._common.voiceSelectionTimedOut"));
|
||||||
|
msg.reply({ embeds: [timeoutEmbed] }).catch(() => {});
|
||||||
resolve(false);
|
resolve(false);
|
||||||
}, 30_000);
|
}, 30_000);
|
||||||
|
|
||||||
@@ -360,12 +373,14 @@ const PlayerLifecycleMixin = {
|
|||||||
} catch(e) {
|
} catch(e) {
|
||||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||||
}
|
}
|
||||||
message.reply(this._t(message, "responses.join.alreadyJoined", { channel: cid }));
|
const alreadyJoinedEmbed = new EmbedBuilder().setColor(getGlobalColor()).setAuthor({ name: this._t(message, "responses.join.connectedAuthor") }).setDescription(this._t(message, "responses.join.alreadyJoined", { channel: cid }));
|
||||||
|
message.reply({ embeds: [alreadyJoinedEmbed] });
|
||||||
return existing;
|
return existing;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (this._pendingJoins.has(cleanChannelId)) {
|
if (this._pendingJoins.has(cleanChannelId)) {
|
||||||
message.reply(this._t(message, "responses.join.joining"));
|
const pendingEmbed = new EmbedBuilder().setColor(getGlobalColor()).setAuthor({ name: this._t(message, "responses.join.connectedAuthor") }).setDescription(this._t(message, "responses.join.joining"));
|
||||||
|
message.reply({ embeds: [pendingEmbed] });
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
this._pendingJoins.add(cleanChannelId);
|
this._pendingJoins.add(cleanChannelId);
|
||||||
@@ -395,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", () => {
|
||||||
@@ -455,7 +504,13 @@ const PlayerLifecycleMixin = {
|
|||||||
? (() => { const t = { id: ch.id, type: ch.type }; t.send = (o) => autoleaveChMgr.send(ch.id, o); return t; })()
|
? (() => { const t = { id: ch.id, type: ch.type }; t.send = (o) => autoleaveChMgr.send(ch.id, o); return t; })()
|
||||||
: ch;
|
: ch;
|
||||||
if (typeof leaveCh?.send === "function") {
|
if (typeof leaveCh?.send === "function") {
|
||||||
leaveCh.send({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)], allowedMentions: { parse: [] } }).catch(err => {
|
const autoleaveEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.locale?.translate(guildId, "responses.join.autoLeaveAuthor") ?? "⏱️ Voice Watchdog • Session Inactive" })
|
||||||
|
.setTitle(this.locale?.translate(guildId, "responses.join.autoLeaveTitle") ?? "Disconnected Due to Inactivity")
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.locale?.translate(guildId, "responses.join.autoLeaveFooter", { prefix }) ?? `Keep bot in voice 24/7 with ${prefix}247` });
|
||||||
|
leaveCh.send({ embeds: [autoleaveEmbed], allowedMentions: { parse: [] } }).catch(err => {
|
||||||
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||||
logger.warn(`[PlayerManager] Cannot send autoleave message in channel ${leaveCh.id} — missing permissions`);
|
logger.warn(`[PlayerManager] Cannot send autoleave message in channel ${leaveCh.id} — missing permissions`);
|
||||||
}
|
}
|
||||||
@@ -550,14 +605,23 @@ const PlayerLifecycleMixin = {
|
|||||||
ch = asSendable(ch);
|
ch = asSendable(ch);
|
||||||
ch.send(payload).catch(err => {
|
ch.send(payload).catch(err => {
|
||||||
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||||
|
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);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const statusMsg = await message.reply(this._t(message, "responses.join.joining"));
|
const joiningEmbed = new EmbedBuilder().setColor(getGlobalColor()).setAuthor({ name: this._t(message, "responses.join.connectedAuthor") }).setDescription(this._t(message, "responses.join.joining"));
|
||||||
|
const statusMsg = await message.reply({ embeds: [joiningEmbed] }).catch(() => null);
|
||||||
try {
|
try {
|
||||||
await player.join(cid);
|
await player.join(cid);
|
||||||
|
|
||||||
@@ -565,9 +629,16 @@ const PlayerLifecycleMixin = {
|
|||||||
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||||
this._pendingJoins.delete(cleanChannelId);
|
this._pendingJoins.delete(cleanChannelId);
|
||||||
|
|
||||||
await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid }));
|
|
||||||
|
|
||||||
const guildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
const guildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
||||||
|
const prefix = this.commands?.getPrefix?.(guildId) ?? "%";
|
||||||
|
const joinedEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this._t(message, "responses.join.connectedAuthor") })
|
||||||
|
.setDescription(this._t(message, "responses.join.joined", { channel: cid }))
|
||||||
|
.setFooter({ text: this._t(message, "responses.join.playPromptFooter", { prefix }) });
|
||||||
|
|
||||||
|
await statusMsg?.edit?.({ content: null, embeds: [joinedEmbed] }).catch(() => {});
|
||||||
|
|
||||||
this._restorePlayerVolume(player, guildId);
|
this._restorePlayerVolume(player, guildId);
|
||||||
|
|
||||||
return player;
|
return player;
|
||||||
@@ -584,9 +655,15 @@ const PlayerLifecycleMixin = {
|
|||||||
|
|
||||||
this.playerMap.set(cleanChannelId, player);
|
this.playerMap.set(cleanChannelId, player);
|
||||||
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||||
await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid }));
|
|
||||||
|
|
||||||
const retryGuildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
const retryGuildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
||||||
|
const retryPrefix = this.commands?.getPrefix?.(retryGuildId) ?? "%";
|
||||||
|
const joinedEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this._t(message, "responses.join.connectedAuthor") })
|
||||||
|
.setDescription(this._t(message, "responses.join.joined", { channel: cid }))
|
||||||
|
.setFooter({ text: this._t(message, "responses.join.playPromptFooter", { prefix: retryPrefix }) });
|
||||||
|
await statusMsg?.edit?.({ content: null, embeds: [joinedEmbed] }).catch(() => {});
|
||||||
|
|
||||||
this._restorePlayerVolume(player, retryGuildId);
|
this._restorePlayerVolume(player, retryGuildId);
|
||||||
return player;
|
return player;
|
||||||
} catch (retryErr) {
|
} catch (retryErr) {
|
||||||
@@ -602,7 +679,15 @@ const PlayerLifecycleMixin = {
|
|||||||
} else {
|
} else {
|
||||||
errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message });
|
errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message });
|
||||||
}
|
}
|
||||||
await statusMsg.edit(errorMsg).catch(() => {});
|
const guildId = cleanId(channel.guildId ?? getMessageGuildId(message));
|
||||||
|
const prefix = this.commands?.getPrefix?.(guildId) ?? "%";
|
||||||
|
const errorEmbed = new EmbedBuilder()
|
||||||
|
.setColor(ERROR_COLOR)
|
||||||
|
.setAuthor({ name: this._t(message, "responses.join.joinFailedAuthor") })
|
||||||
|
.setTitle(this._t(message, "responses.join.joinFailedTitle"))
|
||||||
|
.setDescription(errorMsg)
|
||||||
|
.setFooter({ text: this._t(message, "responses.join.joinFailedFooter", { prefix }) });
|
||||||
|
await statusMsg?.edit?.({ content: null, embeds: [errorEmbed] }).catch(() => {});
|
||||||
this.playerMap.delete(cleanChannelId);
|
this.playerMap.delete(cleanChannelId);
|
||||||
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||||
player.destroy();
|
player.destroy();
|
||||||
|
|||||||
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user