mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
Remix — the complete rewrite
Upgrades the bot from fluxerjs 2.2 to 3.0 and restructures everything into a layered architecture (~28K lines): Dependencies: - @fluxerjs/core, util, voice: ^2.2.0 -> ^3.0.0 (typed events, PartialMessage payloads, camelCase API) - @fluxerjs/sharding ^3.0.0 added — built-in sharding mode (shard.mjs, one process per shard) - @discordjs/opus dropped — opusscript + prism-media cover encoding Architecture: - commands: every command split into submodules (player, lastfm, settings, debug) with a shared CommandBuilder/Loader/Handler core - ui: embeds, paginators, help command, permission checks - voice: gateway event routing, rejoin/247 boot recovery, state resolver - music: player split into Queue/Search/Playback/Display mixins, stream pipeline + WebM/Opus muxer (no FFmpeg needed) - dashboard: Redis pub/sub, RPC handlers, serializers - db: MySQL manager + per-guild settings - services: LastFm manager split into focused mixins - utils: sharding, 24/7 helpers, API client Runtime fixes over v2: - Redis v5 reconnect: capped numeric backoff (0.5s ramp to 15s), never exhausts, auto-recovers when the server comes back - Redis main/subscriber clients connect in parallel; clean shutdown - Logger storm guard: identical error/warn lines deduped in a 60s window - self-deaf fix on voice join - config example uses redis://127.0.0.1 (avoids IPv6 ENETUNREACH) Housekeeping: dead code removed (Tuna.mjs + follow-redirects dep), .gitignore added (config.json, .env, node_modules, runtime state).
This commit is contained in:
1 parent
0f085a6ae4
commit
253d11cd57
150 files changed
+19894
-16853
No files matched your search
+8
-7
@@ -1,8 +1,9 @@
|
|||||||
node_modules/
|
|
||||||
storage/data
|
|
||||||
config.json
|
config.json
|
||||||
settings.json
|
.env
|
||||||
remix-settings.json
|
storage/stats-cache.json
|
||||||
test_data/
|
storage/locales/user/
|
||||||
*.code-workspace
|
*.log
|
||||||
.idea/
|
logs/
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
.idea
|
||||||
@@ -42,6 +42,7 @@
|
|||||||
- [Dashboard Setup (Optional)](#-dashboard-setup-optional)
|
- [Dashboard Setup (Optional)](#-dashboard-setup-optional)
|
||||||
- [Configuration Reference](#-configuration-reference)
|
- [Configuration Reference](#-configuration-reference)
|
||||||
- [Project Architecture](#-project-architecture)
|
- [Project Architecture](#-project-architecture)
|
||||||
|
- [The Layered Codebase](#-the-layered-codebase)
|
||||||
- [Localization](#-localization)
|
- [Localization](#-localization)
|
||||||
- [Scripts](#-npm-scripts)
|
- [Scripts](#-npm-scripts)
|
||||||
- [Credits](#-credits--license)
|
- [Credits](#-credits--license)
|
||||||
@@ -54,6 +55,37 @@ Remix is a free and open-source music bot for [Fluxer](https://fluxer.app), buil
|
|||||||
|
|
||||||
We believe music features shouldn't be locked behind paywalls — **all commands on Remix are 100% free and always will be.**
|
We believe music features shouldn't be locked behind paywalls — **all commands on Remix are 100% free and always will be.**
|
||||||
|
|
||||||
|
### Fluxer.js 3.0
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
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).
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
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).
|
||||||
|
|
||||||
|
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
|
## How Audio Playback Works
|
||||||
@@ -67,7 +99,7 @@ Understanding the pipeline helps when debugging or contributing:
|
|||||||
├─ /v4/loadstream → magic-byte sniffing:
|
├─ /v4/loadstream → magic-byte sniffing:
|
||||||
│ • WebM (1A45DFA3) → passthrough to LiveKit
|
│ • WebM (1A45DFA3) → passthrough to LiveKit
|
||||||
│ • OggS → OggDemuxer → WebMOpusMuxer (remux, no re-encode)
|
│ • OggS → OggDemuxer → WebMOpusMuxer (remux, no re-encode)
|
||||||
│ • raw PCM → OpusEncoder (opusscript / @discordjs/opus)
|
│ • raw PCM → OpusEncoder (opusscript)
|
||||||
│ → WebMOpusMuxer → LiveKit
|
│ → WebMOpusMuxer → LiveKit
|
||||||
└─ conn.play() → @fluxerjs/voice LiveKit connection (bot publishes audio
|
└─ conn.play() → @fluxerjs/voice LiveKit connection (bot publishes audio
|
||||||
as a LiveKit participant)
|
as a LiveKit participant)
|
||||||
@@ -393,79 +425,175 @@ Key configuration options in `config.json`:
|
|||||||
|
|
||||||
```
|
```
|
||||||
fluxer/
|
fluxer/
|
||||||
├── index.mjs # Entry point — Remix class, boot sequence, alone-check,
|
├── index.mjs # Entry point — creates the Remix instance, process-level
|
||||||
│ # presence rotation, error handling, graceful shutdown
|
│ # 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
|
├── config_example.json # Configuration template
|
||||||
├── package.json
|
├── package.json
|
||||||
├── commands/ # 37 command modules (one file per command)
|
├── commands/ # 37 command entry files (one per command); the three
|
||||||
│ ├── play.mjs # Play a track or playlist (Last.fm categories, providers)
|
│ │ # largest (lastfm, settings, debug) are split into action-family
|
||||||
│ ├── player.mjs # Interactive emoji control panel with live progress
|
│ │ # modules inside commands/<name>/ subdirectories
|
||||||
│ ├── settings.mjs # Per-guild settings management (+ prefix/247 shortcuts)
|
│ ├── lastfm/ # lastfm action families (account, playback, listening,
|
||||||
│ ├── lyrics.mjs # Synced lyrics from NodeLink
|
│ │ # whoknows, info, tags, discovery, help, shared)
|
||||||
│ ├── filter.mjs # Audio filter controls
|
│ ├── settings/ # settings helpers (utils, channels247, setters)
|
||||||
│ ├── radio.mjs # Radio station management
|
│ └── debug/ # debug helpers (consts, gateway, rejoin, voiceDiagnostic)
|
||||||
│ ├── debug.mjs # Voice connection debugger (owner only)
|
├── settings/ # Settings system entry points (re-export, migrate, validators)
|
||||||
│ ├── lastfm.mjs # Last.fm linking, scrobbling, profiles, leaderboards
|
├── storage/ # Runtime data: defaults, modules.json, locales
|
||||||
│ ├── trackopt.mjs # Per-track start/end time options (set/get/remove/list)
|
|
||||||
│ └── ... # All other commands
|
|
||||||
├── src/
|
|
||||||
│ ├── CommandHandler.mjs # Command framework — builder, options, requirements,
|
|
||||||
│ │ # cooldowns, prefix manager, loader
|
|
||||||
│ ├── MessageHandler.mjs # Replies/embeds, reaction observers, pagination, help
|
|
||||||
│ ├── PlayerManager.mjs # Player lifecycle, VC resolution & permission checks,
|
|
||||||
│ │ # dashboard broadcasts, Last.fm scrobble wiring
|
|
||||||
│ ├── Player.mjs # Core per-channel player — queue, playback, filters,
|
|
||||||
│ │ # search sessions, autoplay, error circuit breaker
|
|
||||||
│ ├── FluxerAudioBridge.mjs # Audio engine — NodeLink REST streams → sniff/remux/
|
|
||||||
│ │ # encode → LiveKit publishing
|
|
||||||
│ ├── LavalinkManager.mjs # lavalink-client wrapper (NodeLink mode) — search,
|
|
||||||
│ │ # voice payload caching, node readiness
|
|
||||||
│ ├── GatewayHandler.mjs # Raw WS events, voice-state routing, guild lifecycle,
|
|
||||||
│ │ # 24/7 rejoin & rejoin retries
|
|
||||||
│ ├── LastFmManager.mjs # Last.fm API client — auth, scrobbling, user data,
|
|
||||||
│ │ # MySQL persistence (lastfm_users / lastfm_stats)
|
|
||||||
│ ├── FluxerListManager.mjs # FluxerList voters API client (5-min TTL cache)
|
|
||||||
│ ├── TrackOptionsManager.mjs # Per-user per-track start/end times (MySQL + LRU cache)
|
|
||||||
│ ├── Settings.mjs # RemoteSettingsManager — MySQL-backed per-guild settings
|
|
||||||
│ │ # with debounced JSON_SET writes
|
|
||||||
│ ├── Utils.mjs # Shared utilities (IDs, durations, markdown, progress bar)
|
|
||||||
│ ├── probe.mjs # ffprobe wrapper for audio stream info (radio metadata)
|
|
||||||
│ ├── constants/
|
|
||||||
│ │ ├── Logger.mjs # Structured logger with per-category control
|
|
||||||
│ │ ├── Locale.mjs # i18n translation engine
|
|
||||||
│ │ ├── Helpers247.mjs # 24/7 mode helpers
|
|
||||||
│ │ ├── UI.mjs # Emoji + UI constants
|
|
||||||
│ │ ├── providers.mjs # 45+ audio source provider definitions
|
|
||||||
│ │ ├── VoiceStateCache.mjs # Dual LRU voice-state caches (humans / bots)
|
|
||||||
│ │ ├── VoiceStateResolver.mjs # Voice-state normalization + humans-in-channel check
|
|
||||||
│ │ └── audio/
|
|
||||||
│ │ └── WebMOpusMuxer.mjs # Streaming EBML/Matroska muxer (Opus → WebM for LiveKit)
|
|
||||||
│ └── dashboard/
|
|
||||||
│ ├── Dashboard.mjs # Dashboard backend — Redis RPC, player/user serializers,
|
|
||||||
│ │ # remote-control actions with authorization checks
|
|
||||||
│ ├── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers
|
|
||||||
│ └── RedisHandler.mjs # Redis pub/sub RPC transport with reconnect handling
|
|
||||||
├── settings/
|
|
||||||
│ ├── Settings.mjs # Re-export of src/Settings.mjs classes
|
|
||||||
│ ├── migrate.mjs # One-shot settings table clone/repair tool
|
|
||||||
│ ├── runnables.mjs # Setting validators (prefix, pfp, stay_247)
|
|
||||||
│ └── README.md # Settings system documentation
|
|
||||||
├── docker/ # Docker self-hosting (Dockerfile, compose, entrypoint,
|
├── docker/ # Docker self-hosting (Dockerfile, compose, entrypoint,
|
||||||
│ # config templates, .env.example)
|
│ # config templates, .env.example)
|
||||||
└── storage/
|
└── src/
|
||||||
├── defaults.json # Default per-guild settings template
|
├── core/ # Bot composition
|
||||||
├── modules.json # Plugin module registry (empty by default)
|
│ ├── Bot.mjs # Remix class — boot sequence, service wiring, alone-check,
|
||||||
├── stats.json # Static counters
|
│ │ # presence rotation, WebSocket error guards
|
||||||
└── locales/bot/ # Translation files
|
│ ├── BotVoiceMixin.mjs # Voice-channel resolution, 24/7 player spawning with
|
||||||
├── en.json
|
│ │ # announcements, programmatic leave, shared servers
|
||||||
├── ar-SA.json
|
│ ├── Logger.mjs # Structured logger with per-category control
|
||||||
├── de-DE.json
|
│ └── Locale.mjs # i18n translation engine
|
||||||
├── ckb.json
|
├── commands/ # Command framework layer
|
||||||
└── pt-BR.json
|
│ ├── 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
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## The Layered Codebase
|
||||||
|
|
||||||
|
The rewrite organises the codebase into strict layers with one-way dependencies
|
||||||
|
(no layer reaches *down* past another):
|
||||||
|
|
||||||
|
```
|
||||||
|
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,
|
||||||
|
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
|
## 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.
|
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.
|
||||||
@@ -479,6 +607,7 @@ Currently supported languages:
|
|||||||
| `de-DE` | German |
|
| `de-DE` | German |
|
||||||
| `ckb` | Kurdish (Sorani) |
|
| `ckb` | Kurdish (Sorani) |
|
||||||
| `pt-BR` | Brazilian Portuguese |
|
| `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>`.
|
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>`.
|
||||||
|
|
||||||
@@ -488,7 +617,8 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the
|
|||||||
|
|
||||||
| Script | Command | Description |
|
| Script | Command | Description |
|
||||||
| :--- | :--- | :--- |
|
| :--- | :--- | :--- |
|
||||||
| `npm start` | `node index.mjs` | Start the bot |
|
| `npm start` | `node index.mjs` | Start the bot (single process — default) |
|
||||||
|
| `npm run shard` | `node shard.mjs` | Start under the sharding supervisor (optional) |
|
||||||
| `npm run dev` | `node --inspect index.mjs --trace-warnings` | Start with Node.js inspector |
|
| `npm run dev` | `node --inspect index.mjs --trace-warnings` | Start with Node.js inspector |
|
||||||
| `npm run migrate` | `node settings/migrate.mjs` | Clone/repair the remote settings table |
|
| `npm run migrate` | `node settings/migrate.mjs` | Clone/repair the remote settings table |
|
||||||
|
|
||||||
@@ -512,4 +642,3 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the
|
|||||||
© 2026 Remix. Code licensed under the <a href="LICENSE">MIT License</a>.<br>
|
© 2026 Remix. Code licensed under the <a href="LICENSE">MIT License</a>.<br>
|
||||||
<em>The Remix name, logo, and branding are proprietary and may not be reused.</em>
|
<em>The Remix name, logo, and branding are proprietary and may not be reused.</em>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -3,10 +3,10 @@
|
|||||||
* @description Toggle autoplay mode — keeps the music going forever:
|
* @description Toggle autoplay mode — keeps the music going forever:
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { logger } from "../src/constants/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. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
|
|||||||
+2
-2
@@ -3,9 +3,9 @@
|
|||||||
* @description Remove all songs from the playback queue.
|
* @description Remove all songs from the playback queue.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
|
|||||||
+9
-614
@@ -1,340 +1,16 @@
|
|||||||
/**
|
/**
|
||||||
* @module commands/debug
|
* @module commands/debug
|
||||||
* @description Owner-only debug command for voice diagnostics, ghost connection detection, and forced rejoin.
|
* @description Owner-only debug command for voice diagnostics, ghost connection
|
||||||
|
* detection, and forced rejoin. The implementations live in commands/debug/
|
||||||
|
* (gateway, rejoin, voiceDiagnostic); the builder and run() dispatch stay here.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs";
|
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { isGhostConnection } from "./debug/gateway.mjs";
|
||||||
import { getVoiceManager } from "@fluxerjs/voice";
|
import { runBatchRejoin } from "./debug/rejoin.mjs";
|
||||||
import { ERROR_COLOR, WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
import { runVoiceDiagnostic } from "./debug/voiceDiagnostic.mjs";
|
||||||
|
|
||||||
const REJOIN_DELAY_MS = 2_000;
|
|
||||||
const INTENTIONAL_LEAVE_TTL = 30_000;
|
|
||||||
const MAX_DESC = 4096;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a human-readable label for a voice room's connection state.
|
|
||||||
* @private
|
|
||||||
* @param {object|null} room - The voice room object.
|
|
||||||
* @returns {string} Connection state label.
|
|
||||||
*/
|
|
||||||
function roomStateLabel(room) {
|
|
||||||
if (!room) return "none";
|
|
||||||
const cs = room.connectionState;
|
|
||||||
if (cs === 0 || cs === "CONN_DISCONNECTED") return "disconnected(0)";
|
|
||||||
if (cs === 1 || cs === "CONN_CONNECTED") return "connected(1)";
|
|
||||||
if (cs === 2) return room.isConnected ? "connected(2)" : "reconnecting(2)";
|
|
||||||
if (cs === "CONN_RECONNECTING") return "reconnecting";
|
|
||||||
if (cs === 3) return "reconnecting(3)";
|
|
||||||
if (cs === 4) return "signal_reconnecting(4)";
|
|
||||||
if (typeof cs === "string") return cs;
|
|
||||||
return String(cs);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a player has a ghost connection (appears in voice but WebSocket is dead).
|
|
||||||
* @private
|
|
||||||
* @param {object} player - The player instance.
|
|
||||||
* @returns {boolean} True if the player has a ghost connection.
|
|
||||||
*/
|
|
||||||
function isGhostConnection(player) {
|
|
||||||
const conn = player.connection;
|
|
||||||
if (!conn) return false;
|
|
||||||
if (player._destroyed || player.leaving || player._isJoining) return false;
|
|
||||||
|
|
||||||
const room = conn.room;
|
|
||||||
if (!room) {
|
|
||||||
return !conn._destroyed;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!room.isConnected) return true;
|
|
||||||
|
|
||||||
const cs = room.connectionState;
|
|
||||||
if (cs === 0 || cs === "CONN_DISCONNECTED") return true;
|
|
||||||
if (cs === "CONN_RECONNECTING" || cs === 3 || cs === 4) return true;
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the bot's voice channel state from the Discord gateway cache.
|
|
||||||
* @private
|
|
||||||
* @param {object} client - The Discord client instance.
|
|
||||||
* @param {string} guildId - The guild ID to check.
|
|
||||||
* @returns {{ userId: string, channelId: string }|null} Bot's voice state or null.
|
|
||||||
*/
|
|
||||||
function getBotGatewayVoiceState(client, guildId) {
|
|
||||||
const botId = client.user?.id;
|
|
||||||
if (!botId || !guildId) return null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const vm = getVoiceManager(client);
|
|
||||||
if (vm?.voiceStates) {
|
|
||||||
const cleanGuild = cleanId(guildId);
|
|
||||||
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
|
|
||||||
if (guildVoiceMap && typeof guildVoiceMap.get === "function") {
|
|
||||||
const channelId = guildVoiceMap.get(botId);
|
|
||||||
if (channelId) return { userId: botId, channelId: cleanId(channelId) };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (VoiceManager):", e?.message); }
|
|
||||||
|
|
||||||
try {
|
|
||||||
const cleanGuild = cleanId(guildId);
|
|
||||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
|
||||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
|
||||||
if (!voiceStates) return null;
|
|
||||||
|
|
||||||
const entries = Array.isArray(voiceStates)
|
|
||||||
? voiceStates
|
|
||||||
: typeof voiceStates.values === "function"
|
|
||||||
? [...voiceStates.values()]
|
|
||||||
: Object.entries(voiceStates).map(([uid, val]) => {
|
|
||||||
if (typeof val === "string") return { user_id: uid, channel_id: val };
|
|
||||||
const obj = typeof val === "object" && val !== null ? val : {};
|
|
||||||
return { user_id: uid, channel_id: obj.channelId ?? obj.channel_id ?? null, ...obj };
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const state of entries) {
|
|
||||||
const uid = state?.user_id ?? state?.userId ?? state?.id;
|
|
||||||
if (uid === botId) {
|
|
||||||
const chId = state?.channel_id ?? state?.channelId ?? null;
|
|
||||||
if (chId) return { userId: botId, channelId: cleanId(chId) };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (guild cache):", e?.message); }
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if the gateway voice state is stale (mismatches the player's channel).
|
|
||||||
* @private
|
|
||||||
* @param {object} client - The Discord client instance.
|
|
||||||
* @param {object} player - The player instance.
|
|
||||||
* @returns {boolean} True if the gateway presence is stale.
|
|
||||||
*/
|
|
||||||
function isStaleGatewayPresence(client, player) {
|
|
||||||
const guildId = player._guildId ?? player._resolveGuildId?.();
|
|
||||||
if (!guildId) return false;
|
|
||||||
|
|
||||||
const gatewayState = getBotGatewayVoiceState(client, guildId);
|
|
||||||
if (!gatewayState) return false;
|
|
||||||
|
|
||||||
const playerChannel = cleanId(player._channelId ?? player._home247Channel);
|
|
||||||
const gatewayChannel = gatewayState.channelId;
|
|
||||||
|
|
||||||
return !playerChannel || playerChannel !== gatewayChannel;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build a human-readable label for a player (guild name / #channel name).
|
|
||||||
* @private
|
|
||||||
* @param {object} client - The Discord client instance.
|
|
||||||
* @param {string} channelId - The voice channel ID.
|
|
||||||
* @param {object} player - The player instance.
|
|
||||||
* @returns {string} Formatted label string.
|
|
||||||
*/
|
|
||||||
function buildPlayerLabel(client, channelId, player) {
|
|
||||||
const channel = client.channels.get(channelId);
|
|
||||||
const gId = player._guildId ?? channel?.guildId;
|
|
||||||
const guild = gId ? client.guilds.get(cleanId(gId)) : null;
|
|
||||||
return `${guild?.name ?? "unknown"} / #${channel?.name ?? channelId}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Force a player to leave and rejoin, restoring queue and playback state.
|
|
||||||
* @private
|
|
||||||
* @async
|
|
||||||
* @param {object} ctx - The bot (Remix) instance context.
|
|
||||||
* @param {object} player - The player to rejoin.
|
|
||||||
* @returns {Promise<object>} Result object with success status, room state, and details.
|
|
||||||
*/
|
|
||||||
async function forceRejoinPlayer(ctx, player) {
|
|
||||||
const channelId = player._channelId ?? player._home247Channel;
|
|
||||||
const guildId = player._guildId ?? player._resolveGuildId?.();
|
|
||||||
if (!channelId || !guildId) return { success: false, reason: "no channel or guild id" };
|
|
||||||
|
|
||||||
const cleanChannelId = cleanId(channelId);
|
|
||||||
const cleanGuildId = cleanId(guildId);
|
|
||||||
|
|
||||||
const currentTrack = player.queue?.getCurrent();
|
|
||||||
const queueTracks = player.queue?.data ? [...player.queue.data] : [];
|
|
||||||
const wasPaused = player._paused;
|
|
||||||
const wasAutoplay = player._autoplay;
|
|
||||||
const wasLoop = player.queue?.loop ?? false;
|
|
||||||
const wasSongLoop = player.queue?.songLoop ?? false;
|
|
||||||
const savedVolume = player.preferredVolume ?? 1;
|
|
||||||
const savedFilter = player.activeFilter ?? null;
|
|
||||||
const savedFilterPayload = player.activeFilterPayload ?? null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL);
|
|
||||||
|
|
||||||
ctx.players.playerMap.delete(cleanChannelId);
|
|
||||||
ctx.players._unindexPlayer?.(cleanGuildId, cleanChannelId);
|
|
||||||
|
|
||||||
const altIds = [player._channelId, player._home247Channel]
|
|
||||||
.filter(Boolean)
|
|
||||||
.map(id => cleanId(id))
|
|
||||||
.filter(id => id !== cleanChannelId);
|
|
||||||
for (const altId of altIds) {
|
|
||||||
ctx.players.playerMap.delete(altId);
|
|
||||||
ctx.players._unindexPlayer?.(cleanGuildId, altId);
|
|
||||||
}
|
|
||||||
|
|
||||||
const pendingScrobble = ctx.players._pendingScrobbleTimers?.get(cleanChannelId);
|
|
||||||
if (pendingScrobble) {
|
|
||||||
clearTimeout(pendingScrobble.timer);
|
|
||||||
ctx.players._pendingScrobbleTimers.delete(cleanChannelId);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.players._pendingJoins?.delete?.(cleanChannelId);
|
|
||||||
|
|
||||||
if (player.connection) {
|
|
||||||
try { player.connection.removeAllListeners(); } catch (e) { logger.warn("[Debug] connection listener removal:", e?.message); }
|
|
||||||
try { await player.connection.disconnect(); } catch (e) { logger.warn("[Debug] connection disconnect:", e?.message); }
|
|
||||||
}
|
|
||||||
|
|
||||||
try { await player.leave(); } catch (e) { logger.warn("[Debug] player leave:", e?.message); }
|
|
||||||
try { player.destroy(); } catch (e) { logger.warn("[Debug] player destroy:", e?.message); }
|
|
||||||
|
|
||||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
|
||||||
|
|
||||||
const newPlayer = await ctx._spawnPlayer(cleanGuildId, cleanChannelId);
|
|
||||||
|
|
||||||
if (!newPlayer) {
|
|
||||||
return { success: false, reason: "_spawnPlayer returned null", channelId: cleanChannelId };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (newPlayer.preferredVolume !== savedVolume) {
|
|
||||||
newPlayer.setVolume(savedVolume);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (wasLoop) newPlayer.queue?.setLoop?.(true);
|
|
||||||
if (wasSongLoop) newPlayer.queue?.setSongLoop?.(true);
|
|
||||||
|
|
||||||
if (savedFilter && savedFilterPayload) {
|
|
||||||
newPlayer.activeFilter = savedFilter;
|
|
||||||
newPlayer.activeFilterPayload = savedFilterPayload;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (currentTrack && newPlayer.queue) {
|
|
||||||
try {
|
|
||||||
newPlayer.queue.data = queueTracks;
|
|
||||||
newPlayer.queue.current = null;
|
|
||||||
await newPlayer.playNext();
|
|
||||||
if (wasPaused) newPlayer.pause();
|
|
||||||
} catch (e) { logger.warn("[Debug] queue restore:", e?.message); }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (wasAutoplay) {
|
|
||||||
newPlayer._autoplay = true;
|
|
||||||
newPlayer._autoplayHistory = player._autoplayHistory ?? [];
|
|
||||||
try {
|
|
||||||
const { attachAutoplay } = await import("./autoplay.mjs");
|
|
||||||
attachAutoplay(newPlayer, ctx);
|
|
||||||
} catch (e) {
|
|
||||||
logger.warn("[Debug] autoplay re-attach failed:", e?.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const newRoom = newPlayer.connection?.room;
|
|
||||||
return {
|
|
||||||
success: !!(newPlayer.connection && newRoom?.isConnected),
|
|
||||||
roomConnected: newRoom?.isConnected ?? false,
|
|
||||||
roomState: roomStateLabel(newRoom),
|
|
||||||
resumedPlayback: !!(currentTrack && newPlayer.queue?.getCurrent()),
|
|
||||||
channelId: cleanChannelId,
|
|
||||||
};
|
|
||||||
} catch (err) {
|
|
||||||
logger.warn("[Debug] forceRejoinPlayer error:", err?.message);
|
|
||||||
return { success: false, reason: err.message, channelId: cleanChannelId };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Process a batch of players for force-rejoin, updating a status message with progress.
|
|
||||||
* @private
|
|
||||||
* @async
|
|
||||||
* @param {object} ctx - The bot (Remix) instance context.
|
|
||||||
* @param {Array} entries - Array of [channelId, player] tuples.
|
|
||||||
* @param {object} statusMsg - The message to update with progress.
|
|
||||||
* @param {string} title - The title for the progress display.
|
|
||||||
* @returns {Promise<object[]>} Array of rejoin results.
|
|
||||||
*/
|
|
||||||
async function processRejoinBatch(ctx, entries, statusMsg, title) {
|
|
||||||
const results = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < entries.length; i++) {
|
|
||||||
const [cid, player] = entries[i];
|
|
||||||
const label = buildPlayerLabel(ctx.client, cid, player);
|
|
||||||
|
|
||||||
const progressLines = [
|
|
||||||
`🔄 **${title}** — Processing ${i + 1}/${entries.length}`,
|
|
||||||
`Currently rejoining: \`${label}\``,
|
|
||||||
``,
|
|
||||||
];
|
|
||||||
for (let j = 0; j < results.length; j++) {
|
|
||||||
const r = results[j];
|
|
||||||
const icon = r.success ? "✅" : "❌";
|
|
||||||
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(() => {});
|
|
||||||
|
|
||||||
const result = await forceRejoinPlayer(ctx, player);
|
|
||||||
result.label = label;
|
|
||||||
results.push(result);
|
|
||||||
|
|
||||||
if (i < entries.length - 1) {
|
|
||||||
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return results;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build the final embed summarizing rejoin results.
|
|
||||||
* @private
|
|
||||||
* @param {object[]} results - Array of rejoin result objects.
|
|
||||||
* @param {string} title - The title for the embed.
|
|
||||||
* @param {string} noun - The noun describing the rejoin targets.
|
|
||||||
* @returns {object} Message payload with embed.
|
|
||||||
*/
|
|
||||||
function buildRejoinResultEmbed(results, title, noun) {
|
|
||||||
const resultLines = [
|
|
||||||
`🔄 **${title} Complete**`,
|
|
||||||
`${noun.charAt(0).toUpperCase() + noun.slice(1)} processed: **${results.length}**`,
|
|
||||||
``,
|
|
||||||
];
|
|
||||||
|
|
||||||
let rejoinedCount = 0;
|
|
||||||
let resumedCount = 0;
|
|
||||||
let failedCount = 0;
|
|
||||||
|
|
||||||
for (const r of results) {
|
|
||||||
if (r.success) {
|
|
||||||
rejoinedCount++;
|
|
||||||
if (r.resumedPlayback) resumedCount++;
|
|
||||||
resultLines.push(`✅ \`${r.label}\` — rejoined (room:${r.roomState}, playback:${r.resumedPlayback ? "resumed" : "no track"})`);
|
|
||||||
} else {
|
|
||||||
failedCount++;
|
|
||||||
resultLines.push(`❌ \`${r.label}\` — failed${r.reason ? ` (${r.reason})` : ""}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (failedCount === 0) {
|
|
||||||
resultLines.push("", `All **${rejoinedCount}** ${noun} restored.${resumedCount > 0 ? ` ${resumedCount} had playback resumed.` : ""}`);
|
|
||||||
} else {
|
|
||||||
resultLines.push("", `⚠️ **${failedCount}** ${noun} could not be restored.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
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))] };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
@@ -351,6 +27,7 @@ export const command = new CommandBuilder()
|
|||||||
.addChoices("voice", "voice-rejoin", "247-rejoin")
|
.addChoices("voice", "voice-rejoin", "247-rejoin")
|
||||||
.setRequired(true));
|
.setRequired(true));
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run handler for the debug command.
|
* Run handler for the debug command.
|
||||||
* Routes to the appropriate debug subcommand based on the target option.
|
* Routes to the appropriate debug subcommand based on the target option.
|
||||||
@@ -385,285 +62,3 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Run a batch rejoin operation on matching players.
|
|
||||||
* @private
|
|
||||||
* @async
|
|
||||||
* @param {object} msg - The command message wrapper.
|
|
||||||
* @param {string} key - Identifier key for the rejoin type.
|
|
||||||
* @param {string} title - Display title for the operation.
|
|
||||||
* @param {string} noun - Noun describing the targets.
|
|
||||||
* @param {Function} filter - Function to filter which players to rejoin.
|
|
||||||
* @param {boolean} [showHintIfEmpty=false] - Whether to show a hint if no matches found.
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = false) {
|
|
||||||
const allPlayers = [...this.players.playerMap.entries()];
|
|
||||||
const matching = allPlayers.filter(([, player]) => filter(player));
|
|
||||||
|
|
||||||
if (matching.length === 0) {
|
|
||||||
const has247 = allPlayers.some(([, player]) => player._home247Channel);
|
|
||||||
const hintLine = showHintIfEmpty && has247
|
|
||||||
? `\n\n💡 No ghosts auto-detected, but 24/7 channels with dead WebSockets may still report as "connected".\nUse \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`
|
|
||||||
: "";
|
|
||||||
const embed = new EmbedBuilder()
|
|
||||||
.setColor(SUCCESS_COLOR)
|
|
||||||
.setTitle(`Debug — ${title}`)
|
|
||||||
.setDescription(`No ${noun} found. All voice connections appear healthy.${hintLine}`)
|
|
||||||
;
|
|
||||||
return msg.reply({ embeds: [embed] });
|
|
||||||
}
|
|
||||||
|
|
||||||
const statusLines = [
|
|
||||||
`🔄 **${title}** — Found **${matching.length}** ${noun}`,
|
|
||||||
`Destroying stale connections and respawning fresh players...`,
|
|
||||||
``,
|
|
||||||
];
|
|
||||||
|
|
||||||
for (let i = 0; i < matching.length; i++) {
|
|
||||||
const [cid, player] = matching[i];
|
|
||||||
const label = buildPlayerLabel(this.client, cid, player);
|
|
||||||
const ghost = isGhostConnection(player) ? " 👻GHOST" : "";
|
|
||||||
const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none";
|
|
||||||
const connectedLabel = player.connection?.room?.isConnected ? "yes" : "no";
|
|
||||||
statusLines.push(`${i + 1}. \`${label}\` — room:${roomLabel} isConnected:${connectedLabel}${ghost}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const statusEmbed = new EmbedBuilder()
|
|
||||||
.setColor(WARN_COLOR)
|
|
||||||
.setTitle(`Debug — ${title}`)
|
|
||||||
.setDescription(statusLines.join("\n").slice(0, MAX_DESC))
|
|
||||||
;
|
|
||||||
const statusMsg = await msg.reply({ embeds: [statusEmbed] });
|
|
||||||
|
|
||||||
const results = await processRejoinBatch(this, matching, statusMsg, title);
|
|
||||||
|
|
||||||
const finalPayload = buildRejoinResultEmbed(results, title, noun);
|
|
||||||
await statusMsg.edit(finalPayload).catch(() => {
|
|
||||||
msg.reply(finalPayload);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Run a full voice diagnostic, displaying player states and ghost connections.
|
|
||||||
* @private
|
|
||||||
* @async
|
|
||||||
* @param {object} msg - The command message wrapper.
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async function runVoiceDiagnostic(msg) {
|
|
||||||
const servers = [...this.players.playerMap.entries()].map(([cid, s]) => {
|
|
||||||
const channel = this.client.channels.get(cid);
|
|
||||||
const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id;
|
|
||||||
const guild = guildId ? this.client.guilds.get(cleanId(guildId)) : null;
|
|
||||||
const conn = s.connection;
|
|
||||||
const room = conn?.room;
|
|
||||||
const ghost = isGhostConnection(s);
|
|
||||||
const staleGateway = ghost ? isStaleGatewayPresence(this.client, s) : false;
|
|
||||||
const gatewayVoiceState = getBotGatewayVoiceState(this.client, guildId);
|
|
||||||
return {
|
|
||||||
name: channel?.name ?? "unknown",
|
|
||||||
id: channel?.id ?? cid,
|
|
||||||
channelId: s._channelId ?? cid,
|
|
||||||
guildId: guildId ?? "unknown",
|
|
||||||
guildname: guild?.name ?? channel?.guild?.name ?? "unknown",
|
|
||||||
conn: conn ? "yes" : "null",
|
|
||||||
connDestroyed: conn?._destroyed ?? null,
|
|
||||||
roomConnected: room?.isConnected ?? null,
|
|
||||||
roomState: roomStateLabel(room),
|
|
||||||
mediaPlayer: !!s._mediaPlayer && !s._mediaPlayer?.destroyed ? "alive" : (s._mediaPlayer?.destroyed ? "destroyed" : "none"),
|
|
||||||
destroyed: s._destroyed ?? false,
|
|
||||||
leaving: s.leaving ?? false,
|
|
||||||
joining: s._isJoining ?? false,
|
|
||||||
recovering: s._isRecovering ?? false,
|
|
||||||
paused: s._paused ?? false,
|
|
||||||
hasQueue: !!(s.queue?.getCurrent() || !s.queue?.isEmpty()),
|
|
||||||
home247: s._home247Channel ?? null,
|
|
||||||
ghost,
|
|
||||||
staleGateway,
|
|
||||||
gatewayVoiceChannel: gatewayVoiceState?.channelId ?? null,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
const pending = [...(this.players._pendingJoins ?? [])];
|
|
||||||
|
|
||||||
const ghostConnections = servers.filter(s => s.ghost);
|
|
||||||
const livePlayers = servers.filter(s => s.conn === "yes" && !s.destroyed && !s.leaving);
|
|
||||||
const actuallyConnected = livePlayers.filter(s => !s.ghost);
|
|
||||||
const channels247 = servers.filter(s => s.home247);
|
|
||||||
|
|
||||||
const summary = {
|
|
||||||
playerMapSize: this.players.playerMap.size,
|
|
||||||
livePlayers: livePlayers.length,
|
|
||||||
actuallyConnected: actuallyConnected.length,
|
|
||||||
ghostConnections: ghostConnections.length,
|
|
||||||
channels247: channels247.length,
|
|
||||||
pendingJoins: pending.length,
|
|
||||||
pendingChannels: pending,
|
|
||||||
};
|
|
||||||
|
|
||||||
const pages = [];
|
|
||||||
|
|
||||||
const summaryLines = [
|
|
||||||
`📊 **Summary**`,
|
|
||||||
`Players in map: **${summary.playerMapSize}**`,
|
|
||||||
`Live players: **${summary.livePlayers}**`,
|
|
||||||
`Actually connected: **${summary.actuallyConnected}**`,
|
|
||||||
`Ghost connections: **${summary.ghostConnections}**`,
|
|
||||||
`24/7 channels: **${summary.channels247}**`,
|
|
||||||
`Pending joins: **${summary.pendingJoins}**${summary.pendingChannels.length ? ` (\`${summary.pendingChannels.join("`, `")}\`)` : ""}`,
|
|
||||||
];
|
|
||||||
|
|
||||||
if (ghostConnections.length > 0) {
|
|
||||||
summaryLines.push("", `👻 **Ghost Connections (${ghostConnections.length}):**`, "These players *appear* in voice but their WebSocket/LiveKit room is dead:");
|
|
||||||
summaryLines.push(`Use \`%debug voice-rejoin\` to rejoin detected ghosts, or \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`);
|
|
||||||
for (const g of ghostConnections) {
|
|
||||||
const gatewayInfo = g.staleGateway
|
|
||||||
? `gateway:stale(ch:${g.gatewayVoiceChannel ?? "?"})`
|
|
||||||
: `gateway:present(ch:${g.gatewayVoiceChannel ?? "?"})`;
|
|
||||||
const detail = ` 👻 \`${g.guildname}\` / \`#${g.name}\` — room:${g.roomState} connected:${g.roomConnected} media:${g.mediaPlayer} ${gatewayInfo} 247:${g.home247 ?? "no"}`;
|
|
||||||
if (summaryLines.join("\n").length + detail.length + 1 > MAX_DESC - 60) {
|
|
||||||
summaryLines.push(` … and more ghosts (see JSON details)`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
summaryLines.push(detail);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (channels247.length > 0 && ghostConnections.length === 0) {
|
|
||||||
summaryLines.push("", `ℹ️ **24/7 Channels (${channels247.length}):**`, `WebSocket deaths can leave 24/7 channels as invisible ghosts (room reports healthy but transport is dead).`);
|
|
||||||
summaryLines.push(`Use \`%debug 247-rejoin\` to force-rejoin all 24/7 channels if you suspect ghost connections.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
summaryLines.push("", "**Players:**");
|
|
||||||
for (let i = 0; i < servers.length; i++) {
|
|
||||||
const s = servers[i];
|
|
||||||
let status;
|
|
||||||
if (s.ghost) {
|
|
||||||
status = "👻";
|
|
||||||
} else if (s.conn === "yes" && !s.destroyed && !s.leaving) {
|
|
||||||
status = "🟢";
|
|
||||||
} else {
|
|
||||||
status = "🔴";
|
|
||||||
}
|
|
||||||
const ghostTag = s.ghost ? " ⚠️GHOST" : "";
|
|
||||||
const staleTag = s.staleGateway ? " ⚠️STALE_GW" : "";
|
|
||||||
const tag247 = s.home247 ? " 🔄247" : "";
|
|
||||||
const line = `${status} \`${s.guildname}\` / \`#${s.name}\` — conn:${s.conn} room:${s.roomState} connected:${s.roomConnected} media:${s.mediaPlayer}${ghostTag}${staleTag}${tag247}`;
|
|
||||||
if (summaryLines.join("\n").length + line.length + 1 > MAX_DESC - 30) {
|
|
||||||
summaryLines.push(`… and ${servers.length - i} more (see next pages)`);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
summaryLines.push(line);
|
|
||||||
}
|
|
||||||
pages.push(summaryLines.join("\n"));
|
|
||||||
|
|
||||||
let groupJson = "";
|
|
||||||
for (let i = 0; i < servers.length; i++) {
|
|
||||||
const singleJson = JSON.stringify(servers[i], null, 2);
|
|
||||||
const candidate = groupJson
|
|
||||||
? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1)
|
|
||||||
: singleJson;
|
|
||||||
|
|
||||||
const candidateLen = ("```json\n" + candidate + "\n```").length;
|
|
||||||
|
|
||||||
if (candidateLen > MAX_DESC && groupJson) {
|
|
||||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
|
||||||
groupJson = singleJson;
|
|
||||||
} else if (candidateLen > MAX_DESC) {
|
|
||||||
const budget = MAX_DESC - 12;
|
|
||||||
pages.push(("```json\n" + singleJson.slice(0, budget) + "\n```").slice(0, MAX_DESC));
|
|
||||||
groupJson = "";
|
|
||||||
} else {
|
|
||||||
groupJson = candidate;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (groupJson) {
|
|
||||||
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pages.length === 1) {
|
|
||||||
const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor();
|
|
||||||
const embed = new EmbedBuilder()
|
|
||||||
.setColor(embedColor)
|
|
||||||
.setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""))
|
|
||||||
.setDescription(pages[0].slice(0, MAX_DESC))
|
|
||||||
;
|
|
||||||
return msg.reply({ embeds: [embed] });
|
|
||||||
}
|
|
||||||
|
|
||||||
const totalPages = pages.length;
|
|
||||||
let currentPage = 0;
|
|
||||||
|
|
||||||
const buildPage = (pageIdx, expired = false) => {
|
|
||||||
const isSummaryPage = pageIdx === 0;
|
|
||||||
const pageLabel = isSummaryPage
|
|
||||||
? "Summary"
|
|
||||||
: `Player Detail${pages[pageIdx].split(`"name":`).length - 1 > 1 ? "s" : ""}`;
|
|
||||||
const footerText = expired
|
|
||||||
? this.t(msg, "responses._common.controlsExpired")
|
|
||||||
: `${this.t(msg, "responses.debug.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`;
|
|
||||||
|
|
||||||
const embedColor = (isSummaryPage && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor();
|
|
||||||
const titleSuffix = (isSummaryPage && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "";
|
|
||||||
|
|
||||||
const embed = new EmbedBuilder()
|
|
||||||
.setColor(embedColor)
|
|
||||||
.setTitle(this.t(msg, "responses.debug.voiceTitle") + titleSuffix + ` — ${pageLabel}`)
|
|
||||||
.setDescription(pages[pageIdx].slice(0, MAX_DESC))
|
|
||||||
.setFooter({ text: footerText })
|
|
||||||
;
|
|
||||||
return { embeds: [embed] };
|
|
||||||
};
|
|
||||||
|
|
||||||
const replyMsg = await msg.reply(buildPage(0));
|
|
||||||
if (!replyMsg?.message) return;
|
|
||||||
|
|
||||||
const navEmojis = ["⬅️", "➡️", "❌"];
|
|
||||||
for (const emoji of navEmojis) {
|
|
||||||
await replyMsg.message.react(emoji).catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
const clearReactions = async () => {
|
|
||||||
try {
|
|
||||||
await replyMsg.message.removeAllReactions();
|
|
||||||
} catch (e) {
|
|
||||||
for (const emoji of navEmojis) {
|
|
||||||
try { await replyMsg.message.removeReaction(emoji); } catch (err) { logger.warn("[Debug] removeReaction fallback:", err?.message); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let emojiTimeout;
|
|
||||||
const resetTimer = () => {
|
|
||||||
clearTimeout(emojiTimeout);
|
|
||||||
emojiTimeout = setTimeout(async () => {
|
|
||||||
unobserve?.();
|
|
||||||
await clearReactions();
|
|
||||||
await replyMsg.edit(buildPage(currentPage, true)).catch(() => {});
|
|
||||||
}, EMOJI_REMOVE_TIMEOUT);
|
|
||||||
};
|
|
||||||
|
|
||||||
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
|
||||||
const emoji = e?.emoji_id ?? e?.emoji?.id ?? e?.emoji;
|
|
||||||
|
|
||||||
if (emoji === "❌") {
|
|
||||||
clearTimeout(emojiTimeout);
|
|
||||||
unobserve?.();
|
|
||||||
await replyMsg.message.delete().catch(() => {});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
resetTimer();
|
|
||||||
|
|
||||||
if (emoji === "⬅️") {
|
|
||||||
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
|
||||||
} else if (emoji === "➡️") {
|
|
||||||
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
|
||||||
});
|
|
||||||
|
|
||||||
resetTimer();
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/debug/consts
|
||||||
|
* @description Shared timing and embed-size constants for the debug command
|
||||||
|
* modules. Verbatim from the original single-file command; only `export `
|
||||||
|
* prefixes added.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const REJOIN_DELAY_MS = 2_000;
|
||||||
|
export const INTENTIONAL_LEAVE_TTL = 30_000;
|
||||||
|
export const MAX_DESC = 4096;
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/debug/gateway
|
||||||
|
* @description Gateway/voice state inspection helpers (room labels, ghost detection, bot gateway voice state, stale presence, player labels). Verbatim from the original single-file command.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
import { cleanId } from "../../src/ui/index.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a human-readable label for a voice room's connection state.
|
||||||
|
* @private
|
||||||
|
* @param {object|null} room - The voice room object.
|
||||||
|
* @returns {string} Connection state label.
|
||||||
|
*/
|
||||||
|
export function roomStateLabel(room) {
|
||||||
|
if (!room) return "none";
|
||||||
|
const cs = room.connectionState;
|
||||||
|
if (cs === 0 || cs === "CONN_DISCONNECTED") return "disconnected(0)";
|
||||||
|
if (cs === 1 || cs === "CONN_CONNECTED") return "connected(1)";
|
||||||
|
if (cs === 2) return room.isConnected ? "connected(2)" : "reconnecting(2)";
|
||||||
|
if (cs === "CONN_RECONNECTING") return "reconnecting";
|
||||||
|
if (cs === 3) return "reconnecting(3)";
|
||||||
|
if (cs === 4) return "signal_reconnecting(4)";
|
||||||
|
if (typeof cs === "string") return cs;
|
||||||
|
return String(cs);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Check if a player has a ghost connection (appears in voice but WebSocket is dead).
|
||||||
|
* @private
|
||||||
|
* @param {object} player - The player instance.
|
||||||
|
* @returns {boolean} True if the player has a ghost connection.
|
||||||
|
*/
|
||||||
|
export function isGhostConnection(player) {
|
||||||
|
const conn = player.connection;
|
||||||
|
if (!conn) return false;
|
||||||
|
if (player._destroyed || player.leaving || player._isJoining) return false;
|
||||||
|
|
||||||
|
const room = conn.room;
|
||||||
|
if (!room) {
|
||||||
|
return !conn._destroyed;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!room.isConnected) return true;
|
||||||
|
|
||||||
|
const cs = room.connectionState;
|
||||||
|
if (cs === 0 || cs === "CONN_DISCONNECTED") return true;
|
||||||
|
if (cs === "CONN_RECONNECTING" || cs === 3 || cs === 4) return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Get the bot's voice channel state from the gateway cache.
|
||||||
|
* @private
|
||||||
|
* @param {object} client - The client instance.
|
||||||
|
* @param {string} guildId - The guild ID to check.
|
||||||
|
* @returns {{ userId: string, channelId: string }|null} Bot's voice state or null.
|
||||||
|
*/
|
||||||
|
export function getBotGatewayVoiceState(client, guildId) {
|
||||||
|
const botId = client.user?.id;
|
||||||
|
if (!botId || !guildId) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const vm = getVoiceManager(client);
|
||||||
|
if (vm?.voiceStates) {
|
||||||
|
const cleanGuild = cleanId(guildId);
|
||||||
|
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
|
||||||
|
if (guildVoiceMap && typeof guildVoiceMap.get === "function") {
|
||||||
|
const channelId = guildVoiceMap.get(botId);
|
||||||
|
if (channelId) return { userId: botId, channelId: cleanId(channelId) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (VoiceManager):", e?.message); }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const cleanGuild = cleanId(guildId);
|
||||||
|
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||||
|
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
||||||
|
if (!voiceStates) return null;
|
||||||
|
|
||||||
|
const entries = Array.isArray(voiceStates)
|
||||||
|
? voiceStates
|
||||||
|
: typeof voiceStates.values === "function"
|
||||||
|
? [...voiceStates.values()]
|
||||||
|
: Object.entries(voiceStates).map(([uid, val]) => {
|
||||||
|
if (typeof val === "string") return { user_id: uid, channel_id: val };
|
||||||
|
const obj = typeof val === "object" && val !== null ? val : {};
|
||||||
|
return { user_id: uid, channel_id: obj.channelId ?? obj.channel_id ?? null, ...obj };
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const state of entries) {
|
||||||
|
const uid = state?.user_id ?? state?.userId ?? state?.id;
|
||||||
|
if (uid === botId) {
|
||||||
|
const chId = state?.channel_id ?? state?.channelId ?? null;
|
||||||
|
if (chId) return { userId: botId, channelId: cleanId(chId) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (guild cache):", e?.message); }
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Check if the gateway voice state is stale (mismatches the player's channel).
|
||||||
|
* @private
|
||||||
|
* @param {object} client - The client instance.
|
||||||
|
* @param {object} player - The player instance.
|
||||||
|
* @returns {boolean} True if the gateway presence is stale.
|
||||||
|
*/
|
||||||
|
export function isStaleGatewayPresence(client, player) {
|
||||||
|
const guildId = player._guildId ?? player._resolveGuildId?.();
|
||||||
|
if (!guildId) return false;
|
||||||
|
|
||||||
|
const gatewayState = getBotGatewayVoiceState(client, guildId);
|
||||||
|
if (!gatewayState) return false;
|
||||||
|
|
||||||
|
const playerChannel = cleanId(player._channelId ?? player._home247Channel);
|
||||||
|
const gatewayChannel = gatewayState.channelId;
|
||||||
|
|
||||||
|
return !playerChannel || playerChannel !== gatewayChannel;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Build a human-readable label for a player (guild name / #channel name).
|
||||||
|
* @private
|
||||||
|
* @param {object} client - The client instance.
|
||||||
|
* @param {string} channelId - The voice channel ID.
|
||||||
|
* @param {object} player - The player instance.
|
||||||
|
* @returns {string} Formatted label string.
|
||||||
|
*/
|
||||||
|
export function buildPlayerLabel(client, channelId, player) {
|
||||||
|
const channel = client.channels.get(channelId);
|
||||||
|
const gId = player._guildId ?? channel?.guildId;
|
||||||
|
const guild = gId ? client.guilds.get(cleanId(gId)) : null;
|
||||||
|
return `${guild?.name ?? "unknown"} / #${channel?.name ?? channelId}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/debug/rejoin
|
||||||
|
* @description Force-rejoin machinery for the debug command (forceRejoinPlayer, batch processing, result embed, runBatchRejoin entry). Verbatim from the original single-file command; the relative dynamic import of autoplay.mjs was adjusted for the deeper directory.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
import { cleanId } from "../../src/ui/index.mjs";
|
||||||
|
import { WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR } from "../../src/utils/UI.mjs";
|
||||||
|
import { REJOIN_DELAY_MS, INTENTIONAL_LEAVE_TTL, MAX_DESC } from "./consts.mjs";
|
||||||
|
import { roomStateLabel, isGhostConnection, buildPlayerLabel } from "./gateway.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Force a player to leave and rejoin, restoring queue and playback state.
|
||||||
|
* @private
|
||||||
|
* @async
|
||||||
|
* @param {object} ctx - The bot (Remix) instance context.
|
||||||
|
* @param {object} player - The player to rejoin.
|
||||||
|
* @returns {Promise<object>} Result object with success status, room state, and details.
|
||||||
|
*/
|
||||||
|
async function forceRejoinPlayer(ctx, player) {
|
||||||
|
const channelId = player._channelId ?? player._home247Channel;
|
||||||
|
const guildId = player._guildId ?? player._resolveGuildId?.();
|
||||||
|
if (!channelId || !guildId) return { success: false, reason: "no channel or guild id" };
|
||||||
|
|
||||||
|
const cleanChannelId = cleanId(channelId);
|
||||||
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
|
||||||
|
const currentTrack = player.queue?.getCurrent();
|
||||||
|
const queueTracks = player.queue?.data ? [...player.queue.data] : [];
|
||||||
|
const wasPaused = player._paused;
|
||||||
|
const wasAutoplay = player._autoplay;
|
||||||
|
const wasLoop = player.queue?.loop ?? false;
|
||||||
|
const wasSongLoop = player.queue?.songLoop ?? false;
|
||||||
|
const savedVolume = player.preferredVolume ?? 1;
|
||||||
|
const savedFilter = player.activeFilter ?? null;
|
||||||
|
const savedFilterPayload = player.activeFilterPayload ?? null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL);
|
||||||
|
|
||||||
|
ctx.players.playerMap.delete(cleanChannelId);
|
||||||
|
ctx.players._unindexPlayer?.(cleanGuildId, cleanChannelId);
|
||||||
|
|
||||||
|
const altIds = [player._channelId, player._home247Channel]
|
||||||
|
.filter(Boolean)
|
||||||
|
.map(id => cleanId(id))
|
||||||
|
.filter(id => id !== cleanChannelId);
|
||||||
|
for (const altId of altIds) {
|
||||||
|
ctx.players.playerMap.delete(altId);
|
||||||
|
ctx.players._unindexPlayer?.(cleanGuildId, altId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pendingScrobble = ctx.players._pendingScrobbleTimers?.get(cleanChannelId);
|
||||||
|
if (pendingScrobble) {
|
||||||
|
clearTimeout(pendingScrobble.timer);
|
||||||
|
ctx.players._pendingScrobbleTimers.delete(cleanChannelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.players._pendingJoins?.delete?.(cleanChannelId);
|
||||||
|
|
||||||
|
if (player.connection) {
|
||||||
|
try { player.connection.removeAllListeners(); } catch (e) { logger.warn("[Debug] connection listener removal:", e?.message); }
|
||||||
|
try { await player.connection.disconnect(); } catch (e) { logger.warn("[Debug] connection disconnect:", e?.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
try { await player.leave(); } catch (e) { logger.warn("[Debug] player leave:", e?.message); }
|
||||||
|
try { player.destroy(); } catch (e) { logger.warn("[Debug] player destroy:", e?.message); }
|
||||||
|
|
||||||
|
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||||
|
|
||||||
|
const newPlayer = await ctx._spawnPlayer(cleanGuildId, cleanChannelId);
|
||||||
|
|
||||||
|
if (!newPlayer) {
|
||||||
|
return { success: false, reason: "_spawnPlayer returned null", channelId: cleanChannelId };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newPlayer.preferredVolume !== savedVolume) {
|
||||||
|
newPlayer.setVolume(savedVolume);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasLoop) newPlayer.queue?.setLoop?.(true);
|
||||||
|
if (wasSongLoop) newPlayer.queue?.setSongLoop?.(true);
|
||||||
|
|
||||||
|
if (savedFilter && savedFilterPayload) {
|
||||||
|
newPlayer.activeFilter = savedFilter;
|
||||||
|
newPlayer.activeFilterPayload = savedFilterPayload;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentTrack && newPlayer.queue) {
|
||||||
|
try {
|
||||||
|
newPlayer.queue.data = queueTracks;
|
||||||
|
newPlayer.queue.current = null;
|
||||||
|
await newPlayer.playNext();
|
||||||
|
if (wasPaused) newPlayer.pause();
|
||||||
|
} catch (e) { logger.warn("[Debug] queue restore:", e?.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasAutoplay) {
|
||||||
|
newPlayer._autoplay = true;
|
||||||
|
newPlayer._autoplayHistory = player._autoplayHistory ?? [];
|
||||||
|
try {
|
||||||
|
const { attachAutoplay } = await import("../autoplay.mjs");
|
||||||
|
attachAutoplay(newPlayer, ctx);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Debug] autoplay re-attach failed:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const newRoom = newPlayer.connection?.room;
|
||||||
|
return {
|
||||||
|
success: !!(newPlayer.connection && newRoom?.isConnected),
|
||||||
|
roomConnected: newRoom?.isConnected ?? false,
|
||||||
|
roomState: roomStateLabel(newRoom),
|
||||||
|
resumedPlayback: !!(currentTrack && newPlayer.queue?.getCurrent()),
|
||||||
|
channelId: cleanChannelId,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn("[Debug] forceRejoinPlayer error:", err?.message);
|
||||||
|
return { success: false, reason: err.message, channelId: cleanChannelId };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Process a batch of players for force-rejoin, updating a status message with progress.
|
||||||
|
* @private
|
||||||
|
* @async
|
||||||
|
* @param {object} ctx - The bot (Remix) instance context.
|
||||||
|
* @param {Array} entries - Array of [channelId, player] tuples.
|
||||||
|
* @param {object} statusMsg - The message to update with progress.
|
||||||
|
* @param {string} title - The title for the progress display.
|
||||||
|
* @returns {Promise<object[]>} Array of rejoin results.
|
||||||
|
*/
|
||||||
|
async function processRejoinBatch(ctx, entries, statusMsg, title) {
|
||||||
|
const results = [];
|
||||||
|
|
||||||
|
for (let i = 0; i < entries.length; i++) {
|
||||||
|
const [cid, player] = entries[i];
|
||||||
|
const label = buildPlayerLabel(ctx.client, cid, player);
|
||||||
|
|
||||||
|
const progressLines = [
|
||||||
|
`🔄 **${title}** — Processing ${i + 1}/${entries.length}`,
|
||||||
|
`Currently rejoining: \`${label}\``,
|
||||||
|
``,
|
||||||
|
];
|
||||||
|
for (let j = 0; j < results.length; j++) {
|
||||||
|
const r = results[j];
|
||||||
|
const icon = r.success ? "✅" : "❌";
|
||||||
|
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(() => {});
|
||||||
|
|
||||||
|
const result = await forceRejoinPlayer(ctx, player);
|
||||||
|
result.label = label;
|
||||||
|
results.push(result);
|
||||||
|
|
||||||
|
if (i < entries.length - 1) {
|
||||||
|
await new Promise(r => setTimeout(r, REJOIN_DELAY_MS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Build the final embed summarizing rejoin results.
|
||||||
|
* @private
|
||||||
|
* @param {object[]} results - Array of rejoin result objects.
|
||||||
|
* @param {string} title - The title for the embed.
|
||||||
|
* @param {string} noun - The noun describing the rejoin targets.
|
||||||
|
* @returns {object} Message payload with embed.
|
||||||
|
*/
|
||||||
|
function buildRejoinResultEmbed(results, title, noun) {
|
||||||
|
const resultLines = [
|
||||||
|
`🔄 **${title} Complete**`,
|
||||||
|
`${noun.charAt(0).toUpperCase() + noun.slice(1)} processed: **${results.length}**`,
|
||||||
|
``,
|
||||||
|
];
|
||||||
|
|
||||||
|
let rejoinedCount = 0;
|
||||||
|
let resumedCount = 0;
|
||||||
|
let failedCount = 0;
|
||||||
|
|
||||||
|
for (const r of results) {
|
||||||
|
if (r.success) {
|
||||||
|
rejoinedCount++;
|
||||||
|
if (r.resumedPlayback) resumedCount++;
|
||||||
|
resultLines.push(`✅ \`${r.label}\` — rejoined (room:${r.roomState}, playback:${r.resumedPlayback ? "resumed" : "no track"})`);
|
||||||
|
} else {
|
||||||
|
failedCount++;
|
||||||
|
resultLines.push(`❌ \`${r.label}\` — failed${r.reason ? ` (${r.reason})` : ""}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (failedCount === 0) {
|
||||||
|
resultLines.push("", `All **${rejoinedCount}** ${noun} restored.${resumedCount > 0 ? ` ${resumedCount} had playback resumed.` : ""}`);
|
||||||
|
} else {
|
||||||
|
resultLines.push("", `⚠️ **${failedCount}** ${noun} could not be restored.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
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))] };
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Run a batch rejoin operation on matching players.
|
||||||
|
* @private
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {string} key - Identifier key for the rejoin type.
|
||||||
|
* @param {string} title - Display title for the operation.
|
||||||
|
* @param {string} noun - Noun describing the targets.
|
||||||
|
* @param {Function} filter - Function to filter which players to rejoin.
|
||||||
|
* @param {boolean} [showHintIfEmpty=false] - Whether to show a hint if no matches found.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = false) {
|
||||||
|
const allPlayers = [...this.players.playerMap.entries()];
|
||||||
|
const matching = allPlayers.filter(([, player]) => filter(player));
|
||||||
|
|
||||||
|
if (matching.length === 0) {
|
||||||
|
const has247 = allPlayers.some(([, player]) => player._home247Channel);
|
||||||
|
const hintLine = showHintIfEmpty && has247
|
||||||
|
? `\n\n💡 No ghosts auto-detected, but 24/7 channels with dead WebSockets may still report as "connected".\nUse \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`
|
||||||
|
: "";
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(SUCCESS_COLOR)
|
||||||
|
.setTitle(`Debug — ${title}`)
|
||||||
|
.setDescription(`No ${noun} found. All voice connections appear healthy.${hintLine}`)
|
||||||
|
;
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusLines = [
|
||||||
|
`🔄 **${title}** — Found **${matching.length}** ${noun}`,
|
||||||
|
`Destroying stale connections and respawning fresh players...`,
|
||||||
|
``,
|
||||||
|
];
|
||||||
|
|
||||||
|
for (let i = 0; i < matching.length; i++) {
|
||||||
|
const [cid, player] = matching[i];
|
||||||
|
const label = buildPlayerLabel(this.client, cid, player);
|
||||||
|
const ghost = isGhostConnection(player) ? " 👻GHOST" : "";
|
||||||
|
const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none";
|
||||||
|
const connectedLabel = player.connection?.room?.isConnected ? "yes" : "no";
|
||||||
|
statusLines.push(`${i + 1}. \`${label}\` — room:${roomLabel} isConnected:${connectedLabel}${ghost}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusEmbed = new EmbedBuilder()
|
||||||
|
.setColor(WARN_COLOR)
|
||||||
|
.setTitle(`Debug — ${title}`)
|
||||||
|
.setDescription(statusLines.join("\n").slice(0, MAX_DESC))
|
||||||
|
;
|
||||||
|
const statusMsg = await msg.reply({ embeds: [statusEmbed] });
|
||||||
|
|
||||||
|
const results = await processRejoinBatch(this, matching, statusMsg, title);
|
||||||
|
|
||||||
|
const finalPayload = buildRejoinResultEmbed(results, title, noun);
|
||||||
|
await statusMsg.edit(finalPayload).catch(() => {
|
||||||
|
msg.reply(finalPayload);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/debug/voiceDiagnostic
|
||||||
|
* @description Full voice diagnostic renderer for the debug command. Verbatim from the original single-file command.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
import { getGlobalColor, cleanId } from "../../src/ui/index.mjs";
|
||||||
|
import { DANGER_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs";
|
||||||
|
import { MAX_DESC } from "./consts.mjs";
|
||||||
|
import {
|
||||||
|
roomStateLabel, isGhostConnection, getBotGatewayVoiceState, isStaleGatewayPresence,
|
||||||
|
} from "./gateway.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a full voice diagnostic, displaying player states and ghost connections.
|
||||||
|
* @private
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function runVoiceDiagnostic(msg) {
|
||||||
|
const servers = [...this.players.playerMap.entries()].map(([cid, s]) => {
|
||||||
|
const channel = this.client.channels.get(cid);
|
||||||
|
const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id;
|
||||||
|
const guild = guildId ? this.client.guilds.get(cleanId(guildId)) : null;
|
||||||
|
const conn = s.connection;
|
||||||
|
const room = conn?.room;
|
||||||
|
const ghost = isGhostConnection(s);
|
||||||
|
const staleGateway = ghost ? isStaleGatewayPresence(this.client, s) : false;
|
||||||
|
const gatewayVoiceState = getBotGatewayVoiceState(this.client, guildId);
|
||||||
|
return {
|
||||||
|
name: channel?.name ?? "unknown",
|
||||||
|
id: channel?.id ?? cid,
|
||||||
|
channelId: s._channelId ?? cid,
|
||||||
|
guildId: guildId ?? "unknown",
|
||||||
|
guildname: guild?.name ?? channel?.guild?.name ?? "unknown",
|
||||||
|
conn: conn ? "yes" : "null",
|
||||||
|
connDestroyed: conn?._destroyed ?? null,
|
||||||
|
roomConnected: room?.isConnected ?? null,
|
||||||
|
roomState: roomStateLabel(room),
|
||||||
|
mediaPlayer: !!s._mediaPlayer && !s._mediaPlayer?.destroyed ? "alive" : (s._mediaPlayer?.destroyed ? "destroyed" : "none"),
|
||||||
|
destroyed: s._destroyed ?? false,
|
||||||
|
leaving: s.leaving ?? false,
|
||||||
|
joining: s._isJoining ?? false,
|
||||||
|
recovering: s._isRecovering ?? false,
|
||||||
|
paused: s._paused ?? false,
|
||||||
|
hasQueue: !!(s.queue?.getCurrent() || !s.queue?.isEmpty()),
|
||||||
|
home247: s._home247Channel ?? null,
|
||||||
|
ghost,
|
||||||
|
staleGateway,
|
||||||
|
gatewayVoiceChannel: gatewayVoiceState?.channelId ?? null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const pending = [...(this.players._pendingJoins ?? [])];
|
||||||
|
|
||||||
|
const ghostConnections = servers.filter(s => s.ghost);
|
||||||
|
const livePlayers = servers.filter(s => s.conn === "yes" && !s.destroyed && !s.leaving);
|
||||||
|
const actuallyConnected = livePlayers.filter(s => !s.ghost);
|
||||||
|
const channels247 = servers.filter(s => s.home247);
|
||||||
|
|
||||||
|
const summary = {
|
||||||
|
playerMapSize: this.players.playerMap.size,
|
||||||
|
livePlayers: livePlayers.length,
|
||||||
|
actuallyConnected: actuallyConnected.length,
|
||||||
|
ghostConnections: ghostConnections.length,
|
||||||
|
channels247: channels247.length,
|
||||||
|
pendingJoins: pending.length,
|
||||||
|
pendingChannels: pending,
|
||||||
|
};
|
||||||
|
|
||||||
|
const pages = [];
|
||||||
|
|
||||||
|
const summaryLines = [
|
||||||
|
`📊 **Summary**`,
|
||||||
|
`Players in map: **${summary.playerMapSize}**`,
|
||||||
|
`Live players: **${summary.livePlayers}**`,
|
||||||
|
`Actually connected: **${summary.actuallyConnected}**`,
|
||||||
|
`Ghost connections: **${summary.ghostConnections}**`,
|
||||||
|
`24/7 channels: **${summary.channels247}**`,
|
||||||
|
`Pending joins: **${summary.pendingJoins}**${summary.pendingChannels.length ? ` (\`${summary.pendingChannels.join("`, `")}\`)` : ""}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (ghostConnections.length > 0) {
|
||||||
|
summaryLines.push("", `👻 **Ghost Connections (${ghostConnections.length}):**`, "These players *appear* in voice but their WebSocket/LiveKit room is dead:");
|
||||||
|
summaryLines.push(`Use \`%debug voice-rejoin\` to rejoin detected ghosts, or \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`);
|
||||||
|
for (const g of ghostConnections) {
|
||||||
|
const gatewayInfo = g.staleGateway
|
||||||
|
? `gateway:stale(ch:${g.gatewayVoiceChannel ?? "?"})`
|
||||||
|
: `gateway:present(ch:${g.gatewayVoiceChannel ?? "?"})`;
|
||||||
|
const detail = ` 👻 \`${g.guildname}\` / \`#${g.name}\` — room:${g.roomState} connected:${g.roomConnected} media:${g.mediaPlayer} ${gatewayInfo} 247:${g.home247 ?? "no"}`;
|
||||||
|
if (summaryLines.join("\n").length + detail.length + 1 > MAX_DESC - 60) {
|
||||||
|
summaryLines.push(` … and more ghosts (see JSON details)`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
summaryLines.push(detail);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (channels247.length > 0 && ghostConnections.length === 0) {
|
||||||
|
summaryLines.push("", `ℹ️ **24/7 Channels (${channels247.length}):**`, `WebSocket deaths can leave 24/7 channels as invisible ghosts (room reports healthy but transport is dead).`);
|
||||||
|
summaryLines.push(`Use \`%debug 247-rejoin\` to force-rejoin all 24/7 channels if you suspect ghost connections.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
summaryLines.push("", "**Players:**");
|
||||||
|
for (let i = 0; i < servers.length; i++) {
|
||||||
|
const s = servers[i];
|
||||||
|
let status;
|
||||||
|
if (s.ghost) {
|
||||||
|
status = "👻";
|
||||||
|
} else if (s.conn === "yes" && !s.destroyed && !s.leaving) {
|
||||||
|
status = "🟢";
|
||||||
|
} else {
|
||||||
|
status = "🔴";
|
||||||
|
}
|
||||||
|
const ghostTag = s.ghost ? " ⚠️GHOST" : "";
|
||||||
|
const staleTag = s.staleGateway ? " ⚠️STALE_GW" : "";
|
||||||
|
const tag247 = s.home247 ? " 🔄247" : "";
|
||||||
|
const line = `${status} \`${s.guildname}\` / \`#${s.name}\` — conn:${s.conn} room:${s.roomState} connected:${s.roomConnected} media:${s.mediaPlayer}${ghostTag}${staleTag}${tag247}`;
|
||||||
|
if (summaryLines.join("\n").length + line.length + 1 > MAX_DESC - 30) {
|
||||||
|
summaryLines.push(`… and ${servers.length - i} more (see next pages)`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
summaryLines.push(line);
|
||||||
|
}
|
||||||
|
pages.push(summaryLines.join("\n"));
|
||||||
|
|
||||||
|
let groupJson = "";
|
||||||
|
for (let i = 0; i < servers.length; i++) {
|
||||||
|
const singleJson = JSON.stringify(servers[i], null, 2);
|
||||||
|
const candidate = groupJson
|
||||||
|
? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1)
|
||||||
|
: singleJson;
|
||||||
|
|
||||||
|
const candidateLen = ("```json\n" + candidate + "\n```").length;
|
||||||
|
|
||||||
|
if (candidateLen > MAX_DESC && groupJson) {
|
||||||
|
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||||
|
groupJson = singleJson;
|
||||||
|
} else if (candidateLen > MAX_DESC) {
|
||||||
|
const budget = MAX_DESC - 12;
|
||||||
|
pages.push(("```json\n" + singleJson.slice(0, budget) + "\n```").slice(0, MAX_DESC));
|
||||||
|
groupJson = "";
|
||||||
|
} else {
|
||||||
|
groupJson = candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (groupJson) {
|
||||||
|
pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pages.length === 1) {
|
||||||
|
const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor();
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""))
|
||||||
|
.setDescription(pages[0].slice(0, MAX_DESC))
|
||||||
|
;
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalPages = pages.length;
|
||||||
|
let currentPage = 0;
|
||||||
|
|
||||||
|
const buildPage = (pageIdx, expired = false) => {
|
||||||
|
const isSummaryPage = pageIdx === 0;
|
||||||
|
const pageLabel = isSummaryPage
|
||||||
|
? "Summary"
|
||||||
|
: `Player Detail${pages[pageIdx].split(`"name":`).length - 1 > 1 ? "s" : ""}`;
|
||||||
|
const footerText = expired
|
||||||
|
? this.t(msg, "responses._common.controlsExpired")
|
||||||
|
: `${this.t(msg, "responses.debug.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`;
|
||||||
|
|
||||||
|
const embedColor = (isSummaryPage && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor();
|
||||||
|
const titleSuffix = (isSummaryPage && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "";
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(embedColor)
|
||||||
|
.setTitle(this.t(msg, "responses.debug.voiceTitle") + titleSuffix + ` — ${pageLabel}`)
|
||||||
|
.setDescription(pages[pageIdx].slice(0, MAX_DESC))
|
||||||
|
.setFooter({ text: footerText })
|
||||||
|
;
|
||||||
|
return { embeds: [embed] };
|
||||||
|
};
|
||||||
|
|
||||||
|
const replyMsg = await msg.reply(buildPage(0));
|
||||||
|
if (!replyMsg?.message) return;
|
||||||
|
|
||||||
|
const navEmojis = ["⬅️", "➡️", "❌"];
|
||||||
|
for (const emoji of navEmojis) {
|
||||||
|
await replyMsg.message.react(emoji).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearReactions = async () => {
|
||||||
|
try {
|
||||||
|
await replyMsg.message.removeAllReactions();
|
||||||
|
} catch (e) {
|
||||||
|
for (const emoji of navEmojis) {
|
||||||
|
try { await replyMsg.message.removeReaction(emoji); } catch (err) { logger.warn("[Debug] removeReaction fallback:", err?.message); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let emojiTimeout;
|
||||||
|
const resetTimer = () => {
|
||||||
|
clearTimeout(emojiTimeout);
|
||||||
|
emojiTimeout = setTimeout(async () => {
|
||||||
|
unobserve?.();
|
||||||
|
await clearReactions();
|
||||||
|
await replyMsg.edit(buildPage(currentPage, true)).catch(() => {});
|
||||||
|
}, EMOJI_REMOVE_TIMEOUT);
|
||||||
|
};
|
||||||
|
|
||||||
|
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||||
|
const emoji = e?.emoji_id ?? e?.emoji?.id ?? e?.emoji;
|
||||||
|
|
||||||
|
if (emoji === "❌") {
|
||||||
|
clearTimeout(emojiTimeout);
|
||||||
|
unobserve?.();
|
||||||
|
await replyMsg.message.delete().catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
resetTimer();
|
||||||
|
|
||||||
|
if (emoji === "⬅️") {
|
||||||
|
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
||||||
|
} else if (emoji === "➡️") {
|
||||||
|
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
resetTimer();
|
||||||
|
}
|
||||||
+5
-5
@@ -3,12 +3,12 @@
|
|||||||
* @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.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { inspect } from "node:util";
|
import { inspect } from "node:util";
|
||||||
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||||
|
|
||||||
/** @private @type {string[]} Property name substrings that indicate sensitive/secret data. */
|
/** @private @type {string[]} Property name substrings that indicate sensitive/secret data. */
|
||||||
const RESTRICTED = [
|
const RESTRICTED = [
|
||||||
@@ -88,7 +88,7 @@ function removeSensitive(obj, level = 0, visited = new WeakSet()) {
|
|||||||
* @private
|
* @private
|
||||||
* @async
|
* @async
|
||||||
* 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 Discord markup characters.
|
* inspect with node:util, and escape markup characters.
|
||||||
* @param {*} value - The raw eval result.
|
* @param {*} value - The raw eval result.
|
||||||
* @returns {Promise<string>} The sanitized output string.
|
* @returns {Promise<string>} The sanitized output string.
|
||||||
*/
|
*/
|
||||||
|
|||||||
+5
-5
@@ -3,12 +3,12 @@
|
|||||||
* @description Interactive audio filter picker with emoji-based selection and pagination.
|
* @description Interactive audio filter picker with emoji-based selection and pagination.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI } from "../src/constants/UI.mjs";
|
import { PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI } from "../src/utils/UI.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
|
||||||
const NAV_EMOJIS = [PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI];
|
const NAV_EMOJIS = [PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI];
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,8 @@
|
|||||||
* @description Force the bot to leave a voice channel (requires ManageChannels permission).
|
* @description Force the bot to leave a voice channel (requires ManageChannels permission).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { cleanId } from "../src/MessageHandler.mjs";
|
import { cleanId } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
|
|||||||
+2
-2
@@ -3,9 +3,9 @@
|
|||||||
* @description Display the bot invite link and support server information.
|
* @description Display the bot invite link and support server information.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
|
|||||||
+2
-2
@@ -6,9 +6,9 @@
|
|||||||
* 24/7 handling, event binding, and permission checks.
|
* 24/7 handling, event binding, and permission checks.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs";
|
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
|
|||||||
+32
-2510
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,245 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm/account
|
||||||
|
* @description Account linking, profile and playlist actions for the lastfm command (link, confirm, unlink, scrobble, np, profile, playlists). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { Utils } from "../../src/utils/Utils.mjs";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||||
|
import { notLinked } from "./shared.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Action names dispatched to this module.
|
||||||
|
* @type {Set<string>}
|
||||||
|
*/
|
||||||
|
export const ACCOUNT_ACTIONS = new Set([
|
||||||
|
"link",,
|
||||||
|
"confirm",,
|
||||||
|
"unlink",,
|
||||||
|
"scrobble",,
|
||||||
|
"np",,
|
||||||
|
"profile",,
|
||||||
|
"playlists"
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @param {object} lastfm - The Last.fm manager instance.
|
||||||
|
* @param {string} prefix - The guild command prefix.
|
||||||
|
* @param {string} userId - The invoking user's ID.
|
||||||
|
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||||
|
* @param {string} action - The resolved action name.
|
||||||
|
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||||
|
*/
|
||||||
|
export async function runAccountActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
|
switch (action) {
|
||||||
|
case "link": {
|
||||||
|
const existing = await lastfm.getUser(userId);
|
||||||
|
if (existing) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setDescription(this.t(msg, "responses.lastfm.alreadyLinked", { username: existing.username, prefix }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let token;
|
||||||
|
try {
|
||||||
|
token = await lastfm.getAuthToken();
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tokenFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const authUrl = lastfm.getAuthUrl(token);
|
||||||
|
|
||||||
|
let sent = false;
|
||||||
|
try {
|
||||||
|
const dm = await msg.author.createDM();
|
||||||
|
await dm.send({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.authLinkTitle"))
|
||||||
|
.setDescription(this.t(msg, "responses.lastfm.authLinkBody", { url: authUrl, prefix, token }))
|
||||||
|
]
|
||||||
|
});
|
||||||
|
sent = true;
|
||||||
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
|
||||||
|
const replyEmbed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setDescription(
|
||||||
|
sent
|
||||||
|
? this.t(msg, "responses.lastfm.authDM", { prefix })
|
||||||
|
: this.t(msg, "responses.lastfm.authDMFailed", { url: authUrl, prefix })
|
||||||
|
);
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [replyEmbed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "confirm": {
|
||||||
|
let tokenValue = data.get("token")?.value;
|
||||||
|
if (!tokenValue) {
|
||||||
|
const rawContent = msg.message?.content ?? "";
|
||||||
|
const args = rawContent.split(/\s+/);
|
||||||
|
const confirmIdx = args.indexOf("confirm");
|
||||||
|
tokenValue = confirmIdx >= 0 ? args[confirmIdx + 1] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tokenValue) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmUsage", { prefix }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let session;
|
||||||
|
try {
|
||||||
|
session = await lastfm.getSession(tokenValue);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await lastfm.saveUser(userId, session.key, session.name);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setDescription(this.t(msg, "responses.lastfm.linked", { username: session.name }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "unlink": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
await lastfm.removeUser(userId);
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.unlinked", { username: user.username }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "scrobble": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const newState = !user.scrobbleEnabled;
|
||||||
|
await lastfm.setScrobble(userId, newState);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setDescription(newState
|
||||||
|
? this.t(msg, "responses.lastfm.scrobbleEnabled", { username: user.username })
|
||||||
|
: this.t(msg, "responses.lastfm.scrobbleDisabled")
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "np": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let recentData;
|
||||||
|
try {
|
||||||
|
recentData = await lastfm.getRecentTracks(userId, 1);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!recentData.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noRecent", { username: user.username }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const track = recentData[0];
|
||||||
|
const statusEmoji = track.now ? this.t(msg, "responses.lastfm.nowPlaying") : this.t(msg, "responses.lastfm.lastPlayed");
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: statusEmoji, iconURL: track.image || undefined })
|
||||||
|
.setDescription(this.t(msg, "responses.lastfm.npTrackInfo", { name: track.name, artist: track.artist, url: track.url }))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.npFooter", { username: user.username }) });
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "profile": {
|
||||||
|
const profileUserId = targetUserId || userId;
|
||||||
|
const user = await lastfm.getUser(profileUserId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let info;
|
||||||
|
try {
|
||||||
|
info = await lastfm.getUserInfo(profileUserId);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
lastfm.syncUserScrobbleCount(profileUserId).catch(() => {});
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setAuthor({ name: this.t(msg, "responses.lastfm.profileTitle", { username: info.name }), iconURL: info.image?.[2]?.["#text"] || undefined, url: info.url })
|
||||||
|
.setDescription([
|
||||||
|
this.t(msg, "responses.lastfm.profileScrobbles", { playcount: Utils.formatNumber(info.playcount ?? 0) }),
|
||||||
|
this.t(msg, "responses.lastfm.profileRegistered", { date: info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown" }),
|
||||||
|
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.profileLink", { url: info.url }),
|
||||||
|
].join("\n"))
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.profileScrobbleFooter", { prefix }) });
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "playlists": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let playlists;
|
||||||
|
try {
|
||||||
|
playlists = await lastfm.getPlaylists(userId);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!playlists.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noPlaylists", { username: user.username }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = playlists.map((pl, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = pl.url ? `[${pl.title}](${pl.url})` : pl.title;
|
||||||
|
return `\`${num}.\` ${link} — **${pl.trackCount}** tracks`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.playlistsTitle", { username: user.username }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.playlistsFooter", { prefix }) })]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm/discovery
|
||||||
|
* @description Charts and discovery actions for the lastfm command (friends, weekly, trending, geo, artisttracks, search). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { Utils } from "../../src/utils/Utils.mjs";
|
||||||
|
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||||
|
import { notLinked, extractCurrentTrack } from "./shared.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Action names dispatched to this module.
|
||||||
|
* @type {Set<string>}
|
||||||
|
*/
|
||||||
|
export const DISCOVERY_ACTIONS = new Set([
|
||||||
|
"friends",,
|
||||||
|
"fr",,
|
||||||
|
"weekly",,
|
||||||
|
"wc",,
|
||||||
|
"trending",,
|
||||||
|
"tr",,
|
||||||
|
"geo",,
|
||||||
|
"g",,
|
||||||
|
"artisttracks",,
|
||||||
|
"atr",,
|
||||||
|
"search",,
|
||||||
|
"s"
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @param {object} lastfm - The Last.fm manager instance.
|
||||||
|
* @param {string} prefix - The guild command prefix.
|
||||||
|
* @param {string} userId - The invoking user's ID.
|
||||||
|
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||||
|
* @param {string} action - The resolved action name.
|
||||||
|
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||||
|
*/
|
||||||
|
export async function runDiscoveryActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
|
switch (action) {
|
||||||
|
case "friends":
|
||||||
|
case "fr": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let friends;
|
||||||
|
try {
|
||||||
|
friends = await lastfm.getUserFriends(userId, 20);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!friends.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`👥 No friends found for **${user.username}**.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = friends.map((f, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = f.url ? `[${f.name}](${f.url})` : f.name;
|
||||||
|
const details = [];
|
||||||
|
if (f.realname) details.push(f.realname);
|
||||||
|
if (f.country) details.push(f.country);
|
||||||
|
const detailStr = details.length > 0 ? ` (${details.join(", ")})` : "";
|
||||||
|
return `\`${num}.\` ${link}${detailStr}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(`👥 Friends — ${user.username}`)
|
||||||
|
.setDescription(desc)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "weekly":
|
||||||
|
case "wc": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const tokenTextWc = data.get("token")?.value?.toLowerCase().trim() ?? "artists";
|
||||||
|
let chartData;
|
||||||
|
let chartTitle;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (tokenTextWc === "tracks") {
|
||||||
|
chartData = await lastfm.getUserWeeklyTrackChart(userId);
|
||||||
|
chartTitle = `📅 Weekly Track Chart — ${user.username}`;
|
||||||
|
} else if (tokenTextWc === "albums") {
|
||||||
|
chartData = await lastfm.getUserWeeklyAlbumChart(userId);
|
||||||
|
chartTitle = `📅 Weekly Album Chart — ${user.username}`;
|
||||||
|
} else {
|
||||||
|
chartData = await lastfm.getUserWeeklyArtistChart(userId);
|
||||||
|
chartTitle = `📅 Weekly Artist Chart — ${user.username}`;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!chartData.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`📅 No weekly chart data found for **${user.username}**.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = chartData.slice(0, 15).map((item, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = item.url ? `[${item.name}](${item.url})` : item.name;
|
||||||
|
const artistStr = item.artist ? ` by **${item.artist}**` : "";
|
||||||
|
return `\`${num}.\` ${link}${artistStr} — **${Utils.formatNumber(item.playcount)}** plays`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(chartTitle)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: `💡 Use token option: artists, tracks, or albums` })]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "trending":
|
||||||
|
case "tr": {
|
||||||
|
const tokenTextTr = data.get("token")?.value?.toLowerCase().trim() ?? "tracks";
|
||||||
|
let trendingData;
|
||||||
|
let trendingTitle;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (tokenTextTr === "artists") {
|
||||||
|
trendingData = await lastfm.getChartTopArtists(15);
|
||||||
|
trendingTitle = "🔥 Trending Artists on Last.fm";
|
||||||
|
} else {
|
||||||
|
trendingData = await lastfm.getChartTopTracks(15);
|
||||||
|
trendingTitle = "🔥 Trending Tracks on Last.fm";
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!trendingData.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🔥 No trending data found.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = trendingData.map((item, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = item.url ? `[${item.name}](${item.url})` : item.name;
|
||||||
|
const artistStr = item.artist ? ` by **${item.artist}**` : "";
|
||||||
|
const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} listeners` : item.playcount ? ` — ${Utils.formatNumber(item.playcount)} plays` : "";
|
||||||
|
return `\`${num}.\` ${link}${artistStr}${extra}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(trendingTitle)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: `💡 Use token option: tracks or artists` })]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "geo":
|
||||||
|
case "g": {
|
||||||
|
const tokenTextG = data.get("token")?.value?.trim() ?? "";
|
||||||
|
if (!tokenTextG) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a query like \`artists <country>\` or \`tracks <country>\`. Example: \`${prefix}lastfm geo artists united states\`.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lowerToken = tokenTextG.toLowerCase();
|
||||||
|
let type = "artists";
|
||||||
|
let country = tokenTextG;
|
||||||
|
|
||||||
|
if (lowerToken.startsWith("artists ")) {
|
||||||
|
type = "artists";
|
||||||
|
country = tokenTextG.slice(8).trim();
|
||||||
|
} else if (lowerToken.startsWith("tracks ")) {
|
||||||
|
type = "tracks";
|
||||||
|
country = tokenTextG.slice(7).trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!country) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Please specify a country name. Example: \`${prefix}lastfm geo artists united states\`.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let geoData;
|
||||||
|
let geoTitle;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (type === "tracks") {
|
||||||
|
geoData = await lastfm.getGeoTopTracks(country, 15);
|
||||||
|
geoTitle = `🌍 Top Tracks in ${country}`;
|
||||||
|
} else {
|
||||||
|
geoData = await lastfm.getGeoTopArtists(country, 15);
|
||||||
|
geoTitle = `🌍 Top Artists in ${country}`;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!geoData.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🌍 No data found for **${country}**.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = geoData.map((item, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = item.url ? `[${item.name}](${item.url})` : item.name;
|
||||||
|
const artistStr = item.artist ? ` by **${item.artist}**` : "";
|
||||||
|
const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} listeners` : "";
|
||||||
|
return `\`${num}.\` ${link}${artistStr}${extra}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(geoTitle)
|
||||||
|
.setDescription(desc)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "artisttracks":
|
||||||
|
case "atr": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let artistName = null;
|
||||||
|
|
||||||
|
const pAtr = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pAtr);
|
||||||
|
if (current?.artist) {
|
||||||
|
artistName = current.artist;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenTextAtr = data.get("token")?.value;
|
||||||
|
if (tokenTextAtr) {
|
||||||
|
artistName = tokenTextAtr.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!artistName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let recentTracks;
|
||||||
|
try {
|
||||||
|
recentTracks = await lastfm.getRecentTracks(userId, 200);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const artistTracks = recentTracks.filter(t =>
|
||||||
|
t.artist.toLowerCase() === artistName.toLowerCase()
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!artistTracks.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🎵 No scrobbles found for **${artistName}** in your recent history.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = artistTracks.slice(0, 15).map((t, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
|
const nowStr = t.now ? " 🎵" : "";
|
||||||
|
return `\`${num}.\` ${link}${nowStr}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(`🎵 ${artistName} Scrobbles — ${user.username}`)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: `${artistTracks.length} scrobble${artistTracks.length !== 1 ? "s" : ""} found` })]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "search":
|
||||||
|
case "s": {
|
||||||
|
const query = data.get("token")?.value;
|
||||||
|
if (!query) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a search query via the token option. Example: \`${prefix}lastfm search radiohead\``)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let artistResults, albumResults, trackResult;
|
||||||
|
try {
|
||||||
|
[artistResults, albumResults, trackResult] = await Promise.all([
|
||||||
|
lastfm.searchArtist(query, 5),
|
||||||
|
lastfm.searchAlbum(query, 5),
|
||||||
|
lastfm.searchTrack(query),
|
||||||
|
]);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const sections = [];
|
||||||
|
|
||||||
|
if (artistResults.length) {
|
||||||
|
const artistLines = artistResults.map((a, i) => {
|
||||||
|
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||||
|
const listeners = a.listeners ? ` — ${Utils.formatNumber(a.listeners)} listeners` : "";
|
||||||
|
return `${i + 1}. ${link}${listeners}`;
|
||||||
|
});
|
||||||
|
sections.push(`**🎤 Artists:**\n${artistLines.join("\n")}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (albumResults.length) {
|
||||||
|
const albumLines = albumResults.map((a, i) => {
|
||||||
|
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||||
|
return `${i + 1}. ${link} by **${a.artist}**`;
|
||||||
|
});
|
||||||
|
sections.push(`**💿 Albums:**\n${albumLines.join("\n")}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackResult) {
|
||||||
|
sections.push(`**🎵 Best Track Match:**\n[${trackResult.name}](${trackResult.url}) by **${trackResult.artist}**`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sections.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🔍 No results found for **${query}**.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const desc = sections.join("\n\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(`🔍 Search Results for "${query}"`)
|
||||||
|
.setDescription(desc)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm/help
|
||||||
|
* @description Fallback help action for the lastfm command (the original
|
||||||
|
* switch's `default` branch). Extracted verbatim; reached when the action
|
||||||
|
* matches no known action name.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @param {object} lastfm - The Last.fm manager instance.
|
||||||
|
* @param {string} prefix - The guild command prefix.
|
||||||
|
* @param {string} userId - The invoking user's ID.
|
||||||
|
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||||
|
* @param {string} action - The resolved action name.
|
||||||
|
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||||
|
*/
|
||||||
|
export async function runLastFmHelp(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setDescription([
|
||||||
|
`🎵 **Last.fm Commands:**`,
|
||||||
|
``,
|
||||||
|
`\`${prefix}lastfm link\` — Link your Last.fm account`,
|
||||||
|
`\`${prefix}lastfm unlink\` — Disconnect your account`,
|
||||||
|
`\`${prefix}lastfm scrobble\` — Toggle auto-scrobbling`,
|
||||||
|
`\`${prefix}lastfm np\` — Show your Last.fm now playing`,
|
||||||
|
`\`${prefix}lastfm profile\` — View your Last.fm profile (or another user's with user option)`,
|
||||||
|
`\`${prefix}lastfm loved\` — View your loved tracks`,
|
||||||
|
`\`${prefix}lastfm top\` — View your top tracks (supports period)`,
|
||||||
|
`\`${prefix}lastfm artists\` — View your top artists (supports period)`,
|
||||||
|
`\`${prefix}lastfm recent\` — View your recent tracks`,
|
||||||
|
`\`${prefix}lastfm playlists\` — View your Last.fm playlists`,
|
||||||
|
`\`${prefix}lastfm leaderboard\` — Scrobble leaderboard`,
|
||||||
|
`\`${prefix}lastfm love\` — Love the current track`,
|
||||||
|
`\`${prefix}lastfm unlove\` — Unlove the current track`,
|
||||||
|
``,
|
||||||
|
`🔍 **Info Commands:**`,
|
||||||
|
`\`${prefix}lastfm whoknows [artist]\` — Who in the server listens to an artist`,
|
||||||
|
`\`${prefix}lastfm whoknowstrack\` — Who knows a specific track`,
|
||||||
|
`\`${prefix}lastfm whoknowsalbum\` — Who knows a specific album`,
|
||||||
|
`\`${prefix}lastfm artistinfo\` — Detailed info about an artist`,
|
||||||
|
`\`${prefix}lastfm albuminfo\` — Detailed info about an album`,
|
||||||
|
`\`${prefix}lastfm trackinfo\` — Detailed info about a track`,
|
||||||
|
`\`${prefix}lastfm topalbums\` — View your top albums (supports period)`,
|
||||||
|
`\`${prefix}lastfm toptags\` — View your top tags/genres`,
|
||||||
|
`\`${prefix}lastfm tag <name>\` — View info about a specific tag`,
|
||||||
|
`\`${prefix}lastfm compare @user\` — Compare your taste with another user`,
|
||||||
|
`\`${prefix}lastfm cover\` — Get album cover art for the current track`,
|
||||||
|
``,
|
||||||
|
`🏷️ **Tag Commands:**`,
|
||||||
|
`\`${prefix}lastfm artisttags\` — Top tags for an artist`,
|
||||||
|
`\`${prefix}lastfm albumtags\` — Top tags for an album`,
|
||||||
|
`\`${prefix}lastfm tracktags\` — Top tags for a track`,
|
||||||
|
`\`${prefix}lastfm tagalbums <tag>\` — Top albums for a tag`,
|
||||||
|
``,
|
||||||
|
`👥 **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"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm
|
||||||
|
* @description Barrel for the lastfm command group implementation modules.
|
||||||
|
* commands/lastfm.mjs (the command entry file) dispatches through this
|
||||||
|
* barrel; it stays the single import surface for the group.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export { notConfigured, notLinked, extractCurrentTrack, extractPeriod, VALID_PERIODS } from "./shared.mjs";
|
||||||
|
export { runAccountActions, ACCOUNT_ACTIONS } from "./account.mjs";
|
||||||
|
export { runPlaybackActions, PLAYBACK_ACTIONS, playLastFmCategory } from "./playback.mjs";
|
||||||
|
export { runListeningActions, LISTENING_ACTIONS } from "./listening.mjs";
|
||||||
|
export { runWhoknowsActions, WHOKNOWS_ACTIONS } from "./whoknows.mjs";
|
||||||
|
export { runInfoActions, INFO_ACTIONS } from "./info.mjs";
|
||||||
|
export { runTagActions, TAG_ACTIONS } from "./tags.mjs";
|
||||||
|
export { runDiscoveryActions, DISCOVERY_ACTIONS } from "./discovery.mjs";
|
||||||
|
export { runLastFmHelp } from "./help.mjs";
|
||||||
@@ -0,0 +1,505 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm/info
|
||||||
|
* @description Metadata lookup actions for the lastfm command (artistinfo, albuminfo, trackinfo, topalbums, toptags, cover) with the duration formatter. Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { Utils } from "../../src/utils/Utils.mjs";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||||
|
import { notLinked, extractCurrentTrack, extractPeriod } from "./shared.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Action names dispatched to this module.
|
||||||
|
* @type {Set<string>}
|
||||||
|
*/
|
||||||
|
export const INFO_ACTIONS = new Set([
|
||||||
|
"artistinfo",,
|
||||||
|
"ai",,
|
||||||
|
"albuminfo",,
|
||||||
|
"ali",,
|
||||||
|
"trackinfo",,
|
||||||
|
"ti",,
|
||||||
|
"topalbums",,
|
||||||
|
"toptags",,
|
||||||
|
"tags",,
|
||||||
|
"cover",,
|
||||||
|
"art"
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format seconds into a human-readable duration string (h:mm:ss or m:ss).
|
||||||
|
* @private
|
||||||
|
* @param {number} seconds - Duration in seconds.
|
||||||
|
* @returns {string} Formatted duration, or empty string if invalid.
|
||||||
|
*/
|
||||||
|
function formatDuration(seconds) {
|
||||||
|
if (!seconds || seconds <= 0) return "";
|
||||||
|
const h = Math.floor(seconds / 3600);
|
||||||
|
const m = Math.floor((seconds % 3600) / 60);
|
||||||
|
const s = seconds % 60;
|
||||||
|
if (h > 0) {
|
||||||
|
return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
return `${m}:${String(s).padStart(2, "0")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @param {object} lastfm - The Last.fm manager instance.
|
||||||
|
* @param {string} prefix - The guild command prefix.
|
||||||
|
* @param {string} userId - The invoking user's ID.
|
||||||
|
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||||
|
* @param {string} action - The resolved action name.
|
||||||
|
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||||
|
*/
|
||||||
|
export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
|
switch (action) {
|
||||||
|
case "artistinfo":
|
||||||
|
case "ai": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
|
||||||
|
let artistName = null;
|
||||||
|
|
||||||
|
const pAi = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pAi);
|
||||||
|
if (current?.artist) {
|
||||||
|
artistName = current.artist;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenText = data.get("token")?.value;
|
||||||
|
if (tokenText) {
|
||||||
|
artistName = tokenText.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!artistName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
|
this.t(msg, "responses.lastfm.noArtistSpecified")
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let info;
|
||||||
|
try {
|
||||||
|
info = await lastfm.getArtistInfo(artistName, userId);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!info) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.artistNotFound", { artist: artistName }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(`🎤 ${info.name}`)
|
||||||
|
.setURL(info.url || undefined)
|
||||||
|
.setThumbnail(info.image || undefined);
|
||||||
|
|
||||||
|
const fields = [];
|
||||||
|
fields.push({ name: "Listeners", value: Utils.formatNumber(info.stats?.listeners ?? 0), inline: true });
|
||||||
|
fields.push({ name: "Global Plays", value: Utils.formatNumber(info.stats?.playcount ?? 0), inline: true });
|
||||||
|
|
||||||
|
if (info.userplaycount != null && user) {
|
||||||
|
fields.push({ name: "Your Plays", 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) {
|
||||||
|
const simStr = info.similar.slice(0, 5).map(s => {
|
||||||
|
return s.url ? `[${s.name}](${s.url})` : s.name;
|
||||||
|
}).join(" · ");
|
||||||
|
fields.push({ name: "Similar Artists", value: simStr, inline: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
embed.addFields(...fields);
|
||||||
|
|
||||||
|
if (info.bio) {
|
||||||
|
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] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "albuminfo":
|
||||||
|
case "ali": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
|
||||||
|
let artistName = null;
|
||||||
|
let albumName = null;
|
||||||
|
|
||||||
|
const pAli = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pAli);
|
||||||
|
if (current?.album && current?.artist) {
|
||||||
|
artistName = current.artist;
|
||||||
|
albumName = current.album;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenText = data.get("token")?.value;
|
||||||
|
if (tokenText) {
|
||||||
|
const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
|
if (dashMatch) {
|
||||||
|
artistName = dashMatch[1].trim();
|
||||||
|
albumName = dashMatch[2].trim();
|
||||||
|
} else {
|
||||||
|
albumName = tokenText.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!albumName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
|
this.t(msg, "responses.lastfm.noAlbumSpecified")
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let info;
|
||||||
|
try {
|
||||||
|
info = await lastfm.getAlbumInfo(artistName || "", albumName, userId);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!info) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.albumNotFound", { album: albumName }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(`💿 ${info.name}`)
|
||||||
|
.setURL(info.url || undefined)
|
||||||
|
.setThumbnail(info.image || undefined);
|
||||||
|
|
||||||
|
const fields = [];
|
||||||
|
|
||||||
|
if (info.artist) {
|
||||||
|
fields.push({ name: "Artist", value: info.artist, inline: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (info.userplaycount != null && user) {
|
||||||
|
fields.push({ name: "Your Plays", 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.tracks?.length) {
|
||||||
|
const trackLines = info.tracks.slice(0, 15).map((t, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const dur = t.duration > 0 ? ` (${formatDuration(t.duration)})` : "";
|
||||||
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
|
return `\`${num}.\` ${link}${dur}`;
|
||||||
|
});
|
||||||
|
fields.push({ name: "Tracklist", value: trackLines.join("\n").slice(0, 1024), inline: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
embed.addFields(...fields);
|
||||||
|
embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" });
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "trackinfo":
|
||||||
|
case "ti": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let artistName = null;
|
||||||
|
let trackName = null;
|
||||||
|
|
||||||
|
const pTi = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pTi);
|
||||||
|
if (current?.artist && current?.name) {
|
||||||
|
artistName = current.artist;
|
||||||
|
trackName = current.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenText = data.get("token")?.value;
|
||||||
|
if (tokenText) {
|
||||||
|
const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
|
if (dashMatch) {
|
||||||
|
artistName = dashMatch[1].trim();
|
||||||
|
trackName = dashMatch[2].trim();
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const searchResult = await lastfm.searchTrack(tokenText.trim());
|
||||||
|
if (searchResult) {
|
||||||
|
artistName = searchResult.artist;
|
||||||
|
trackName = searchResult.name;
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!artistName || !trackName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
|
this.t(msg, "responses.lastfm.noTrackSpecified")
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let info;
|
||||||
|
try {
|
||||||
|
info = await lastfm.getTrackInfo(artistName, trackName, userId);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!info) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.trackNotFound", { track: trackName, artist: artistName }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(`🎵 ${info.name}`)
|
||||||
|
.setURL(info.url || undefined);
|
||||||
|
|
||||||
|
if (info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]) {
|
||||||
|
embed.setThumbnail(info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
||||||
|
fields.push({ name: "Listeners", value: Utils.formatNumber(Number(info.listeners)), inline: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (info.playcount) {
|
||||||
|
fields.push({ name: "Global Plays", value: Utils.formatNumber(Number(info.playcount)), inline: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (info.userplaycount) {
|
||||||
|
fields.push({ name: "Your Plays", value: Utils.formatNumber(Number(info.userplaycount)), inline: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userLoved = info.userloved === "1" || info.userloved === 1 || info.userloved === true;
|
||||||
|
fields.push({ name: "Loved", value: userLoved ? "❤️ Yes" : "🖤 No", inline: true });
|
||||||
|
|
||||||
|
if (info.toptags?.tag?.length) {
|
||||||
|
const tagStr = info.toptags.tag.slice(0, 8).map(t => {
|
||||||
|
const tagName = t.name ?? t;
|
||||||
|
const tagLower = String(tagName).toLowerCase().replace(/\s+/g, "+");
|
||||||
|
return `[${tagName}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`;
|
||||||
|
}).join(" · ");
|
||||||
|
fields.push({ name: "Tags", value: tagStr, inline: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
embed.addFields(...fields);
|
||||||
|
|
||||||
|
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 = [];
|
||||||
|
try {
|
||||||
|
similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 5);
|
||||||
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
|
||||||
|
if (similarTracks.length) {
|
||||||
|
const simStr = similarTracks.map(t => {
|
||||||
|
const matchPct = Math.round(t.match * 100);
|
||||||
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
|
return `${link} by **${t.artist}** (${matchPct}%)`;
|
||||||
|
}).join("\n");
|
||||||
|
embed.addFields({ name: "Similar Tracks", value: simStr.slice(0, 1024), inline: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
embed.setFooter({ text: `Last.fm: ${user.username}` });
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "topalbums": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const period = extractPeriod(data, msg);
|
||||||
|
|
||||||
|
let albums;
|
||||||
|
try {
|
||||||
|
albums = await lastfm.getTopAlbums(userId, period, 15);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!albums.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTopAlbums", { username: user.username }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
||||||
|
|
||||||
|
const lines = albums.map((a, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
let albumTitle = a.name;
|
||||||
|
if (albumTitle.length > 30) albumTitle = albumTitle.slice(0, 27) + "...";
|
||||||
|
const link = a.url ? `[${albumTitle}](${a.url})` : albumTitle;
|
||||||
|
return `\`${num}.\` ${link} — **${a.artist}** (**${a.playcount}** plays)`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.topAlbumsTitle", { period: periodLabel, username: user.username }))
|
||||||
|
.setDescription(desc);
|
||||||
|
|
||||||
|
if (albums[0]?.image) {
|
||||||
|
embed.setThumbnail(albums[0].image);
|
||||||
|
}
|
||||||
|
|
||||||
|
embed.setFooter({ text: this.t(msg, "responses.lastfm.topAlbumsFooter", { prefix }) });
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "toptags":
|
||||||
|
case "tags": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let tags;
|
||||||
|
try {
|
||||||
|
tags = await lastfm.getUserTopTags(userId, 20);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tags.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTopTags", { username: user.username }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = tags.map((t, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
|
return `\`${num}.\` ${link} — **${t.count}**`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.topTagsTitle", { username: user.username }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.topTagsFooter", { prefix }) })]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "cover":
|
||||||
|
case "art": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const pCover = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pCover);
|
||||||
|
if (!current || !current.name) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.coverNothingPlaying"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const artistName = current.artist ?? "Unknown";
|
||||||
|
const trackName = current.name;
|
||||||
|
const albumName = current.album;
|
||||||
|
|
||||||
|
let coverUrl = null;
|
||||||
|
let albumTitle = albumName ?? "Unknown Album";
|
||||||
|
|
||||||
|
if (albumName) {
|
||||||
|
try {
|
||||||
|
const albumInfo = await lastfm.getAlbumInfo(artistName, albumName, userId);
|
||||||
|
if (albumInfo?.image) {
|
||||||
|
coverUrl = albumInfo.image;
|
||||||
|
albumTitle = `${albumInfo.name} by ${albumInfo.artist}`;
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!coverUrl) {
|
||||||
|
try {
|
||||||
|
const trackInfo = await lastfm.getTrackInfo(artistName, trackName, userId);
|
||||||
|
if (trackInfo?.album?.image) {
|
||||||
|
const images = trackInfo.album.image;
|
||||||
|
coverUrl = images?.[2]?.["#text"] || images?.[1]?.["#text"] || images?.[0]?.["#text"] || null;
|
||||||
|
if (trackInfo.album?.title) {
|
||||||
|
albumTitle = trackInfo.album.title;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!coverUrl) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.coverNotFound", { track: trackName, artist: artistName }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.coverTitle", { album: albumTitle }))
|
||||||
|
.setImage(coverUrl)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.coverFooter", { track: trackName, artist: artistName }) });
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm/listening
|
||||||
|
* @description Personal listening actions for the lastfm command (loved, top, leaderboard, recent, artists, love, unlove) with their list/leaderboard embed builders. Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { Utils } from "../../src/utils/Utils.mjs";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs";
|
||||||
|
import { notLinked, extractPeriod } from "./shared.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Action names dispatched to this module.
|
||||||
|
* @type {Set<string>}
|
||||||
|
*/
|
||||||
|
export const LISTENING_ACTIONS = new Set([
|
||||||
|
"loved",,
|
||||||
|
"top",,
|
||||||
|
"leaderboard",,
|
||||||
|
"lb",,
|
||||||
|
"recent",,
|
||||||
|
"artists",,
|
||||||
|
"love",,
|
||||||
|
"unlove"
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build an embed listing tracks with optional playcount.
|
||||||
|
* @private
|
||||||
|
* @param {string} username - The Last.fm username.
|
||||||
|
* @param {string} title - The list title.
|
||||||
|
* @param {object[]} tracks - Array of track objects with name, artist, url, and optional playcount.
|
||||||
|
* @param {boolean} [showPlaycount=false] - Whether to show play counts.
|
||||||
|
* @param {string} [prefix="%"] - The command prefix for the footer hint.
|
||||||
|
* @returns {EmbedBuilder} The constructed embed.
|
||||||
|
*/
|
||||||
|
function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") {
|
||||||
|
const lines = tracks.map((t, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
let name = t.name;
|
||||||
|
if (name.length > 40) name = name.slice(0, 37) + "...";
|
||||||
|
const link = t.url ? `[${name}](${t.url})` : name;
|
||||||
|
const extra = showPlaycount && t.playcount ? ` (${t.playcount} plays)` : "";
|
||||||
|
return `\`${num}.\` ${link} — **${t.artist}**${extra}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(`${title} — ${username}`)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a scrobble leaderboard embed for a given page.
|
||||||
|
* @private
|
||||||
|
* @param {object} lb - Leaderboard data with entries and perPage.
|
||||||
|
* @param {number} pageIdx - The page index (0-based).
|
||||||
|
* @param {string} prefix - The command prefix for the footer hint.
|
||||||
|
* @returns {EmbedBuilder} The constructed embed.
|
||||||
|
*/
|
||||||
|
function buildLeaderboardEmbed(lb, pageIdx, prefix) {
|
||||||
|
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||||
|
const startRank = pageIdx * lb.perPage;
|
||||||
|
|
||||||
|
const lines = lb.entries.map((entry, i) => {
|
||||||
|
const rank = startRank + i + 1;
|
||||||
|
const medal = rank <= 3 ? MEDALS[rank - 1] : ` `;
|
||||||
|
const name = entry.username || entry.userId;
|
||||||
|
const count = Utils.formatNumber(entry.scrobbleCount);
|
||||||
|
return `${medal} ${rank}. **${name}** — ${count} scrobbles`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle("🎵 Scrobble Leaderboard")
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: `💡 View & sync your count: ${prefix}lastfm profile` });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @param {object} lastfm - The Last.fm manager instance.
|
||||||
|
* @param {string} prefix - The guild command prefix.
|
||||||
|
* @param {string} userId - The invoking user's ID.
|
||||||
|
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||||
|
* @param {string} action - The resolved action name.
|
||||||
|
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||||
|
*/
|
||||||
|
export async function runListeningActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
|
switch (action) {
|
||||||
|
case "loved": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let tracks;
|
||||||
|
try {
|
||||||
|
tracks = await lastfm.getLovedTracks(userId, 15);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tracks.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noLoved", { username: user.username }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.lovedTitle", { username: user.username }), tracks, false, prefix)] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "top": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const period = extractPeriod(data, msg);
|
||||||
|
|
||||||
|
let tracks;
|
||||||
|
try {
|
||||||
|
tracks = await lastfm.getTopTracks(userId, period, 15);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tracks.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTop", { username: user.username }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
||||||
|
return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.topTitle", { username: user.username }) + periodLabel, tracks, true, prefix)] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "leaderboard":
|
||||||
|
case "lb": {
|
||||||
|
let lb;
|
||||||
|
try {
|
||||||
|
lb = await lastfm.getLeaderboard(0, 10);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!lb.entries.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||||
|
this.t(msg, "responses.lastfm.leaderboardEmpty", { prefix })
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lb.totalPages <= 1) {
|
||||||
|
const embed = buildLeaderboardEmbed(lb, 0, prefix);
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
let currentPage = 0;
|
||||||
|
|
||||||
|
const buildPage = (pageIdx, expired = false) => {
|
||||||
|
const footerText = expired
|
||||||
|
? this.t(msg, "responses.lastfm.leaderboardControlsExpired")
|
||||||
|
: this.t(msg, "responses.lastfm.leaderboardPageFooter", { current: pageIdx + 1, total: lb.totalPages });
|
||||||
|
const embed = buildLeaderboardEmbed(lb, pageIdx, prefix);
|
||||||
|
embed.setFooter({ text: footerText });
|
||||||
|
return { embeds: [embed] };
|
||||||
|
};
|
||||||
|
|
||||||
|
const replyMsg = await msg.reply(buildPage(0));
|
||||||
|
if (!replyMsg?.message) return;
|
||||||
|
|
||||||
|
const navEmojis = ["◀️", "▶️", "❌"];
|
||||||
|
for (const emoji of navEmojis) {
|
||||||
|
await replyMsg.message.react(emoji).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearReactions = async () => {
|
||||||
|
try {
|
||||||
|
await replyMsg.message.removeAllReactions();
|
||||||
|
} catch {
|
||||||
|
for (const emoji of navEmojis) {
|
||||||
|
try { await replyMsg.message.removeReaction(emoji); } catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let emojiTimeout;
|
||||||
|
const resetTimer = () => {
|
||||||
|
clearTimeout(emojiTimeout);
|
||||||
|
emojiTimeout = setTimeout(async () => {
|
||||||
|
unobserve?.();
|
||||||
|
await clearReactions();
|
||||||
|
await replyMsg.edit(buildPage(currentPage, true)).catch(() => {});
|
||||||
|
}, EMOJI_REMOVE_TIMEOUT);
|
||||||
|
};
|
||||||
|
|
||||||
|
const unobserve = replyMsg.onReaction(navEmojis, async (e) => {
|
||||||
|
if (e.emoji_id === "❌") {
|
||||||
|
clearTimeout(emojiTimeout);
|
||||||
|
unobserve?.();
|
||||||
|
await replyMsg.message.delete().catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
resetTimer();
|
||||||
|
|
||||||
|
if (e.emoji_id === "◀️") {
|
||||||
|
currentPage = currentPage > 0 ? currentPage - 1 : lb.totalPages - 1;
|
||||||
|
} else if (e.emoji_id === "▶️") {
|
||||||
|
currentPage = currentPage < lb.totalPages - 1 ? currentPage + 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
lb = await lastfm.getLeaderboard(currentPage, 10);
|
||||||
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
|
||||||
|
await replyMsg.edit(buildPage(currentPage)).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
resetTimer();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "recent": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let tracks;
|
||||||
|
try {
|
||||||
|
tracks = await lastfm.getRecentTracks(userId, 15);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tracks.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noRecent", { username: user.username }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.recentTitle", { username: user.username }), tracks, false, prefix)] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "artists": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const period = extractPeriod(data, msg);
|
||||||
|
|
||||||
|
let artists;
|
||||||
|
try {
|
||||||
|
artists = await lastfm.getTopArtists(userId, period, 15);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!artists.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noArtists", { username: user.username }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const periodLabel = period !== "overall" ? ` (${period})` : "";
|
||||||
|
const lines = artists.map((a, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
let name = a.name;
|
||||||
|
if (name.length > 40) name = name.slice(0, 37) + "...";
|
||||||
|
const link = a.url ? `[${name}](${a.url})` : name;
|
||||||
|
return `\`${num}.\` ${link} — **${a.playcount}** plays`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.artistsTitle", { username: user.username }) + periodLabel)
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.artistsFooter", { prefix }) })]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "love": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const pLove = await this.getPlayer(msg, false, false, false);
|
||||||
|
if (!pLove) return;
|
||||||
|
const track = pLove.queue?.getCurrent();
|
||||||
|
if (!track) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingLove"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? "Unknown";
|
||||||
|
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown";
|
||||||
|
|
||||||
|
try {
|
||||||
|
await lastfm.loveTrack(userId, artist, name);
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.lovedTrack", { name, artist }))]
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.loveFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case "unlove": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const pUnlove = await this.getPlayer(msg, false, false, false);
|
||||||
|
if (!pUnlove) return;
|
||||||
|
const track = pUnlove.queue?.getCurrent();
|
||||||
|
if (!track) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingUnlove"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? "Unknown";
|
||||||
|
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown";
|
||||||
|
|
||||||
|
try {
|
||||||
|
await lastfm.unloveTrack(userId, artist, name);
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.unlovedTrack", { name, artist }))]
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.unloveFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm/playback
|
||||||
|
* @description The `play` action plus the shared Last.fm playback pipeline (playLastFmCategory, kept exported for commands/play.mjs, plus its private helpers). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
import { PROVIDER_CHOICES } from "../../src/music/providers.mjs";
|
||||||
|
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||||
|
import { notConfigured, notLinked } from "./shared.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Action names dispatched to this module.
|
||||||
|
* @type {Set<string>}
|
||||||
|
*/
|
||||||
|
export const PLAYBACK_ACTIONS = new Set([
|
||||||
|
"play"
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums", "artists"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a Last.fm track metadata object from a track.
|
||||||
|
* @private
|
||||||
|
* @param {object} track - The track object with artist, name, and url.
|
||||||
|
* @returns {{ source: string, artist: string, name: string, url: string }} Track metadata.
|
||||||
|
*/
|
||||||
|
function buildLastFmTrackMeta(track) {
|
||||||
|
return {
|
||||||
|
source: "lastfm",
|
||||||
|
artist: track.artist,
|
||||||
|
name: track.name,
|
||||||
|
url: track.url ?? "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a Last.fm track to playable audio via a search provider.
|
||||||
|
* @private
|
||||||
|
* @async
|
||||||
|
* @param {object} player - The player instance.
|
||||||
|
* @param {object} track - The Last.fm track with query and metadata.
|
||||||
|
* @param {string} [resolveProvider="yt"] - The provider to resolve with.
|
||||||
|
* @returns {Promise<object[]|null>} Array of resolved track data, or null on failure.
|
||||||
|
*/
|
||||||
|
async function resolveLastFmTrack(player, track, resolveProvider = "yt") {
|
||||||
|
const data = await player.generalQuery({
|
||||||
|
query: track.query,
|
||||||
|
provider: resolveProvider,
|
||||||
|
trackMeta: buildLastFmTrackMeta(track),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!data || data.type === "error") return null;
|
||||||
|
if (data.type === "video") return [data.data];
|
||||||
|
if (data.type === "list") return data.data ?? [];
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch and play tracks from a Last.fm category (loved, top, recent, albums, artists, playlist).
|
||||||
|
* @async
|
||||||
|
* @param {object} ctx - The bot (Remix) instance context.
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {string} userId - The user ID.
|
||||||
|
* @param {string} category - The Last.fm category to play.
|
||||||
|
* @param {object} [options={}] - Additional options.
|
||||||
|
* @param {string} [options.resolveProvider="yt"] - Provider to resolve tracks with.
|
||||||
|
* @param {string} [options.playlistId] - Playlist number for playlist category.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function playLastFmCategory(ctx, msg, userId, category, options = {}) {
|
||||||
|
const lastfm = ctx.lastfm;
|
||||||
|
const prefix = ctx.handler.getPrefix(msg.message?.guildId);
|
||||||
|
const resolveProvider = options.resolveProvider || "yt";
|
||||||
|
|
||||||
|
if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(ctx, msg));
|
||||||
|
|
||||||
|
const validCategories = [...SIMPLE_CATEGORIES, "playlist"];
|
||||||
|
if (!validCategories.includes(category)) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
|
`❌ Unknown category \`${category}\`. Use \`loved\`, \`top\`, \`recent\`, \`albums\`, \`artists\`, or \`playlist\`.`
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (category === "playlist" && !options.playlistId) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
|
`❌ Specify a playlist number. Use \`${prefix}lastfm playlists\` to see your playlists, then \`${prefix}lastfm play playlist <number>\`.`
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(ctx, msg, prefix));
|
||||||
|
|
||||||
|
const p = await ctx.getPlayer(msg, true, true, true);
|
||||||
|
if (!p) return;
|
||||||
|
|
||||||
|
const categoryEmoji = { loved: "❤️", top: "📊", recent: "🕐", playlist: "📋", albums: "💿", artists: "🎤" }[category];
|
||||||
|
const categoryLabel = { loved: "Loved", top: "Top", recent: "Recent", playlist: "Playlist", albums: "Top Albums", artists: "Top Artists" }[category];
|
||||||
|
|
||||||
|
const resolveLabel = resolveProvider !== "yt" ? ` via ${resolveProvider.toUpperCase()}` : "";
|
||||||
|
|
||||||
|
let statusMsg;
|
||||||
|
try {
|
||||||
|
statusMsg = await msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||||
|
`${categoryEmoji} Fetching your ${categoryLabel} tracks from Last.fm${resolveLabel}...`
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||||
|
|
||||||
|
let result;
|
||||||
|
try {
|
||||||
|
result = await lastfm.getTracksForPlay(userId, category, options);
|
||||||
|
} catch (err) {
|
||||||
|
const errMsg = err.message === "NOT_LINKED"
|
||||||
|
? notLinked(ctx, msg, prefix)
|
||||||
|
: { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(ctx.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||||
|
if (statusMsg) statusMsg.edit(errMsg).catch(() => msg.reply(errMsg));
|
||||||
|
else msg.reply(errMsg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!result.tracks.length) {
|
||||||
|
const noTracks = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||||
|
`${categoryEmoji} No ${categoryLabel.toLowerCase()} tracks found for **${result.username}**.`
|
||||||
|
)] };
|
||||||
|
if (statusMsg) statusMsg.edit(noTracks).catch(() => msg.reply(noTracks));
|
||||||
|
else msg.reply(noTracks);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let added = 0;
|
||||||
|
let failed = 0;
|
||||||
|
|
||||||
|
if (statusMsg) {
|
||||||
|
statusMsg.edit({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||||
|
`${categoryEmoji} Loading **${result.tracks.length}** ${categoryLabel.toLowerCase()} tracks from **${result.username}**${resolveLabel}...`
|
||||||
|
)]
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const track of result.tracks) {
|
||||||
|
try {
|
||||||
|
const resolvedTracks = await resolveLastFmTrack(p, track, resolveProvider);
|
||||||
|
if (!resolvedTracks?.length) {
|
||||||
|
failed++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
p.addManyToQueue(resolvedTracks, false);
|
||||||
|
added += resolvedTracks.length;
|
||||||
|
|
||||||
|
if (!p.queue.getCurrent()) {
|
||||||
|
p.playNext();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[LastfmCmd] Track resolve failed:", e?.message);
|
||||||
|
failed++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary = [];
|
||||||
|
if (added > 0) summary.push(`✅ Added **${added}** track${added !== 1 ? "s" : ""} to the queue`);
|
||||||
|
if (failed > 0) summary.push(`⚠️ ${failed} track${failed !== 1 ? "s" : ""} couldn't be found`);
|
||||||
|
|
||||||
|
const doneEmbed = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||||
|
`${categoryEmoji} **${categoryLabel} Tracks — ${result.username}**\n${summary.join(" · ")}`
|
||||||
|
)] };
|
||||||
|
|
||||||
|
if (statusMsg) statusMsg.edit(doneEmbed).catch(() => msg.reply(doneEmbed));
|
||||||
|
else msg.reply(doneEmbed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse play subcommand arguments for category and provider.
|
||||||
|
* @private
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @returns {{ category: string, resolveProvider?: string, playlistId?: string, showAllCategories?: boolean, invalidCategory?: string }} Parsed args.
|
||||||
|
*/
|
||||||
|
function parsePlayArgs(msg, data) {
|
||||||
|
let raw = data.get("token")?.value;
|
||||||
|
if (!raw) {
|
||||||
|
const content = msg.message?.content ?? "";
|
||||||
|
const args = content.split(/\s+/);
|
||||||
|
const playIdx = args.indexOf("play");
|
||||||
|
if (playIdx >= 0 && args[playIdx + 1]) {
|
||||||
|
raw = args.slice(playIdx + 1).join(" ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!raw) return { category: "" };
|
||||||
|
|
||||||
|
const lower = raw.toLowerCase().trim();
|
||||||
|
|
||||||
|
const subMatch = lower.match(/^([a-z]+):\s*(.*)$/);
|
||||||
|
if (subMatch) {
|
||||||
|
const maybeProvider = subMatch[1];
|
||||||
|
const rest = subMatch[2].trim();
|
||||||
|
if (PROVIDER_CHOICES.includes(maybeProvider)) {
|
||||||
|
const isLastFmProvider = maybeProvider === "lf" || maybeProvider === "lastfm";
|
||||||
|
|
||||||
|
if (!rest) {
|
||||||
|
if (isLastFmProvider) {
|
||||||
|
return { category: "", resolveProvider: maybeProvider, showAllCategories: true };
|
||||||
|
}
|
||||||
|
return { category: "top", resolveProvider: maybeProvider };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isLastFmProvider) {
|
||||||
|
const playlistMatch = rest.match(/^playlist\s+(\d+)$/);
|
||||||
|
if (playlistMatch) {
|
||||||
|
return { category: "playlist", playlistId: playlistMatch[1], resolveProvider: maybeProvider };
|
||||||
|
}
|
||||||
|
if (SIMPLE_CATEGORIES.includes(rest)) {
|
||||||
|
return { category: rest, resolveProvider: maybeProvider };
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (rest === "top") {
|
||||||
|
return { category: "top", resolveProvider: maybeProvider };
|
||||||
|
}
|
||||||
|
return { category: "", resolveProvider: maybeProvider, invalidCategory: rest };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (PROVIDER_CHOICES.includes(lower)) {
|
||||||
|
const isLastFmProvider = lower === "lf" || lower === "lastfm";
|
||||||
|
if (isLastFmProvider) {
|
||||||
|
return { category: "", resolveProvider: lower, showAllCategories: true };
|
||||||
|
}
|
||||||
|
return { category: "top", resolveProvider: lower };
|
||||||
|
}
|
||||||
|
|
||||||
|
const playlistMatch = lower.match(/^playlist\s+(\d+)$/);
|
||||||
|
if (playlistMatch) {
|
||||||
|
return { category: "playlist", playlistId: playlistMatch[1] };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (SIMPLE_CATEGORIES.includes(lower)) {
|
||||||
|
return { category: lower };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { category: "" };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @param {object} lastfm - The Last.fm manager instance.
|
||||||
|
* @param {string} prefix - The guild command prefix.
|
||||||
|
* @param {string} userId - The invoking user's ID.
|
||||||
|
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||||
|
* @param {string} action - The resolved action name.
|
||||||
|
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||||
|
*/
|
||||||
|
export async function runPlaybackActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
|
switch (action) {
|
||||||
|
case "play": {
|
||||||
|
const parsed = parsePlayArgs(msg, data);
|
||||||
|
|
||||||
|
if (parsed.invalidCategory) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
|
`❌ \`${parsed.resolveProvider}:${parsed.invalidCategory}\` is not valid. Non-Last.fm providers only support \`top\`.\nUse \`${prefix}lastfm play ${parsed.resolveProvider}\` or \`${prefix}lastfm play ${parsed.resolveProvider}:top\` instead.\nFor other categories, use Last.fm as the resolve provider: \`${prefix}lastfm play lf:${parsed.invalidCategory}\``
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!parsed.category) {
|
||||||
|
const lfProviderNote = parsed.showAllCategories && parsed.resolveProvider
|
||||||
|
? `\n\n💡 \`${prefix}lastfm play ${parsed.resolveProvider}:<category>\` — Specify a category after the provider:`
|
||||||
|
: "";
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([
|
||||||
|
`❌ Usage: \`${prefix}lastfm play <category>\``,
|
||||||
|
``,
|
||||||
|
`**Categories:**`,
|
||||||
|
`\`loved\` — Play your loved tracks`,
|
||||||
|
`\`top\` — Play your top tracks`,
|
||||||
|
`\`recent\` — Play your recent tracks`,
|
||||||
|
`\`albums\` — Play your top albums`,
|
||||||
|
`\`artists\` — Play your top artists' tracks`,
|
||||||
|
`\`playlist <number>\` — Play a playlist (use \`${prefix}lastfm playlists\` to list)`,
|
||||||
|
``,
|
||||||
|
`**With a search provider (defaults to \`top\`):**`,
|
||||||
|
`\`${prefix}lastfm play td\` or \`${prefix}lastfm play td:top\` — Play top tracks, search on Tidal`,
|
||||||
|
`\`${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`,
|
||||||
|
`\`${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`,
|
||||||
|
``,
|
||||||
|
`**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, {
|
||||||
|
playlistId: parsed.playlistId,
|
||||||
|
resolveProvider: parsed.resolveProvider,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm/shared
|
||||||
|
* @description Helpers shared by several lastfm action modules. Bodies
|
||||||
|
* are verbatim from the original single-file command; the `export `
|
||||||
|
* prefixes are the only addition.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||||
|
|
||||||
|
export const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return an embed indicating Last.fm is not configured.
|
||||||
|
* @private
|
||||||
|
* @param {object} ctx - The bot (Remix) instance context.
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @returns {{ embeds: EmbedBuilder[] }} Error embed payload.
|
||||||
|
*/
|
||||||
|
export function notConfigured(ctx, msg) {
|
||||||
|
return {
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(ERROR_COLOR)
|
||||||
|
.setDescription(ctx.t(msg, "responses.lastfm.notConfigured"))]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return an embed indicating the user has not linked their Last.fm account.
|
||||||
|
* @private
|
||||||
|
* @param {object} ctx - The bot (Remix) instance context.
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {string} prefix - The guild's command prefix.
|
||||||
|
* @returns {{ embeds: EmbedBuilder[] }} Error embed payload.
|
||||||
|
*/
|
||||||
|
export function notLinked(ctx, msg, prefix) {
|
||||||
|
return {
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setDescription(ctx.t(msg, "responses.lastfm.notLinked", { prefix }))]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract Last.fm-relevant info from the player's current track.
|
||||||
|
* @private
|
||||||
|
* @param {object} player - The player instance.
|
||||||
|
* @returns {{ artist: string|null, name: string|null, album: string|null, track: object|null }} Extracted track info.
|
||||||
|
*/
|
||||||
|
export function extractCurrentTrack(player) {
|
||||||
|
const track = player?.queue?.getCurrent();
|
||||||
|
if (!track) return null;
|
||||||
|
const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? null;
|
||||||
|
const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? null;
|
||||||
|
const album = track.album ?? track.lastfm?.album ?? null;
|
||||||
|
return { artist, name, album, track };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract a valid time period from command data or message content.
|
||||||
|
* @private
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @returns {string} The period string, defaults to "overall".
|
||||||
|
*/
|
||||||
|
export function extractPeriod(data, msg) {
|
||||||
|
let raw = data.get("token")?.value;
|
||||||
|
if (!raw) {
|
||||||
|
const content = msg.message?.content ?? "";
|
||||||
|
const args = content.split(/\s+/);
|
||||||
|
const last = args[args.length - 1];
|
||||||
|
if (last && VALID_PERIODS.includes(last.toLowerCase())) raw = last;
|
||||||
|
}
|
||||||
|
if (raw && VALID_PERIODS.includes(raw.toLowerCase().trim())) {
|
||||||
|
return raw.toLowerCase().trim();
|
||||||
|
}
|
||||||
|
return "overall";
|
||||||
|
}
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm/tags
|
||||||
|
* @description Tag/genre actions for the lastfm command (tag, artisttags, albumtags, tracktags, tagalbums). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { Utils } from "../../src/utils/Utils.mjs";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||||
|
import { extractCurrentTrack } from "./shared.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Action names dispatched to this module.
|
||||||
|
* @type {Set<string>}
|
||||||
|
*/
|
||||||
|
export const TAG_ACTIONS = new Set([
|
||||||
|
"tag",,
|
||||||
|
"artisttags",,
|
||||||
|
"at",,
|
||||||
|
"albumtags",,
|
||||||
|
"alt",,
|
||||||
|
"tracktags",,
|
||||||
|
"tt",,
|
||||||
|
"tagalbums",,
|
||||||
|
"ta"
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @param {object} lastfm - The Last.fm manager instance.
|
||||||
|
* @param {string} prefix - The guild command prefix.
|
||||||
|
* @param {string} userId - The invoking user's ID.
|
||||||
|
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||||
|
* @param {string} action - The resolved action name.
|
||||||
|
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||||
|
*/
|
||||||
|
export async function runTagActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
|
switch (action) {
|
||||||
|
case "tag": {
|
||||||
|
const tagName = data.get("token")?.value;
|
||||||
|
if (!tagName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
|
this.t(msg, "responses.lastfm.tagProvideName", { prefix })
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let tagInfo;
|
||||||
|
let topTracks;
|
||||||
|
let topArtists;
|
||||||
|
|
||||||
|
try {
|
||||||
|
[tagInfo, topTracks, topArtists] = await Promise.all([
|
||||||
|
lastfm.getTagInfo(tagName),
|
||||||
|
lastfm.getTagTopTracks(tagName, 5),
|
||||||
|
lastfm.getTagTopArtists(tagName, 5),
|
||||||
|
]);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tagInfo) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tagNotFound", { tag: tagName }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(`🏷️ ${tagInfo.name}`)
|
||||||
|
.setURL(tagInfo.url || undefined);
|
||||||
|
|
||||||
|
const fields = [];
|
||||||
|
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)}** 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) {
|
||||||
|
const cleanSummary = tagInfo.summary.replace(/<[^>]*>/g, "").trim();
|
||||||
|
if (cleanSummary.length > 0) {
|
||||||
|
const truncated = cleanSummary.length > 300 ? cleanSummary.slice(0, 297) + "..." : cleanSummary;
|
||||||
|
embed.setDescription(truncated);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "artisttags":
|
||||||
|
case "at": {
|
||||||
|
let artistName = null;
|
||||||
|
|
||||||
|
const pAt = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pAt);
|
||||||
|
if (current?.artist) {
|
||||||
|
artistName = current.artist;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenTextAt = data.get("token")?.value;
|
||||||
|
if (tokenTextAt) {
|
||||||
|
artistName = tokenTextAt.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!artistName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let tags;
|
||||||
|
try {
|
||||||
|
tags = await lastfm.getArtistTopTags(artistName, 15);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tags.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noArtistTags", { artist: artistName }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = tags.map((t, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
|
return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: artistName }))
|
||||||
|
.setDescription(desc)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "albumtags":
|
||||||
|
case "alt": {
|
||||||
|
let artistName = null;
|
||||||
|
let albumName = null;
|
||||||
|
|
||||||
|
const pAlt = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pAlt);
|
||||||
|
if (current?.album && current?.artist) {
|
||||||
|
artistName = current.artist;
|
||||||
|
albumName = current.album;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenTextAlt = data.get("token")?.value;
|
||||||
|
if (tokenTextAlt) {
|
||||||
|
const dashMatch = tokenTextAlt.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
|
if (dashMatch) {
|
||||||
|
artistName = dashMatch[1].trim();
|
||||||
|
albumName = dashMatch[2].trim();
|
||||||
|
} else {
|
||||||
|
albumName = tokenTextAlt.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!albumName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let tags;
|
||||||
|
try {
|
||||||
|
tags = await lastfm.getAlbumTopTags(artistName || "", albumName, 15);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tags.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🏷️ No tags found for album **${albumName}**.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = tags.map((t, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
|
return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: albumName }))
|
||||||
|
.setDescription(desc)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "tracktags":
|
||||||
|
case "tt": {
|
||||||
|
let artistName = null;
|
||||||
|
let trackName = null;
|
||||||
|
|
||||||
|
const pTt = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pTt);
|
||||||
|
if (current?.artist && current?.name) {
|
||||||
|
artistName = current.artist;
|
||||||
|
trackName = current.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenTextTt = data.get("token")?.value;
|
||||||
|
if (tokenTextTt) {
|
||||||
|
const dashMatch = tokenTextTt.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
|
if (dashMatch) {
|
||||||
|
artistName = dashMatch[1].trim();
|
||||||
|
trackName = dashMatch[2].trim();
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const searchResult = await lastfm.searchTrack(tokenTextTt.trim());
|
||||||
|
if (searchResult) {
|
||||||
|
artistName = searchResult.artist;
|
||||||
|
trackName = searchResult.name;
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!artistName || !trackName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let tags;
|
||||||
|
try {
|
||||||
|
tags = await lastfm.getTrackTopTags(artistName, trackName, 15);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tags.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🏷️ No tags found for **${trackName}** by **${artistName}**.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = tags.map((t, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = t.url ? `[${t.name}](${t.url})` : t.name;
|
||||||
|
return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: trackName }))
|
||||||
|
.setDescription(desc)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "tagalbums":
|
||||||
|
case "ta": {
|
||||||
|
const tagName = data.get("token")?.value;
|
||||||
|
if (!tagName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a tag name via the token option. Example: \`${prefix}lastfm tagalbums rock\``)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let albums;
|
||||||
|
try {
|
||||||
|
albums = await lastfm.getTagTopAlbums(tagName.trim(), 15);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!albums.length) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`💿 No top albums found for tag **${tagName}**.`)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = albums.map((a, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||||
|
return `\`${num}.\` ${link} by **${a.artist}**${a.playcount > 0 ? ` (${Utils.formatNumber(a.playcount)} plays)` : ""}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(`💿 Top Albums — ${tagName}`)
|
||||||
|
.setDescription(desc);
|
||||||
|
|
||||||
|
if (albums[0]?.image) {
|
||||||
|
embed.setThumbnail(albums[0].image);
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,525 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/lastfm/whoknows
|
||||||
|
* @description Server-social actions for the lastfm command (whoknows, whoknowstrack, whoknowsalbum, affinity, crowns, compare, refreshmembers) with the guild-member helper. Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { Utils } from "../../src/utils/Utils.mjs";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
import { ERROR_COLOR } from "../../src/utils/UI.mjs";
|
||||||
|
import { notLinked, extractCurrentTrack } from "./shared.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Action names dispatched to this module.
|
||||||
|
* @type {Set<string>}
|
||||||
|
*/
|
||||||
|
export const WHOKNOWS_ACTIONS = new Set([
|
||||||
|
"whoknows",,
|
||||||
|
"wk",,
|
||||||
|
"compare",,
|
||||||
|
"fmc",,
|
||||||
|
"refreshmembers",,
|
||||||
|
"rm",,
|
||||||
|
"affinity",,
|
||||||
|
"af",,
|
||||||
|
"crowns",,
|
||||||
|
"cr",,
|
||||||
|
"whoknowstrack",,
|
||||||
|
"wkt",,
|
||||||
|
"whoknowsalbum",,
|
||||||
|
"wka"
|
||||||
|
]);
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all non-bot user IDs in a guild.
|
||||||
|
* @private
|
||||||
|
* @async
|
||||||
|
* @param {object} guild - The guild object.
|
||||||
|
* @returns {Promise<string[]>} Array of user ID strings.
|
||||||
|
*/
|
||||||
|
async function getGuildLinkedUsers(guild) {
|
||||||
|
const memberIds = [];
|
||||||
|
try {
|
||||||
|
const members = guild?.members;
|
||||||
|
if (members) {
|
||||||
|
const iter = typeof members.values === "function" ? members.values() : Object.values(members);
|
||||||
|
for (const m of iter) {
|
||||||
|
const userId = m.user?.id ?? m.id;
|
||||||
|
if (userId && !m.user?.bot) memberIds.push(String(userId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
return memberIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} data - Parsed command data.
|
||||||
|
* @param {object} lastfm - The Last.fm manager instance.
|
||||||
|
* @param {string} prefix - The guild command prefix.
|
||||||
|
* @param {string} userId - The invoking user's ID.
|
||||||
|
* @param {string|null} targetUserId - The targeted user's ID, if any.
|
||||||
|
* @param {string} action - The resolved action name.
|
||||||
|
* @returns {Promise<*>} Whatever the original switch returned for this action.
|
||||||
|
*/
|
||||||
|
export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targetUserId, action) {
|
||||||
|
switch (action) {
|
||||||
|
case "whoknows":
|
||||||
|
case "wk": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let artistName = null;
|
||||||
|
const tokenTextWk = data.get("token")?.value;
|
||||||
|
if (tokenTextWk) {
|
||||||
|
artistName = tokenTextWk.trim();
|
||||||
|
} else {
|
||||||
|
const pWk = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pWk);
|
||||||
|
if (current?.artist) {
|
||||||
|
artistName = current.artist;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!artistName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingNoArtist"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let statusMsg;
|
||||||
|
try {
|
||||||
|
statusMsg = await msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||||
|
this.t(msg, "responses.lastfm.whoknowsChecking", { artist: artistName })
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||||
|
|
||||||
|
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||||
|
const memberIds = await getGuildLinkedUsers(guild);
|
||||||
|
|
||||||
|
let listeners;
|
||||||
|
try {
|
||||||
|
listeners = await lastfm.getWhoKnows(artistName, memberIds);
|
||||||
|
} catch (err) {
|
||||||
|
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||||
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
|
else msg.reply(errEmbed);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!listeners.length) {
|
||||||
|
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(
|
||||||
|
this.t(msg, "responses.lastfm.whoknowsNobody", { artist: artistName })
|
||||||
|
)] };
|
||||||
|
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||||
|
else msg.reply(noData);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||||
|
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
||||||
|
|
||||||
|
const lines = listeners.map((l, i) => {
|
||||||
|
const medal = i < 3 ? MEDALS[i] : ` `;
|
||||||
|
return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.whoknowsTitle", { artist: artistName }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) });
|
||||||
|
|
||||||
|
const replyPayload = { embeds: [embed] };
|
||||||
|
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||||
|
else msg.reply(replyPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "compare":
|
||||||
|
case "fmc": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
if (!targetUserId) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
|
this.t(msg, "responses.lastfm.compareSpecifyUser", { prefix })
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetUser = await lastfm.getUser(targetUserId);
|
||||||
|
if (!targetUser) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(
|
||||||
|
this.t(msg, "responses.lastfm.compareUserNotLinked")
|
||||||
|
)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let comparison;
|
||||||
|
try {
|
||||||
|
comparison = await lastfm.compareUsers(userId, targetUserId);
|
||||||
|
} catch (err) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!comparison) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.compareFailed"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.compareTitle"))
|
||||||
|
.setDescription([
|
||||||
|
`**${comparison.user1.username}** vs **${comparison.user2.username}**`,
|
||||||
|
``,
|
||||||
|
`📊 **${comparison.matchPercentage}%** match`,
|
||||||
|
``,
|
||||||
|
`👤 ${comparison.user1.username}: ${comparison.user1.totalArtists} top artists`,
|
||||||
|
`👤 ${comparison.user2.username}: ${comparison.user2.totalArtists} top artists`,
|
||||||
|
].join("\n"));
|
||||||
|
|
||||||
|
if (comparison.commonArtists?.length) {
|
||||||
|
const commonStr = comparison.commonArtists.slice(0, 15).map((a, i) => {
|
||||||
|
const num = String(i + 1).padStart(2, " ");
|
||||||
|
const link = a.url ? `[${a.name}](${a.url})` : a.name;
|
||||||
|
return `\`${num}.\` ${link} (**${a.playcount}** plays)`;
|
||||||
|
}).join("\n");
|
||||||
|
embed.addFields({ name: `Common Artists (${comparison.commonArtists.length})`, value: commonStr.slice(0, 1024), inline: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg.reply({ embeds: [embed] });
|
||||||
|
}
|
||||||
|
|
||||||
|
case "refreshmembers":
|
||||||
|
case "rm": {
|
||||||
|
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||||
|
if (!guild) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.refreshFailed"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let count = 0;
|
||||||
|
try {
|
||||||
|
if (guild.members && typeof guild.members.fetch === "function") {
|
||||||
|
const fetched = await guild.members.fetch();
|
||||||
|
count = fetched.size;
|
||||||
|
} else {
|
||||||
|
const memberIds = await getGuildLinkedUsers(guild);
|
||||||
|
count = memberIds.length;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
const memberIds = await getGuildLinkedUsers(guild);
|
||||||
|
count = memberIds.length;
|
||||||
|
}
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.refreshSuccess", { count: Utils.formatNumber(count) }))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
case "affinity":
|
||||||
|
case "af": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||||
|
const memberIds = await getGuildLinkedUsers(guild);
|
||||||
|
|
||||||
|
if (memberIds.length < 2) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityNeedUsers"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let statusMsg;
|
||||||
|
try {
|
||||||
|
statusMsg = await msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityChecking"))]
|
||||||
|
});
|
||||||
|
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||||
|
|
||||||
|
let affinityResults;
|
||||||
|
try {
|
||||||
|
affinityResults = await lastfm.getAffinity(memberIds, 10);
|
||||||
|
} catch (err) {
|
||||||
|
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||||
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
|
else msg.reply(errEmbed);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!affinityResults.length) {
|
||||||
|
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityNoCommon"))] };
|
||||||
|
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||||
|
else msg.reply(noData);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = affinityResults.map(r => {
|
||||||
|
const topCommon = r.commonArtists.slice(0, 3).map(a => a.name).join(", ");
|
||||||
|
return `**${r.users[0]}** & **${r.users[1]}** — ${r.matchCount} common artists (${topCommon}${r.commonArtists.length > 3 ? "..." : ""})`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.affinityTitle"))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.affinityFooter", { count: memberIds.length }) });
|
||||||
|
|
||||||
|
const replyPayload = { embeds: [embed] };
|
||||||
|
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||||
|
else msg.reply(replyPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "crowns":
|
||||||
|
case "cr": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||||
|
const memberIds = await getGuildLinkedUsers(guild);
|
||||||
|
|
||||||
|
let statusMsg;
|
||||||
|
try {
|
||||||
|
statusMsg = await msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.crownsChecking"))]
|
||||||
|
});
|
||||||
|
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||||
|
|
||||||
|
let crowns;
|
||||||
|
try {
|
||||||
|
crowns = await lastfm.getCrowns(userId, memberIds);
|
||||||
|
} catch (err) {
|
||||||
|
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||||
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
|
else msg.reply(errEmbed);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!crowns.length) {
|
||||||
|
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.crownsNone"))] };
|
||||||
|
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||||
|
else msg.reply(noData);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenFilter = data.get("token")?.value?.toLowerCase().trim();
|
||||||
|
|
||||||
|
let filteredCrowns = crowns;
|
||||||
|
if (tokenFilter === "stolen") {
|
||||||
|
filteredCrowns = crowns.filter(c => c.nextBest && c.nextBest.playcount > 0);
|
||||||
|
} else if (tokenFilter === "recent") {
|
||||||
|
filteredCrowns = crowns.slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
const lines = filteredCrowns.slice(0, 20).map(c => {
|
||||||
|
const link = c.artistUrl ? `[${c.artist}](${c.artistUrl})` : c.artist;
|
||||||
|
const nextStr = c.nextBest ? ` (next: **${c.nextBest.username}** with ${Utils.formatNumber(c.nextBest.playcount)})` : "";
|
||||||
|
return `👑 ${link} — **${Utils.formatNumber(c.userPlaycount)}** plays${nextStr}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.crownsTitle", { username: user.username }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.crownsFooter", { count: filteredCrowns.length, plural: filteredCrowns.length !== 1 ? "s" : "" }) });
|
||||||
|
|
||||||
|
if (filteredCrowns[0]?.image) {
|
||||||
|
embed.setThumbnail(filteredCrowns[0].image);
|
||||||
|
}
|
||||||
|
|
||||||
|
const replyPayload = { embeds: [embed] };
|
||||||
|
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||||
|
else msg.reply(replyPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "whoknowstrack":
|
||||||
|
case "wkt": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let artistName = null;
|
||||||
|
let trackName = null;
|
||||||
|
|
||||||
|
const pWkt = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pWkt);
|
||||||
|
if (current?.artist && current?.name) {
|
||||||
|
artistName = current.artist;
|
||||||
|
trackName = current.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenTextWkt = data.get("token")?.value;
|
||||||
|
if (tokenTextWkt) {
|
||||||
|
const dashMatch = tokenTextWkt.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
|
if (dashMatch) {
|
||||||
|
artistName = dashMatch[1].trim();
|
||||||
|
trackName = dashMatch[2].trim();
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const searchResult = await lastfm.searchTrack(tokenTextWkt.trim());
|
||||||
|
if (searchResult) {
|
||||||
|
artistName = searchResult.artist;
|
||||||
|
trackName = searchResult.name;
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[LastFm] Error:", e?.message); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!artistName || !trackName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let statusMsg;
|
||||||
|
try {
|
||||||
|
statusMsg = await msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsTrackChecking", { track: trackName, artist: artistName }))]
|
||||||
|
});
|
||||||
|
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||||
|
|
||||||
|
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||||
|
const memberIds = await getGuildLinkedUsers(guild);
|
||||||
|
|
||||||
|
let listeners;
|
||||||
|
try {
|
||||||
|
listeners = await lastfm.getWhoKnowsTrack(artistName, trackName, memberIds);
|
||||||
|
} catch (err) {
|
||||||
|
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||||
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
|
else msg.reply(errEmbed);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!listeners.length) {
|
||||||
|
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsTrackNobody", { track: trackName, artist: artistName }))] };
|
||||||
|
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||||
|
else msg.reply(noData);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||||
|
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
||||||
|
|
||||||
|
const lines = listeners.map((l, i) => {
|
||||||
|
const medal = i < 3 ? MEDALS[i] : ` `;
|
||||||
|
return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.whoknowsTrackTitle", { track: trackName }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsTrackFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays), artist: artistName }) });
|
||||||
|
|
||||||
|
const replyPayload = { embeds: [embed] };
|
||||||
|
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||||
|
else msg.reply(replyPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
case "whoknowsalbum":
|
||||||
|
case "wka": {
|
||||||
|
const user = await lastfm.getUser(userId);
|
||||||
|
if (!user) return msg.reply(notLinked(this, msg, prefix));
|
||||||
|
|
||||||
|
let artistName = null;
|
||||||
|
let albumName = null;
|
||||||
|
|
||||||
|
const pWka = await this.getPlayer(msg, false, false, false);
|
||||||
|
const current = extractCurrentTrack(pWka);
|
||||||
|
if (current?.album && current?.artist) {
|
||||||
|
artistName = current.artist;
|
||||||
|
albumName = current.album;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenTextWka = data.get("token")?.value;
|
||||||
|
if (tokenTextWka) {
|
||||||
|
const dashMatch = tokenTextWka.match(/^(.+?)\s*[-–—]\s*(.+)$/);
|
||||||
|
if (dashMatch) {
|
||||||
|
artistName = dashMatch[1].trim();
|
||||||
|
albumName = dashMatch[2].trim();
|
||||||
|
} else {
|
||||||
|
albumName = tokenTextWka.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!albumName) {
|
||||||
|
return msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let statusMsg;
|
||||||
|
try {
|
||||||
|
statusMsg = await msg.reply({
|
||||||
|
embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsAlbumChecking", { album: albumName, artistClause: artistName ? ` by **${artistName}**` : "" }))]
|
||||||
|
});
|
||||||
|
} catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; }
|
||||||
|
|
||||||
|
const guild = msg.message?.guild ?? msg.message?.member?.guild;
|
||||||
|
const memberIds = await getGuildLinkedUsers(guild);
|
||||||
|
|
||||||
|
let listeners;
|
||||||
|
try {
|
||||||
|
listeners = await lastfm.getWhoKnowsAlbum(artistName || "", albumName, memberIds);
|
||||||
|
} catch (err) {
|
||||||
|
const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] };
|
||||||
|
if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed));
|
||||||
|
else msg.reply(errEmbed);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!listeners.length) {
|
||||||
|
const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsAlbumNobody", { album: albumName }))] };
|
||||||
|
if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData));
|
||||||
|
else msg.reply(noData);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MEDALS = ["🥇", "🥈", "🥉"];
|
||||||
|
const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0);
|
||||||
|
|
||||||
|
const lines = listeners.map((l, i) => {
|
||||||
|
const medal = i < 3 ? MEDALS[i] : ` `;
|
||||||
|
return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const desc = lines.join("\n").slice(0, 4096);
|
||||||
|
|
||||||
|
const embed = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(this.t(msg, "responses.lastfm.whoknowsAlbumTitle", { album: albumName }))
|
||||||
|
.setDescription(desc)
|
||||||
|
.setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) });
|
||||||
|
|
||||||
|
const replyPayload = { embeds: [embed] };
|
||||||
|
if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload));
|
||||||
|
else msg.reply(replyPayload);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-4
@@ -3,10 +3,10 @@
|
|||||||
* @description Make the bot leave a voice channel, with 24/7 cleanup and player destruction.
|
* @description Make the bot leave a voice channel, with 24/7 cleanup and player destruction.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs";
|
import { getGlobalColor, 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()
|
||||||
@@ -25,7 +25,7 @@ export const command = new CommandBuilder()
|
|||||||
* Resolve the guild ID from a player, its map key, or the channel object.
|
* Resolve the guild ID from a player, its map key, or the channel object.
|
||||||
* @param {Player} player - The player instance.
|
* @param {Player} player - The player instance.
|
||||||
* @param {string} mapKey - The key under which the player is stored in playerMap.
|
* @param {string} mapKey - The key under which the player is stored in playerMap.
|
||||||
* @param {import('@fluxerjs/core').Client} client - The Discord/Fluxer client.
|
* @param {import('@fluxerjs/core').Client} client - The Fluxer client.
|
||||||
* @returns {string} Cleaned guild ID, or empty string if unresolvable.
|
* @returns {string} Cleaned guild ID, or empty string if unresolvable.
|
||||||
*/
|
*/
|
||||||
function resolvePlayerGuildId(player, mapKey, client) {
|
function resolvePlayerGuildId(player, mapKey, client) {
|
||||||
|
|||||||
+2
-2
@@ -3,8 +3,8 @@
|
|||||||
* @description List the songs in the queue of the current voice channel with pagination.
|
* @description List the songs in the queue of the current voice channel with pagination.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { QueuePaginator, getGlobalColor } from "../src/MessageHandler.mjs";
|
import { QueuePaginator, getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
|
||||||
const PAGE_SIZE = 10;
|
const PAGE_SIZE = 10;
|
||||||
|
|||||||
+2
-2
@@ -3,9 +3,9 @@
|
|||||||
* @description Toggle looping of the current song or the entire queue.
|
* @description Toggle looping of the current song or the entire queue.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.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()
|
||||||
|
|||||||
+5
-5
@@ -3,12 +3,12 @@
|
|||||||
* @description Display synced or unsynced lyrics for the currently playing track from NodeLink.
|
* @description Display synced or unsynced lyrics for the currently playing track from NodeLink.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/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()
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
* @description Move a track from one position to another in the queue.
|
* @description Move a track from one position to another in the queue.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/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()
|
||||||
|
|||||||
+2
-2
@@ -3,9 +3,9 @@
|
|||||||
* @description Display the currently playing track name and URL.
|
* @description Display the currently playing track name and URL.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the np (now playing) command. */
|
/** @type {CommandBuilder} @description Command definition for the np (now playing) command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
|
|||||||
+2
-2
@@ -3,9 +3,9 @@
|
|||||||
* @description Pause the currently playing track.
|
* @description Pause the currently playing track.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.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()
|
||||||
|
|||||||
+6
-6
@@ -4,14 +4,14 @@
|
|||||||
* Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and Last.fm integration.
|
* Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and Last.fm integration.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs";
|
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||||
import { playLastFmCategory } from "./lastfm.mjs";
|
import { playLastFmCategory } from "./lastfm.mjs";
|
||||||
import { parseLastFmUrl, isLastFmUrl } from "../src/LastFmManager.mjs";
|
import { parseLastFmUrl, isLastFmUrl } from "../src/services/lastfm/LastFmManager.mjs";
|
||||||
import { ERROR_COLOR } from "../src/constants/UI.mjs";
|
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||||
|
|
||||||
const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
|
const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
|
||||||
|
|
||||||
|
|||||||
+21
-270
@@ -1,15 +1,17 @@
|
|||||||
/**
|
/**
|
||||||
* @module commands/player
|
* @module commands/player
|
||||||
* @description Create an interactive player control panel with live progress, reaction controls,
|
* @description Create an interactive player control panel with live progress, reaction controls,
|
||||||
* and embedded lyrics viewer.
|
* and embedded lyrics viewer. The panel embed construction, display constants and the lyrics
|
||||||
|
* viewer live in commands/player/; run() below owns the session lifecycle (timers, player
|
||||||
|
* event wiring and the control-reaction dispatcher).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { CONTROLS, buildPlayerEmbed, openLyricsViewer, clearLyricsReactions } from "./player/index.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the player command. */
|
/** @type {CommandBuilder} @description Command definition for the player command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
@@ -17,40 +19,6 @@ export const command = new CommandBuilder()
|
|||||||
.setDescription("Create an interactive player control panel with live progress", "commands.player")
|
.setDescription("Create an interactive player control panel with live progress", "commands.player")
|
||||||
.setCategory("music");
|
.setCategory("music");
|
||||||
|
|
||||||
/** @private @type {Object.<string, string>} Emoji indicators for player states. */
|
|
||||||
const STATES = {
|
|
||||||
playing: "🎵",
|
|
||||||
paused: "⏸️",
|
|
||||||
stopped: "🔇",
|
|
||||||
loading: "⏳"
|
|
||||||
};
|
|
||||||
|
|
||||||
/** @private @type {Object.<string, {emoji: string, action: string, desc: string}>} Available control button definitions. */
|
|
||||||
const CONTROLS = {
|
|
||||||
prev: { emoji: "⏮️", action: "previous", desc: "Previous" },
|
|
||||||
play: { emoji: "▶️", action: "resume", desc: "Play" },
|
|
||||||
pause: { emoji: "⏸️", action: "pause", desc: "Pause" },
|
|
||||||
stop: { emoji: "⏹️", action: "stop", desc: "Stop" },
|
|
||||||
next: { emoji: "⏭️", action: "skip", desc: "Skip" },
|
|
||||||
loop: { emoji: "🔁", action: "loop", desc: "Loop" },
|
|
||||||
shuffle: { emoji: "🔀", action: "shuffle", desc: "Shuffle" },
|
|
||||||
volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" },
|
|
||||||
volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" },
|
|
||||||
lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" },
|
|
||||||
filter: { emoji: "🎛️", action: "filter", desc: "Audio Filters" },
|
|
||||||
close: { emoji: "❌", action: "close", desc: "Close" }
|
|
||||||
};
|
|
||||||
|
|
||||||
/** @private @type {Object.<string, string>} Progress bar character set. */
|
|
||||||
const PROGRESS = {
|
|
||||||
filled: "▰",
|
|
||||||
empty: "▱",
|
|
||||||
indicator: "●",
|
|
||||||
start: "▏",
|
|
||||||
end: "▕"
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @async
|
* @async
|
||||||
* Run handler for the player command.
|
* Run handler for the player command.
|
||||||
@@ -73,89 +41,7 @@ export async function run(msg) {
|
|||||||
const allControls = controlsLayout.flat();
|
const allControls = controlsLayout.flat();
|
||||||
const controlEmojis = allControls.map(c => c.emoji);
|
const controlEmojis = allControls.map(c => c.emoji);
|
||||||
|
|
||||||
/**
|
const message = await msg.reply({ embeds: [buildPlayerEmbed(this, msg, player, timeout)] });
|
||||||
* @private
|
|
||||||
* Build the player panel embed with current state, progress, volume, and loop info.
|
|
||||||
* @param {object} [state={}] - Optional state override with a message field.
|
|
||||||
* @returns {EmbedBuilder} The constructed embed builder.
|
|
||||||
*/
|
|
||||||
const buildEmbed = (state = {}) => {
|
|
||||||
const current = player.queue.getCurrent();
|
|
||||||
const isPlaying = !player.paused && current;
|
|
||||||
const statusEmoji = isPlaying ? STATES.playing : player.paused ? STATES.paused : STATES.stopped;
|
|
||||||
|
|
||||||
let progressBar = "";
|
|
||||||
let timeDisplay = "`0:00 / 0:00`";
|
|
||||||
|
|
||||||
if (current?.duration && player.startedPlaying) {
|
|
||||||
const elapsed = Date.now() - player.startedPlaying;
|
|
||||||
const totalMs = typeof current.duration === "object"
|
|
||||||
? (current.duration.seconds ?? 0) * 1000
|
|
||||||
: current.duration;
|
|
||||||
|
|
||||||
const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled);
|
|
||||||
progressBar = PROGRESS.start + bar + PROGRESS.end;
|
|
||||||
|
|
||||||
const elapsedStr = Utils.prettifyMS(elapsed);
|
|
||||||
const totalStr = Utils.prettifyMS(totalMs);
|
|
||||||
timeDisplay = `\`${elapsedStr} / ${totalStr}\``;
|
|
||||||
} else {
|
|
||||||
progressBar = PROGRESS.start + PROGRESS.empty.repeat(20) + PROGRESS.end;
|
|
||||||
}
|
|
||||||
|
|
||||||
const volPercent = Math.round((player.preferredVolume ?? 1) * 100);
|
|
||||||
const volBars = Math.ceil(volPercent / 10);
|
|
||||||
const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars);
|
|
||||||
|
|
||||||
const queueSize = player.queue.size();
|
|
||||||
const loopStatus = player.queue.songLoop ? this.t(msg, "responses.player.loopSong") : player.queue.loop ? this.t(msg, "responses.player.loopQueue") : this.t(msg, "responses.player.loopOff");
|
|
||||||
|
|
||||||
let filterStatus = this.t(msg, "responses.player.filterOff");
|
|
||||||
if (player.activeFilter) {
|
|
||||||
if (player.activeFilter.label.includes("+")) {
|
|
||||||
filterStatus = `🔥 **${player.activeFilter.label}**`;
|
|
||||||
} else {
|
|
||||||
filterStatus = `${player.activeFilter.emoji ?? "🎛️"} **${player.activeFilter.label}**`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const nowPlaying = current
|
|
||||||
? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})`
|
|
||||||
: this.t(msg, "responses.filter.nothingPlayingInline");
|
|
||||||
|
|
||||||
const description = [
|
|
||||||
`${statusEmoji} ${this.t(msg, "responses.player.nowPlayingLabel")}`,
|
|
||||||
`${nowPlaying}`,
|
|
||||||
``,
|
|
||||||
`${progressBar}`,
|
|
||||||
`${timeDisplay}`,
|
|
||||||
``,
|
|
||||||
this.t(msg, "responses.player.volumeLabel", { volume: volPercent }) + " " + volumeBar,
|
|
||||||
`${this.t(msg, "responses.player.queueLabel", { count: queueSize })} | Loop: ${loopStatus} | Filter: ${filterStatus}`,
|
|
||||||
``,
|
|
||||||
state.message ? `💬 *${state.message}*` : `💡 *${this.t(msg, "responses.player.reactHint")}*`,
|
|
||||||
``,
|
|
||||||
this.t(msg, "responses.player.sessionExpires", { minutes: Math.ceil(timeout / 60000) })
|
|
||||||
].join("\n");
|
|
||||||
|
|
||||||
const avatarUrl = typeof msg.author?.avatarURL === "function"
|
|
||||||
? msg.author.avatarURL()
|
|
||||||
: msg.author?.avatarURL ?? null;
|
|
||||||
|
|
||||||
const builder = new EmbedBuilder()
|
|
||||||
.setColor(getGlobalColor())
|
|
||||||
.setTitle(this.t(msg, "responses.player.title"))
|
|
||||||
.setDescription(description)
|
|
||||||
.setFooter({
|
|
||||||
text: this.t(msg, "responses.player.requestedBy", { username: msg.author?.username || "Unknown" }),
|
|
||||||
iconURL: avatarUrl
|
|
||||||
});
|
|
||||||
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
|
||||||
if (current?.thumbnail) builder.setThumbnail(current.thumbnail);
|
|
||||||
return builder;
|
|
||||||
};
|
|
||||||
|
|
||||||
const message = await msg.reply({ embeds: [buildEmbed()] });
|
|
||||||
if (!message?.message) return;
|
if (!message?.message) return;
|
||||||
|
|
||||||
for (const row of controlsLayout) {
|
for (const row of controlsLayout) {
|
||||||
@@ -172,9 +58,8 @@ export async function run(msg) {
|
|||||||
let emojiRemoveTimeout;
|
let emojiRemoveTimeout;
|
||||||
let lastState = {};
|
let lastState = {};
|
||||||
|
|
||||||
let activeLyricsMsg = null;
|
/** @private @type {object} Shared lyrics-viewer session state (cleaned up by closeSession). */
|
||||||
let lyricsUnobserve = null;
|
const lyrics = { activeLyricsMsg: null, unobserve: null, emojiTimeout: null };
|
||||||
let lyricsEmojiTimeout = null;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @private
|
* @private
|
||||||
@@ -202,31 +87,12 @@ export async function run(msg) {
|
|||||||
clearTimeout(emojiRemoveTimeout);
|
clearTimeout(emojiRemoveTimeout);
|
||||||
emojiRemoveTimeout = setTimeout(async () => {
|
emojiRemoveTimeout = setTimeout(async () => {
|
||||||
await clearReactions();
|
await clearReactions();
|
||||||
const disabledEmbed = buildEmbed({ message: this.t(msg, "responses.player.controlsDisabled") });
|
const disabledEmbed = buildPlayerEmbed(this, msg, player, timeout, { message: this.t(msg, "responses.player.controlsDisabled") });
|
||||||
disabledEmbed.footer = { text: this.t(msg, "responses._common.controlsExpired") };
|
disabledEmbed.footer = { text: this.t(msg, "responses._common.controlsExpired") };
|
||||||
await message.edit({ embeds: [disabledEmbed] }).catch(() => {});
|
await message.edit({ embeds: [disabledEmbed] }).catch(() => {});
|
||||||
}, EMOJI_REMOVE_TIMEOUT);
|
}, EMOJI_REMOVE_TIMEOUT);
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* @private
|
|
||||||
* Remove navigation reactions from a lyrics message.
|
|
||||||
* @param {object} lyricsMsg - The wrapped lyrics message with a .message property.
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
const clearLyricsReactions = async (lyricsMsg) => {
|
|
||||||
if (!lyricsMsg?.message) return;
|
|
||||||
try {
|
|
||||||
await lyricsMsg.message.removeAllReactions();
|
|
||||||
} catch (e) {
|
|
||||||
for (const emoji of ["⬅️", "➡️", "❌"]) {
|
|
||||||
try {
|
|
||||||
await lyricsMsg.message.removeReaction(emoji);
|
|
||||||
} catch(e) { logger.warn("[Player] Error:", e?.message); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let editFailures = 0;
|
let editFailures = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -236,7 +102,7 @@ export async function run(msg) {
|
|||||||
* @returns {void}
|
* @returns {void}
|
||||||
*/
|
*/
|
||||||
const refresh = (extra = {}) => {
|
const refresh = (extra = {}) => {
|
||||||
const embed = buildEmbed(extra);
|
const embed = buildPlayerEmbed(this, msg, player, timeout, extra);
|
||||||
message.edit({ embeds: [embed] })
|
message.edit({ embeds: [embed] })
|
||||||
.then(() => { editFailures = 0; })
|
.then(() => { editFailures = 0; })
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
@@ -275,17 +141,17 @@ export async function run(msg) {
|
|||||||
player.off("filter", onFilter);
|
player.off("filter", onFilter);
|
||||||
player.off("autoleave", onAutoLeave);
|
player.off("autoleave", onAutoLeave);
|
||||||
|
|
||||||
if (lyricsUnobserve) {
|
if (lyrics.unobserve) {
|
||||||
lyricsUnobserve();
|
lyrics.unobserve();
|
||||||
clearTimeout(lyricsEmojiTimeout);
|
clearTimeout(lyrics.emojiTimeout);
|
||||||
}
|
}
|
||||||
if (activeLyricsMsg) {
|
if (lyrics.activeLyricsMsg) {
|
||||||
await clearLyricsReactions(activeLyricsMsg);
|
await clearLyricsReactions(lyrics.activeLyricsMsg);
|
||||||
}
|
}
|
||||||
|
|
||||||
await clearReactions();
|
await clearReactions();
|
||||||
|
|
||||||
const closedEmbed = buildEmbed({
|
const closedEmbed = buildPlayerEmbed(this, msg, player, timeout, {
|
||||||
message: this.t(msg, "responses.player.sessionClosed", { reason: reason !== "timeout" ? ` • ${reason}` : "" })
|
message: this.t(msg, "responses.player.sessionClosed", { reason: reason !== "timeout" ? ` • ${reason}` : "" })
|
||||||
});
|
});
|
||||||
closedEmbed.setColor(getGlobalColor());
|
closedEmbed.setColor(getGlobalColor());
|
||||||
@@ -431,122 +297,7 @@ export async function run(msg) {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case "lyrics":
|
case "lyrics":
|
||||||
reply = this.t(msg, "responses.player.fetchingLyrics");
|
reply = await openLyricsViewer(this, msg, player, refresh, lyrics);
|
||||||
refresh({ message: reply });
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (lyricsUnobserve) {
|
|
||||||
lyricsUnobserve();
|
|
||||||
clearTimeout(lyricsEmojiTimeout);
|
|
||||||
if (activeLyricsMsg) await clearLyricsReactions(activeLyricsMsg);
|
|
||||||
}
|
|
||||||
|
|
||||||
const lyricsResult = await player.lyrics();
|
|
||||||
if (!lyricsResult) {
|
|
||||||
reply = this.t(msg, "responses.player.noLyricsFound");
|
|
||||||
shouldUpdate = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
const syncBadge = lyricsResult.synced ? " ⏱️ Synced" : "";
|
|
||||||
const lines = lyricsResult.text.split('\n');
|
|
||||||
const totalLines = lines.length;
|
|
||||||
const LINES_PER_PAGE = 25;
|
|
||||||
const totalPages = Math.ceil(totalLines / LINES_PER_PAGE);
|
|
||||||
|
|
||||||
const pages = [];
|
|
||||||
for (let i = 0; i < totalLines; i += LINES_PER_PAGE) {
|
|
||||||
pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n'));
|
|
||||||
}
|
|
||||||
|
|
||||||
let currentPage = 0;
|
|
||||||
|
|
||||||
const buildLyricsContent = (pageIdx, expired = false, closed = false) => {
|
|
||||||
const title = Utils.truncate(
|
|
||||||
player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '',
|
|
||||||
50
|
|
||||||
);
|
|
||||||
const footerText = closed
|
|
||||||
? `👋 Lyrics closed • NodeLink • ${totalLines} lines`
|
|
||||||
: expired
|
|
||||||
? `⌛ Controls expired • NodeLink • ${totalLines} lines`
|
|
||||||
: `NodeLink • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`;
|
|
||||||
const desc = [
|
|
||||||
`**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`,
|
|
||||||
``,
|
|
||||||
'```',
|
|
||||||
pages[pageIdx],
|
|
||||||
totalPages > 1 && !expired && !closed ? `\n\n💡 ⬅️ ➡️ Navigate • ❌ Close` : '',
|
|
||||||
'```'
|
|
||||||
].join('\n');
|
|
||||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText })] };
|
|
||||||
};
|
|
||||||
|
|
||||||
activeLyricsMsg = await msg.reply(buildLyricsContent(0));
|
|
||||||
|
|
||||||
if (activeLyricsMsg?.message && totalPages > 1) {
|
|
||||||
const navEmojis = ["⬅️", "➡️", "❌"];
|
|
||||||
for (const emoji of navEmojis) {
|
|
||||||
await activeLyricsMsg.message.react(emoji).catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
const resetLyricsTimer = () => {
|
|
||||||
clearTimeout(lyricsEmojiTimeout);
|
|
||||||
lyricsEmojiTimeout = setTimeout(async () => {
|
|
||||||
await clearLyricsReactions(activeLyricsMsg);
|
|
||||||
await activeLyricsMsg.edit(buildLyricsContent(currentPage, true, false)).catch(() => {});
|
|
||||||
}, EMOJI_REMOVE_TIMEOUT);
|
|
||||||
};
|
|
||||||
|
|
||||||
lyricsUnobserve = activeLyricsMsg.onReaction(navEmojis, async (e) => {
|
|
||||||
if (e.emoji_id === "❌") {
|
|
||||||
lyricsUnobserve();
|
|
||||||
clearTimeout(lyricsEmojiTimeout);
|
|
||||||
await clearLyricsReactions(activeLyricsMsg);
|
|
||||||
await activeLyricsMsg.edit(buildLyricsContent(currentPage, false, true)).catch(() => {});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
resetLyricsTimer();
|
|
||||||
|
|
||||||
if (e.emoji_id === "⬅️") {
|
|
||||||
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
|
||||||
} else if (e.emoji_id === "➡️") {
|
|
||||||
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
await activeLyricsMsg.edit(buildLyricsContent(currentPage));
|
|
||||||
});
|
|
||||||
|
|
||||||
resetLyricsTimer();
|
|
||||||
} else if (activeLyricsMsg?.message) {
|
|
||||||
await activeLyricsMsg.message.react("❌").catch(() => {});
|
|
||||||
|
|
||||||
const resetLyricsTimer = () => {
|
|
||||||
clearTimeout(lyricsEmojiTimeout);
|
|
||||||
lyricsEmojiTimeout = setTimeout(async () => {
|
|
||||||
await clearLyricsReactions(activeLyricsMsg);
|
|
||||||
await activeLyricsMsg.edit(buildLyricsContent(0, true, false)).catch(() => {});
|
|
||||||
}, EMOJI_REMOVE_TIMEOUT);
|
|
||||||
};
|
|
||||||
|
|
||||||
lyricsUnobserve = activeLyricsMsg.onReaction(["❌"], async (e) => {
|
|
||||||
if (e.emoji_id === "❌") {
|
|
||||||
lyricsUnobserve();
|
|
||||||
clearTimeout(lyricsEmojiTimeout);
|
|
||||||
await clearLyricsReactions(activeLyricsMsg);
|
|
||||||
await activeLyricsMsg.edit(buildLyricsContent(0, false, true)).catch(() => {});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
resetLyricsTimer();
|
|
||||||
}
|
|
||||||
|
|
||||||
reply = this.t(msg, "responses.player.lyricsDisplayed", { lines: totalLines, pages: totalPages });
|
|
||||||
|
|
||||||
} catch (err) {
|
|
||||||
reply = this.t(msg, "responses.player.lyricsError", { error: Utils.truncate(err.message, 50) });
|
|
||||||
}
|
|
||||||
shouldUpdate = true;
|
shouldUpdate = true;
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/player/consts
|
||||||
|
* @description Pure display constants for the player control panel: state
|
||||||
|
* emoji indicators, control button definitions and progress-bar characters.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** @type {Object.<string, string>} Emoji indicators for player states. */
|
||||||
|
export const STATES = {
|
||||||
|
playing: "🎵",
|
||||||
|
paused: "⏸️",
|
||||||
|
stopped: "🔇",
|
||||||
|
loading: "⏳"
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @type {Object.<string, {emoji: string, action: string, desc: string}>} Available control button definitions. */
|
||||||
|
export const CONTROLS = {
|
||||||
|
prev: { emoji: "⏮️", action: "previous", desc: "Previous" },
|
||||||
|
play: { emoji: "▶️", action: "resume", desc: "Play" },
|
||||||
|
pause: { emoji: "⏸️", action: "pause", desc: "Pause" },
|
||||||
|
stop: { emoji: "⏹️", action: "stop", desc: "Stop" },
|
||||||
|
next: { emoji: "⏭️", action: "skip", desc: "Skip" },
|
||||||
|
loop: { emoji: "🔁", action: "loop", desc: "Loop" },
|
||||||
|
shuffle: { emoji: "🔀", action: "shuffle", desc: "Shuffle" },
|
||||||
|
volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" },
|
||||||
|
volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" },
|
||||||
|
lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" },
|
||||||
|
filter: { emoji: "🎛️", action: "filter", desc: "Audio Filters" },
|
||||||
|
close: { emoji: "❌", action: "close", desc: "Close" }
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @type {Object.<string, string>} Progress bar character set. */
|
||||||
|
export const PROGRESS = {
|
||||||
|
filled: "▰",
|
||||||
|
empty: "▱",
|
||||||
|
indicator: "●",
|
||||||
|
start: "▏",
|
||||||
|
end: "▕"
|
||||||
|
};
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/player/embed
|
||||||
|
* @description Player panel embed construction: state emoji, progress bar,
|
||||||
|
* volume gauge, loop/filter status and footer (verbatim body of the original
|
||||||
|
* run() closure, with the bot instance passed explicitly instead of `this`).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Utils } from "../../src/utils/Utils.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { STATES, PROGRESS } from "./consts.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the player panel embed with current state, progress, volume, and loop info.
|
||||||
|
* @param {object} bot - The bot instance (used for locale translation).
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} player - The guild player.
|
||||||
|
* @param {number} timeout - Session timeout in ms (shown in the footer area).
|
||||||
|
* @param {object} [state={}] - Optional state override with a message field.
|
||||||
|
* @returns {EmbedBuilder} The constructed embed builder.
|
||||||
|
*/
|
||||||
|
export function buildPlayerEmbed(bot, msg, player, timeout, state = {}) {
|
||||||
|
const current = player.queue.getCurrent();
|
||||||
|
const isPlaying = !player.paused && current;
|
||||||
|
const statusEmoji = isPlaying ? STATES.playing : player.paused ? STATES.paused : STATES.stopped;
|
||||||
|
|
||||||
|
let progressBar = "";
|
||||||
|
let timeDisplay = "`0:00 / 0:00`";
|
||||||
|
|
||||||
|
if (current?.duration && player.startedPlaying) {
|
||||||
|
const elapsed = Date.now() - player.startedPlaying;
|
||||||
|
const totalMs = typeof current.duration === "object"
|
||||||
|
? (current.duration.seconds ?? 0) * 1000
|
||||||
|
: current.duration;
|
||||||
|
|
||||||
|
const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled);
|
||||||
|
progressBar = PROGRESS.start + bar + PROGRESS.end;
|
||||||
|
|
||||||
|
const elapsedStr = Utils.prettifyMS(elapsed);
|
||||||
|
const totalStr = Utils.prettifyMS(totalMs);
|
||||||
|
timeDisplay = `\`${elapsedStr} / ${totalStr}\``;
|
||||||
|
} else {
|
||||||
|
progressBar = PROGRESS.start + PROGRESS.empty.repeat(20) + PROGRESS.end;
|
||||||
|
}
|
||||||
|
|
||||||
|
const volPercent = Math.round((player.preferredVolume ?? 1) * 100);
|
||||||
|
const volBars = Math.ceil(volPercent / 10);
|
||||||
|
const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars);
|
||||||
|
|
||||||
|
const queueSize = player.queue.size();
|
||||||
|
const loopStatus = player.queue.songLoop ? bot.t(msg, "responses.player.loopSong") : player.queue.loop ? bot.t(msg, "responses.player.loopQueue") : bot.t(msg, "responses.player.loopOff");
|
||||||
|
|
||||||
|
let filterStatus = bot.t(msg, "responses.player.filterOff");
|
||||||
|
if (player.activeFilter) {
|
||||||
|
if (player.activeFilter.label.includes("+")) {
|
||||||
|
filterStatus = `🔥 **${player.activeFilter.label}**`;
|
||||||
|
} else {
|
||||||
|
filterStatus = `${player.activeFilter.emoji ?? "🎛️"} **${player.activeFilter.label}**`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const nowPlaying = current
|
||||||
|
? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})`
|
||||||
|
: bot.t(msg, "responses.filter.nothingPlayingInline");
|
||||||
|
|
||||||
|
const description = [
|
||||||
|
`${statusEmoji} ${bot.t(msg, "responses.player.nowPlayingLabel")}`,
|
||||||
|
`${nowPlaying}`,
|
||||||
|
``,
|
||||||
|
`${progressBar}`,
|
||||||
|
`${timeDisplay}`,
|
||||||
|
``,
|
||||||
|
bot.t(msg, "responses.player.volumeLabel", { volume: volPercent }) + " " + volumeBar,
|
||||||
|
`${bot.t(msg, "responses.player.queueLabel", { count: queueSize })} | Loop: ${loopStatus} | Filter: ${filterStatus}`,
|
||||||
|
``,
|
||||||
|
state.message ? `💬 *${state.message}*` : `💡 *${bot.t(msg, "responses.player.reactHint")}*`,
|
||||||
|
``,
|
||||||
|
bot.t(msg, "responses.player.sessionExpires", { minutes: Math.ceil(timeout / 60000) })
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
const avatarUrl = typeof msg.author?.avatarURL === "function"
|
||||||
|
? msg.author.avatarURL()
|
||||||
|
: msg.author?.avatarURL ?? null;
|
||||||
|
|
||||||
|
const builder = new EmbedBuilder()
|
||||||
|
.setColor(getGlobalColor())
|
||||||
|
.setTitle(bot.t(msg, "responses.player.title"))
|
||||||
|
.setDescription(description)
|
||||||
|
.setFooter({
|
||||||
|
text: bot.t(msg, "responses.player.requestedBy", { username: msg.author?.username || "Unknown" }),
|
||||||
|
iconURL: avatarUrl
|
||||||
|
});
|
||||||
|
if (typeof builder.setTimestamp === "function") builder.setTimestamp();
|
||||||
|
if (current?.thumbnail) builder.setThumbnail(current.thumbnail);
|
||||||
|
return builder;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/player
|
||||||
|
* @description Barrel for the player control-panel implementation modules.
|
||||||
|
* commands/player.mjs (the command entry file) imports through this barrel;
|
||||||
|
* it stays the single import surface for the group.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export { STATES, CONTROLS, PROGRESS } from "./consts.mjs";
|
||||||
|
export { buildPlayerEmbed } from "./embed.mjs";
|
||||||
|
export { openLyricsViewer, clearLyricsReactions } from "./lyrics.mjs";
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/player/lyrics
|
||||||
|
* @description Embedded lyrics viewer for the player panel (verbatim body of
|
||||||
|
* the original "lyrics" reaction case): paginated lyric pages with navigation
|
||||||
|
* reactions, control-expiry timer and close handling. Session-scoped mutable
|
||||||
|
* state lives in the shared `session` object ({activeLyricsMsg, unobserve,
|
||||||
|
* emojiTimeout}) so the panel's closeSession can clean it up.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Utils } from "../../src/utils/Utils.mjs";
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor } from "../../src/ui/index.mjs";
|
||||||
|
import { EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs";
|
||||||
|
import { logger } from "../../src/core/Logger.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove navigation reactions from a lyrics message.
|
||||||
|
* @param {object} lyricsMsg - The wrapped lyrics message with a .message property.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function clearLyricsReactions(lyricsMsg) {
|
||||||
|
if (!lyricsMsg?.message) return;
|
||||||
|
try {
|
||||||
|
await lyricsMsg.message.removeAllReactions();
|
||||||
|
} catch (e) {
|
||||||
|
for (const emoji of ["⬅️", "➡️", "❌"]) {
|
||||||
|
try {
|
||||||
|
await lyricsMsg.message.removeReaction(emoji);
|
||||||
|
} catch(e) { logger.warn("[Player] Error:", e?.message); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open (or reopen) the lyrics viewer for the player's current track.
|
||||||
|
*
|
||||||
|
* Mirrors the original `case "lyrics":` flow exactly: announces fetching,
|
||||||
|
* tears down a previous viewer, fetches lyrics from the player, renders
|
||||||
|
* paginated content, wires navigation/close reactions with the shared
|
||||||
|
* emoji-expiry timer, and returns the final reply string. Every exit path
|
||||||
|
* corresponds to `shouldUpdate = true` in the original switch, so the caller
|
||||||
|
* always refreshes the panel afterwards.
|
||||||
|
*
|
||||||
|
* @param {object} bot - The bot instance (locale translation via bot.t).
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {object} player - The guild player (player.lyrics(), queue).
|
||||||
|
* @param {function} refresh - Panel refresh callback ({ message }) => void.
|
||||||
|
* @param {object} session - Shared viewer state: { activeLyricsMsg, unobserve, emojiTimeout }.
|
||||||
|
* @returns {Promise<string>} The reply message text to surface on the panel.
|
||||||
|
*/
|
||||||
|
export async function openLyricsViewer(bot, msg, player, refresh, session) {
|
||||||
|
let reply = bot.t(msg, "responses.player.fetchingLyrics");
|
||||||
|
refresh({ message: reply });
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (session.unobserve) {
|
||||||
|
session.unobserve();
|
||||||
|
clearTimeout(session.emojiTimeout);
|
||||||
|
if (session.activeLyricsMsg) await clearLyricsReactions(session.activeLyricsMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
const lyricsResult = await player.lyrics();
|
||||||
|
if (!lyricsResult) {
|
||||||
|
return bot.t(msg, "responses.player.noLyricsFound");
|
||||||
|
}
|
||||||
|
|
||||||
|
const syncBadge = lyricsResult.synced ? " ⏱️ Synced" : "";
|
||||||
|
const lines = lyricsResult.text.split('\n');
|
||||||
|
const totalLines = lines.length;
|
||||||
|
const LINES_PER_PAGE = 25;
|
||||||
|
const totalPages = Math.ceil(totalLines / LINES_PER_PAGE);
|
||||||
|
|
||||||
|
const pages = [];
|
||||||
|
for (let i = 0; i < totalLines; i += LINES_PER_PAGE) {
|
||||||
|
pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
let currentPage = 0;
|
||||||
|
|
||||||
|
const buildLyricsContent = (pageIdx, expired = false, closed = false) => {
|
||||||
|
const title = Utils.truncate(
|
||||||
|
player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '',
|
||||||
|
50
|
||||||
|
);
|
||||||
|
const footerText = closed
|
||||||
|
? `👋 Lyrics closed • NodeLink • ${totalLines} lines`
|
||||||
|
: expired
|
||||||
|
? `⌛ Controls expired • NodeLink • ${totalLines} lines`
|
||||||
|
: `NodeLink • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`;
|
||||||
|
const desc = [
|
||||||
|
`**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`,
|
||||||
|
``,
|
||||||
|
'```',
|
||||||
|
pages[pageIdx],
|
||||||
|
totalPages > 1 && !expired && !closed ? `\n\n💡 ⬅️ ➡️ Navigate • ❌ Close` : '',
|
||||||
|
'```'
|
||||||
|
].join('\n');
|
||||||
|
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText })] };
|
||||||
|
};
|
||||||
|
|
||||||
|
session.activeLyricsMsg = await msg.reply(buildLyricsContent(0));
|
||||||
|
|
||||||
|
if (session.activeLyricsMsg?.message && totalPages > 1) {
|
||||||
|
const navEmojis = ["⬅️", "➡️", "❌"];
|
||||||
|
for (const emoji of navEmojis) {
|
||||||
|
await session.activeLyricsMsg.message.react(emoji).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetLyricsTimer = () => {
|
||||||
|
clearTimeout(session.emojiTimeout);
|
||||||
|
session.emojiTimeout = setTimeout(async () => {
|
||||||
|
await clearLyricsReactions(session.activeLyricsMsg);
|
||||||
|
await session.activeLyricsMsg.edit(buildLyricsContent(currentPage, true, false)).catch(() => {});
|
||||||
|
}, EMOJI_REMOVE_TIMEOUT);
|
||||||
|
};
|
||||||
|
|
||||||
|
session.unobserve = session.activeLyricsMsg.onReaction(navEmojis, async (e) => {
|
||||||
|
if (e.emoji_id === "❌") {
|
||||||
|
session.unobserve();
|
||||||
|
clearTimeout(session.emojiTimeout);
|
||||||
|
await clearLyricsReactions(session.activeLyricsMsg);
|
||||||
|
await session.activeLyricsMsg.edit(buildLyricsContent(currentPage, false, true)).catch(() => {});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
resetLyricsTimer();
|
||||||
|
|
||||||
|
if (e.emoji_id === "⬅️") {
|
||||||
|
currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1;
|
||||||
|
} else if (e.emoji_id === "➡️") {
|
||||||
|
currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
await session.activeLyricsMsg.edit(buildLyricsContent(currentPage));
|
||||||
|
});
|
||||||
|
|
||||||
|
resetLyricsTimer();
|
||||||
|
} else if (session.activeLyricsMsg?.message) {
|
||||||
|
await session.activeLyricsMsg.message.react("❌").catch(() => {});
|
||||||
|
|
||||||
|
const resetLyricsTimer = () => {
|
||||||
|
clearTimeout(session.emojiTimeout);
|
||||||
|
session.emojiTimeout = setTimeout(async () => {
|
||||||
|
await clearLyricsReactions(session.activeLyricsMsg);
|
||||||
|
await session.activeLyricsMsg.edit(buildLyricsContent(0, true, false)).catch(() => {});
|
||||||
|
}, EMOJI_REMOVE_TIMEOUT);
|
||||||
|
};
|
||||||
|
|
||||||
|
session.unobserve = session.activeLyricsMsg.onReaction(["❌"], async (e) => {
|
||||||
|
if (e.emoji_id === "❌") {
|
||||||
|
session.unobserve();
|
||||||
|
clearTimeout(session.emojiTimeout);
|
||||||
|
await clearLyricsReactions(session.activeLyricsMsg);
|
||||||
|
await session.activeLyricsMsg.edit(buildLyricsContent(0, false, true)).catch(() => {});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
resetLyricsTimer();
|
||||||
|
}
|
||||||
|
|
||||||
|
return bot.t(msg, "responses.player.lyricsDisplayed", { lines: totalLines, pages: totalPages });
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
return bot.t(msg, "responses.player.lyricsError", { error: Utils.truncate(err.message, 50) });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,10 +4,10 @@
|
|||||||
* Supports inline provider prefixes and flag-based provider selection.
|
* Supports inline provider prefixes and flag-based provider selection.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs";
|
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+4
-4
@@ -3,11 +3,11 @@
|
|||||||
* @description Play internet radio stations with interactive station selection via reactions.
|
* @description Play internet radio stations with interactive station selection via reactions.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/constants/UI.mjs";
|
import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/utils/UI.mjs";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+2
-2
@@ -3,9 +3,9 @@
|
|||||||
* @description Owner-only command to hot-reload commands, source modules, or audio modules at runtime.
|
* @description Owner-only command to hot-reload commands, source modules, or audio modules at runtime.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { pathToFileURL } from "node:url";
|
import { pathToFileURL } from "node:url";
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
* @description Remove a specific track from the queue by its position.
|
* @description Remove a specific track from the queue by its position.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/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()
|
||||||
|
|||||||
+2
-2
@@ -3,9 +3,9 @@
|
|||||||
* @description Resume paused playback in the current voice channel.
|
* @description Resume paused playback in the current voice channel.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
|
|||||||
+5
-5
@@ -3,12 +3,12 @@
|
|||||||
* @description Search for tracks across providers and pick one to play via reaction selection.
|
* @description Search for tracks across providers and pick one to play via reaction selection.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { Message, getGlobalColor } from "../src/MessageHandler.mjs";
|
import { Message, getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/constants/providers.mjs";
|
import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/music/providers.mjs";
|
||||||
import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/constants/UI.mjs";
|
import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/utils/UI.mjs";
|
||||||
import { logger } from "../src/constants/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. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
|
|||||||
+4
-4
@@ -3,11 +3,11 @@
|
|||||||
* @description Seek to a specific position in the currently playing track.
|
* @description Seek to a specific position in the currently playing track.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { ERROR_COLOR } from "../src/constants/UI.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()
|
||||||
|
|||||||
@@ -3,11 +3,11 @@
|
|||||||
* @description Owner-only command to list all servers the bot is in with pagination.
|
* @description Owner-only command to list all servers the bot is in with pagination.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
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()
|
||||||
|
|||||||
+15
-448
@@ -1,455 +1,22 @@
|
|||||||
/**
|
/**
|
||||||
* @module commands/settings
|
* @module commands/settings
|
||||||
* @description Server settings management with subcommands (get/set/reset/help) and shortcut aliases (prefix, 247).
|
* @description Server settings management with subcommands (get/set/reset/help) and
|
||||||
|
* shortcut aliases (prefix, 247). The helpers live in commands/settings/ (utils,
|
||||||
|
* channels247, setters); the command factory and run() dispatch stay here.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
|
||||||
import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs";
|
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
|
||||||
import runnables from "../settings/runnables.mjs";
|
|
||||||
|
|
||||||
/**
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
* Command alias to setting key mapping.
|
import { getMessageGuildId } from "../src/ui/index.mjs";
|
||||||
* @type {Object.<string, string>}
|
// kept verbatim from the original file (unused there as well):
|
||||||
*/
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
const SHORTCUTS = {
|
import {
|
||||||
prefix: "prefix",
|
SHORTCUTS, BOOL_SETTINGS, VALID_LOCALES, setValidLocales,
|
||||||
pfx: "prefix",
|
VOLUME_MIN, VOLUME_MAX,
|
||||||
"247": "stay_247",
|
displayValue, getGuildName, embed, prettifySettingLabel,
|
||||||
};
|
} from "./settings/utils.mjs";
|
||||||
|
import { get247Channels, build247Panel } from "./settings/channels247.mjs";
|
||||||
/** @private @type {Set<string>} Strings that evaluate to boolean true. */
|
import { applySet, handleShortcut } from "./settings/setters.mjs";
|
||||||
const BOOL_TRUE = new Set(["true", "1", "yes", "on", "enable", "enabled"]);
|
|
||||||
/** @private @type {Set<string>} Strings that evaluate to boolean false. */
|
|
||||||
const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]);
|
|
||||||
/** @private @type {Set<string>} Setting keys that use boolean display formatting. */
|
|
||||||
const BOOL_SETTINGS = new Set(["songAnnouncements"]);
|
|
||||||
|
|
||||||
/** @private @type {Set<string>} Available locale codes, populated at load time. */
|
|
||||||
let VALID_LOCALES = new Set(["en"]);
|
|
||||||
|
|
||||||
/** @private @type {number} Minimum allowed volume value. */
|
|
||||||
const VOLUME_MIN = 1;
|
|
||||||
/** @private @type {number} Maximum allowed volume value. */
|
|
||||||
const VOLUME_MAX = 200;
|
|
||||||
/** @private @type {number} Maximum prefix length in characters. */
|
|
||||||
const PREFIX_MAX = 5;
|
|
||||||
/** @private @type {number} Maximum number of 24/7 channels per guild. */
|
|
||||||
const MAX_247_CHANNELS = 1;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check whether a string looks like a valid Fluxer ID (Snowflake-like).
|
|
||||||
* @param {string} id - The ID to validate.
|
|
||||||
* @returns {boolean} True if the ID is 15-22 characters after cleaning.
|
|
||||||
*/
|
|
||||||
function isValidFluxerId(id) {
|
|
||||||
const cleaned = cleanId(id);
|
|
||||||
return cleaned.length >= 15 && cleaned.length <= 22;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse a string into a boolean, or return null if unrecognised.
|
|
||||||
* @param {string} str - The string to parse.
|
|
||||||
* @returns {boolean|null} True, false, or null if not a boolean string.
|
|
||||||
*/
|
|
||||||
function parseBool(str) {
|
|
||||||
const s = String(str).toLowerCase().trim();
|
|
||||||
if (BOOL_TRUE.has(s)) return true;
|
|
||||||
if (BOOL_FALSE.has(s)) return false;
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Format a setting value for display in embed messages.
|
|
||||||
* @param {string} key - The setting key.
|
|
||||||
* @param {*} value - The setting value.
|
|
||||||
* @returns {string} Formatted display string.
|
|
||||||
*/
|
|
||||||
function displayValue(key, value) {
|
|
||||||
if (BOOL_SETTINGS.has(key)) return value ? "\u2705 enabled" : "\u274c disabled";
|
|
||||||
if (value === null || value === undefined || value === "none") return "none";
|
|
||||||
return "`" + value + "`";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @private
|
|
||||||
* Get the display name of the guild from a message object.
|
|
||||||
* @param {object} message - The command message wrapper.
|
|
||||||
* @returns {string} The guild name, or a fallback string.
|
|
||||||
*/
|
|
||||||
function getGuildName(message) {
|
|
||||||
return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @private
|
|
||||||
* Create a simple embed payload with global color, description, and optional title/footer.
|
|
||||||
* @param {string} desc - The embed description text.
|
|
||||||
* @param {object} [opts={}] - Optional overrides for title, iconURL, and footer.
|
|
||||||
* @returns {object} Embed payload for message.reply().
|
|
||||||
*/
|
|
||||||
function embed(desc, opts = {}) {
|
|
||||||
const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
|
|
||||||
if (opts.title) b.setTitle(opts.title);
|
|
||||||
if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL });
|
|
||||||
if (opts.footer) b.setFooter({ text: opts.footer });
|
|
||||||
return { embeds: [b] };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse the stay_247 setting into a Set of validated channel IDs.
|
|
||||||
* @param {ServerSettings} set - The guild settings instance.
|
|
||||||
* @returns {Set<string>} Set of cleaned, valid channel IDs.
|
|
||||||
*/
|
|
||||||
function get247Channels(set) {
|
|
||||||
const raw = set.get("stay_247");
|
|
||||||
if (!raw || raw === "none") return new Set();
|
|
||||||
if (typeof raw === "string") {
|
|
||||||
const id = cleanId(raw);
|
|
||||||
return (id && isValidFluxerId(id)) ? new Set([id]) : new Set();
|
|
||||||
}
|
|
||||||
if (Array.isArray(raw)) {
|
|
||||||
return new Set(raw.map(id => cleanId(id)).filter(id => id && isValidFluxerId(id)));
|
|
||||||
}
|
|
||||||
return new Set();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Save a Set of channel IDs back to the stay_247 setting.
|
|
||||||
* Writes 'none' if the set is empty.
|
|
||||||
* @param {ServerSettings} set - The guild settings instance.
|
|
||||||
* @param {Set<string>} channels - The channel IDs to save.
|
|
||||||
*/
|
|
||||||
function save247Channels(set, channels) {
|
|
||||||
const arr = [...channels].filter(id => id && isValidFluxerId(id));
|
|
||||||
set.set("stay_247", arr.length > 0 ? arr : "none");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @private
|
|
||||||
* Resolve a channel ID to a human-readable channel name from the client cache.
|
|
||||||
* @param {import('@fluxerjs/core').Client} client - The Discord/Fluxer client.
|
|
||||||
* @param {string} channelId - The channel ID to look up.
|
|
||||||
* @returns {string|null} The channel name, or null if not found.
|
|
||||||
*/
|
|
||||||
function resolveChannelName(client, channelId) {
|
|
||||||
try {
|
|
||||||
const ch = client?.channels?.get?.(channelId);
|
|
||||||
if (ch?.name) return ch.name;
|
|
||||||
} catch (_) {}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @private
|
|
||||||
* Create a translation function bound to the given context and guild.
|
|
||||||
* @param {object} ctx - The bot (Remix) context.
|
|
||||||
* @param {string} guildId - The guild ID for localization.
|
|
||||||
* @returns {Function} A translation function with signature (key, data?) => string.
|
|
||||||
*/
|
|
||||||
function tWrap(ctx, guildId) {
|
|
||||||
const tFn = ctx.locale?.translate?.bind(ctx.locale);
|
|
||||||
return (key, data = {}) => tFn ? tFn(guildId, key, data) : key;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @private
|
|
||||||
* Get a human-readable label for a setting key, using locale translations when available.
|
|
||||||
* @param {string} key - The setting key.
|
|
||||||
* @param {Function|null} t - Translation function (guildId, key, data) => string.
|
|
||||||
* @param {string} guildId - The guild ID for localization.
|
|
||||||
* @returns {string} The pretty-printed setting label.
|
|
||||||
*/
|
|
||||||
function prettifySettingLabel(key, t, guildId) {
|
|
||||||
const localeMap = {
|
|
||||||
songAnnouncements: "responses.settings.labelSongAnnouncements",
|
|
||||||
prefix: "responses.settings.labelPrefix",
|
|
||||||
pfx: "responses.settings.labelPfp",
|
|
||||||
locale: "responses.settings.labelLocale",
|
|
||||||
stay_247: "responses.settings.label247",
|
|
||||||
volume: "responses.settings.labelVolume",
|
|
||||||
};
|
|
||||||
if (localeMap[key] && t && guildId) return t(guildId, localeMap[key]);
|
|
||||||
const fallback = {
|
|
||||||
songAnnouncements: "Song announcements",
|
|
||||||
prefix: "Prefix",
|
|
||||||
pfp: "Bot avatar style",
|
|
||||||
locale: "Locale",
|
|
||||||
stay_247: "24/7 mode",
|
|
||||||
volume: "Default volume",
|
|
||||||
};
|
|
||||||
return fallback[key] ?? key.replace(/_/g, " ");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build an embed payload showing the current 24/7 status for the guild.
|
|
||||||
* @param {ServerSettings} set - The guild settings instance.
|
|
||||||
* @param {object} ctx - The bot (Remix) context.
|
|
||||||
* @param {string} guildId - The guild ID.
|
|
||||||
* @param {string|null} channelId - The channel ID (for active indicator), or null.
|
|
||||||
* @returns {object} Embed payload object for message.reply().
|
|
||||||
*/
|
|
||||||
function build247Panel(set, ctx, guildId, channelId) {
|
|
||||||
const channels = [...get247Channels(set)];
|
|
||||||
const prefix = ctx.handler.getPrefix(guildId);
|
|
||||||
|
|
||||||
if (channels.length > 0) {
|
|
||||||
const lines = channels.map(id => {
|
|
||||||
const name = resolveChannelName(ctx.client, id);
|
|
||||||
const isActive = id === channelId;
|
|
||||||
return (isActive ? "\u25b6 " : "\u2022 ") + (name ? "**" + name + "** " : "") + "<#" + id + ">";
|
|
||||||
});
|
|
||||||
return embed(
|
|
||||||
channels.length === 1 && channelId
|
|
||||||
? "\u2705 24/7 is now **enabled** in <#" + channelId + ">\n\n" +
|
|
||||||
"The bot will stay connected and auto-rejoin if disconnected."
|
|
||||||
: "\u2705 24/7 active in " + channels.length + " channel(s):\n\n" + lines.join("\n"),
|
|
||||||
{ title: "\u2705 24/7 Mode" }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return embed(
|
|
||||||
"\u274c 24/7 is **disabled**\n\n" +
|
|
||||||
"The bot will leave voice channels when idle.\n\n" +
|
|
||||||
"Join a voice channel and use `" + prefix + "247` to enable.",
|
|
||||||
{ title: "\u274c 24/7 Mode" }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Disable 24/7 mode for a specific channel.
|
|
||||||
* Removes the channel from stay_247, marks intentional leave, and destroys the player.
|
|
||||||
* @param {object} ctx - The bot (Remix) context.
|
|
||||||
* @param {ServerSettings} set - The guild settings instance.
|
|
||||||
* @param {string} guildId - The guild ID.
|
|
||||||
* @param {string} channelId - The channel ID to disable.
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async function disable247(ctx, set, guildId, channelId) {
|
|
||||||
const id = cleanId(channelId);
|
|
||||||
const channels = get247Channels(set);
|
|
||||||
channels.delete(id);
|
|
||||||
save247Channels(set, channels);
|
|
||||||
ctx.markIntentionalLeave?.(id);
|
|
||||||
const player = ctx.players.playerMap.get(id)
|
|
||||||
?? [...ctx.players.playerMap.values()].find(p =>
|
|
||||||
cleanId(p?._channelId ?? "") === id &&
|
|
||||||
cleanId(p?._guildId ?? "") === cleanId(guildId)
|
|
||||||
);
|
|
||||||
if (player) {
|
|
||||||
const activeId = cleanId(player._channelId ?? id);
|
|
||||||
ctx.players.playerMap.delete(activeId);
|
|
||||||
if (activeId !== id) ctx.players.playerMap.delete(id);
|
|
||||||
await player.leave().catch(() => {});
|
|
||||||
player.destroy();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Enable 24/7 mode for a specific channel.
|
|
||||||
* Enforces MAX_247_CHANNELS (1) by disabling any existing 24/7 channel first,
|
|
||||||
* then saves the new channel and spawns a player if none exists.
|
|
||||||
* @param {object} ctx - The bot (Remix) context.
|
|
||||||
* @param {ServerSettings} set - The guild settings instance.
|
|
||||||
* @param {string} guildId - The guild ID.
|
|
||||||
* @param {string} channelId - The channel ID to enable.
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async function enable247(ctx, set, guildId, channelId) {
|
|
||||||
const id = cleanId(channelId);
|
|
||||||
const channels = get247Channels(set);
|
|
||||||
if (channels.has(id)) return;
|
|
||||||
|
|
||||||
// Platform only supports 1 voice channel per bot per guild.
|
|
||||||
// If another channel already has 24/7, disable it first.
|
|
||||||
if (channels.size >= MAX_247_CHANNELS) {
|
|
||||||
for (const oldId of channels) {
|
|
||||||
if (oldId !== id) {
|
|
||||||
ctx.markIntentionalLeave?.(oldId);
|
|
||||||
const oldPlayer = ctx.players.playerMap.get(oldId)
|
|
||||||
?? [...ctx.players.playerMap.values()].find(p =>
|
|
||||||
cleanId(p?._channelId ?? "") === oldId &&
|
|
||||||
cleanId(p?._guildId ?? "") === cleanId(guildId)
|
|
||||||
);
|
|
||||||
if (oldPlayer) {
|
|
||||||
const activeId = cleanId(oldPlayer._channelId ?? oldId);
|
|
||||||
ctx.players.playerMap.delete(activeId);
|
|
||||||
if (activeId !== oldId) ctx.players.playerMap.delete(oldId);
|
|
||||||
await oldPlayer.leave().catch(() => {});
|
|
||||||
oldPlayer.destroy();
|
|
||||||
}
|
|
||||||
channels.delete(oldId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
channels.add(id);
|
|
||||||
save247Channels(set, channels);
|
|
||||||
const playerExists = ctx.players.playerMap.has(id) ||
|
|
||||||
[...ctx.players.playerMap.values()].some(p =>
|
|
||||||
cleanId(p?._channelId ?? "") === id && cleanId(p?._guildId ?? "") === cleanId(guildId)
|
|
||||||
);
|
|
||||||
if (!playerExists) {
|
|
||||||
try { await ctx._spawnPlayer(guildId, id); } catch (_) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handle the !247 toggle command. If the user is in a 24/7 channel, disable it;
|
|
||||||
* otherwise, enable it for the user's current voice channel.
|
|
||||||
* @param {object} ctx - The bot (Remix) context.
|
|
||||||
* @param {object} message - The command message.
|
|
||||||
* @param {ServerSettings} set - The guild settings instance.
|
|
||||||
* @param {string} guildId - The guild ID.
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async function handle247Toggle(ctx, message, set, guildId) {
|
|
||||||
const loc = tWrap(ctx, guildId);
|
|
||||||
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
|
|
||||||
|
|
||||||
const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message);
|
|
||||||
if (!userChannelId) {
|
|
||||||
return message.reply(build247Panel(set, ctx, guildId, null));
|
|
||||||
}
|
|
||||||
|
|
||||||
const id = cleanId(userChannelId);
|
|
||||||
const channels = get247Channels(set);
|
|
||||||
|
|
||||||
if (channels.has(id)) {
|
|
||||||
await disable247(ctx, set, guildId, userChannelId);
|
|
||||||
return message.reply(build247Panel(set, ctx, guildId, id));
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await enable247(ctx, set, guildId, userChannelId);
|
|
||||||
if (result?.max) {
|
|
||||||
return message.reply(embed(
|
|
||||||
loc("responses.settings.max247Channels", { max: MAX_247_CHANNELS, prefix: ctx.handler.getPrefix(guildId) })
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
return message.reply(build247Panel(set, ctx, guildId, id));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Apply a new value to a setting, with type-specific validation.
|
|
||||||
* @param {object} ctx - The bot (Remix) context.
|
|
||||||
* @param {object} message - The command message.
|
|
||||||
* @param {ServerSettings} set - The guild settings instance.
|
|
||||||
* @param {string} key - The setting key.
|
|
||||||
* @param {string} rawValue - The raw string value from the command.
|
|
||||||
* @returns {Promise<string|null>} Error message string, or null on success.
|
|
||||||
*/
|
|
||||||
async function applySet(ctx, message, set, key, rawValue) {
|
|
||||||
if (BOOL_SETTINGS.has(key)) {
|
|
||||||
const bool = parseBool(rawValue);
|
|
||||||
if (bool === null) {
|
|
||||||
return ctx.t(message, "responses.settings.mustBeBool", { setting: key });
|
|
||||||
}
|
|
||||||
set.set(key, bool);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (key === "volume") {
|
|
||||||
const num = parseInt(rawValue, 10);
|
|
||||||
if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) {
|
|
||||||
return ctx.t(message, "responses.settings.volumeRange");
|
|
||||||
}
|
|
||||||
set.set(key, num);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (key === "locale") {
|
|
||||||
if (!VALID_LOCALES.has(rawValue)) {
|
|
||||||
return ctx.t(message, "responses.settings.invalidLocale", {
|
|
||||||
locale: rawValue,
|
|
||||||
locales: [...VALID_LOCALES].map(l => "`" + l + "`").join(", ")
|
|
||||||
});
|
|
||||||
}
|
|
||||||
set.set(key, rawValue);
|
|
||||||
const gid = getMessageGuildId(message);
|
|
||||||
if (gid) ctx.locale.invalidateCache(gid);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (key === "prefix") {
|
|
||||||
if (!rawValue || rawValue.length > PREFIX_MAX) {
|
|
||||||
return ctx.t(message, "responses.settings.prefixLength");
|
|
||||||
}
|
|
||||||
if (/\s/.test(rawValue)) {
|
|
||||||
return ctx.t(message, "responses.settings.prefixSpaces");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (runnables[key]) {
|
|
||||||
const err = runnables[key].call(ctx, rawValue, { msg: message });
|
|
||||||
if (err) return "\u274c " + err;
|
|
||||||
}
|
|
||||||
|
|
||||||
set.set(key, rawValue);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @private
|
|
||||||
* @async
|
|
||||||
* Handle a settings shortcut command (e.g. `prefix`, `247`).
|
|
||||||
* Dispatches to 24/7 toggle, value display, or value set depending on arguments.
|
|
||||||
* @param {object} ctx - The bot (Remix) context.
|
|
||||||
* @param {object} message - The command message.
|
|
||||||
* @param {string} settingKey - The resolved setting key.
|
|
||||||
* @param {string[]} valueTokens - Remaining argument tokens after the shortcut alias.
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
*/
|
|
||||||
async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
|
||||||
const set = ctx.getSettings(message);
|
|
||||||
const guildId = getMessageGuildId(message);
|
|
||||||
const t247 = ctx.locale?.translate?.bind(ctx.locale);
|
|
||||||
|
|
||||||
if (valueTokens.length === 0) {
|
|
||||||
if (settingKey === "stay_247") {
|
|
||||||
return handle247Toggle(ctx, message, set, guildId);
|
|
||||||
}
|
|
||||||
const val = set.get(settingKey);
|
|
||||||
const label = prettifySettingLabel(settingKey, t247, guildId);
|
|
||||||
return message.reply(embed("**" + label + "**\nValue: " + displayValue(settingKey, val)));
|
|
||||||
}
|
|
||||||
|
|
||||||
const rawValue = valueTokens.join(" ");
|
|
||||||
|
|
||||||
if (settingKey === "stay_247") {
|
|
||||||
const mode = rawValue.toLowerCase().trim();
|
|
||||||
if (mode === "off" || mode === "false" || mode === "disable" || mode === "0") {
|
|
||||||
const loc = tWrap(ctx, guildId);
|
|
||||||
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
|
|
||||||
const { channelId } = await ctx.players.checkVoiceChannels(message);
|
|
||||||
if (channelId) {
|
|
||||||
await disable247(ctx, set, guildId, channelId);
|
|
||||||
return message.reply(build247Panel(set, ctx, guildId, cleanId(channelId)));
|
|
||||||
}
|
|
||||||
for (const [chId, player] of [...ctx.players.playerMap.entries()]) {
|
|
||||||
if (cleanId(player?._guildId ?? "") === cleanId(guildId)) {
|
|
||||||
const activeId = cleanId(player._channelId ?? chId);
|
|
||||||
ctx.markIntentionalLeave?.(activeId);
|
|
||||||
ctx.players.playerMap.delete(activeId);
|
|
||||||
if (activeId !== chId) ctx.players.playerMap.delete(chId);
|
|
||||||
await player.leave().catch(() => {});
|
|
||||||
player.destroy();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
save247Channels(set, new Set());
|
|
||||||
return message.reply(build247Panel(set, ctx, guildId, null));
|
|
||||||
}
|
|
||||||
return handle247Toggle(ctx, message, set, guildId);
|
|
||||||
}
|
|
||||||
|
|
||||||
const err = await applySet(ctx, message, set, settingKey, rawValue);
|
|
||||||
if (err) return message.reply(embed(err));
|
|
||||||
|
|
||||||
const val = set.get(settingKey);
|
|
||||||
const label = prettifySettingLabel(settingKey, t247, guildId);
|
|
||||||
return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label, value: displayValue(settingKey, val) })));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {Function}
|
* @type {Function}
|
||||||
@@ -459,7 +26,7 @@ async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
|||||||
*/
|
*/
|
||||||
export const command = function() {
|
export const command = function() {
|
||||||
if (this.locale) {
|
if (this.locale) {
|
||||||
VALID_LOCALES = this.locale.availableLocales();
|
setValidLocales(this.locale.availableLocales());
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.loader) {
|
if (this.loader) {
|
||||||
|
|||||||
@@ -0,0 +1,198 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/settings/channels247
|
||||||
|
* @description 24/7 channel storage, panel
|
||||||
|
* rendering and enable/disable/toggle handling for the settings command.
|
||||||
|
* Bodies are verbatim from the original single-file command.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { cleanId } from "../../src/ui/index.mjs";
|
||||||
|
import { isValidFluxerId, MAX_247_CHANNELS, embed, tWrap } from "./utils.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse the stay_247 setting into a Set of validated channel IDs.
|
||||||
|
* @param {ServerSettings} set - The guild settings instance.
|
||||||
|
* @returns {Set<string>} Set of cleaned, valid channel IDs.
|
||||||
|
*/
|
||||||
|
export function get247Channels(set) {
|
||||||
|
const raw = set.get("stay_247");
|
||||||
|
if (!raw || raw === "none") return new Set();
|
||||||
|
if (typeof raw === "string") {
|
||||||
|
const id = cleanId(raw);
|
||||||
|
return (id && isValidFluxerId(id)) ? new Set([id]) : new Set();
|
||||||
|
}
|
||||||
|
if (Array.isArray(raw)) {
|
||||||
|
return new Set(raw.map(id => cleanId(id)).filter(id => id && isValidFluxerId(id)));
|
||||||
|
}
|
||||||
|
return new Set();
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Save a Set of channel IDs back to the stay_247 setting.
|
||||||
|
* Writes 'none' if the set is empty.
|
||||||
|
* @param {ServerSettings} set - The guild settings instance.
|
||||||
|
* @param {Set<string>} channels - The channel IDs to save.
|
||||||
|
*/
|
||||||
|
export function save247Channels(set, channels) {
|
||||||
|
const arr = [...channels].filter(id => id && isValidFluxerId(id));
|
||||||
|
set.set("stay_247", arr.length > 0 ? arr : "none");
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Resolve a channel ID to a human-readable channel name from the client cache.
|
||||||
|
* @param {import('@fluxerjs/core').Client} client - The Fluxer client.
|
||||||
|
* @param {string} channelId - The channel ID to look up.
|
||||||
|
* @returns {string|null} The channel name, or null if not found.
|
||||||
|
*/
|
||||||
|
function resolveChannelName(client, channelId) {
|
||||||
|
try {
|
||||||
|
const ch = client?.channels?.get?.(channelId);
|
||||||
|
if (ch?.name) return ch.name;
|
||||||
|
} catch (_) {}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build an embed payload showing the current 24/7 status for the guild.
|
||||||
|
* @param {ServerSettings} set - The guild settings instance.
|
||||||
|
* @param {object} ctx - The bot (Remix) context.
|
||||||
|
* @param {string} guildId - The guild ID.
|
||||||
|
* @param {string|null} channelId - The channel ID (for active indicator), or null.
|
||||||
|
* @returns {object} Embed payload object for message.reply().
|
||||||
|
*/
|
||||||
|
export function build247Panel(set, ctx, guildId, channelId) {
|
||||||
|
const channels = [...get247Channels(set)];
|
||||||
|
const prefix = ctx.handler.getPrefix(guildId);
|
||||||
|
|
||||||
|
if (channels.length > 0) {
|
||||||
|
const lines = channels.map(id => {
|
||||||
|
const name = resolveChannelName(ctx.client, id);
|
||||||
|
const isActive = id === channelId;
|
||||||
|
return (isActive ? "\u25b6 " : "\u2022 ") + (name ? "**" + name + "** " : "") + "<#" + id + ">";
|
||||||
|
});
|
||||||
|
return embed(
|
||||||
|
channels.length === 1 && channelId
|
||||||
|
? "\u2705 24/7 is now **enabled** in <#" + channelId + ">\n\n" +
|
||||||
|
"The bot will stay connected and auto-rejoin if disconnected."
|
||||||
|
: "\u2705 24/7 active in " + channels.length + " channel(s):\n\n" + lines.join("\n"),
|
||||||
|
{ title: "\u2705 24/7 Mode" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return embed(
|
||||||
|
"\u274c 24/7 is **disabled**\n\n" +
|
||||||
|
"The bot will leave voice channels when idle.\n\n" +
|
||||||
|
"Join a voice channel and use `" + prefix + "247` to enable.",
|
||||||
|
{ title: "\u274c 24/7 Mode" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Disable 24/7 mode for a specific channel.
|
||||||
|
* Removes the channel from stay_247, marks intentional leave, and destroys the player.
|
||||||
|
* @param {object} ctx - The bot (Remix) context.
|
||||||
|
* @param {ServerSettings} set - The guild settings instance.
|
||||||
|
* @param {string} guildId - The guild ID.
|
||||||
|
* @param {string} channelId - The channel ID to disable.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function disable247(ctx, set, guildId, channelId) {
|
||||||
|
const id = cleanId(channelId);
|
||||||
|
const channels = get247Channels(set);
|
||||||
|
channels.delete(id);
|
||||||
|
save247Channels(set, channels);
|
||||||
|
ctx.markIntentionalLeave?.(id);
|
||||||
|
const player = ctx.players.playerMap.get(id)
|
||||||
|
?? [...ctx.players.playerMap.values()].find(p =>
|
||||||
|
cleanId(p?._channelId ?? "") === id &&
|
||||||
|
cleanId(p?._guildId ?? "") === cleanId(guildId)
|
||||||
|
);
|
||||||
|
if (player) {
|
||||||
|
const activeId = cleanId(player._channelId ?? id);
|
||||||
|
ctx.players.playerMap.delete(activeId);
|
||||||
|
if (activeId !== id) ctx.players.playerMap.delete(id);
|
||||||
|
await player.leave().catch(() => {});
|
||||||
|
player.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Enable 24/7 mode for a specific channel.
|
||||||
|
* Enforces MAX_247_CHANNELS (1) by disabling any existing 24/7 channel first,
|
||||||
|
* then saves the new channel and spawns a player if none exists.
|
||||||
|
* @param {object} ctx - The bot (Remix) context.
|
||||||
|
* @param {ServerSettings} set - The guild settings instance.
|
||||||
|
* @param {string} guildId - The guild ID.
|
||||||
|
* @param {string} channelId - The channel ID to enable.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
async function enable247(ctx, set, guildId, channelId) {
|
||||||
|
const id = cleanId(channelId);
|
||||||
|
const channels = get247Channels(set);
|
||||||
|
if (channels.has(id)) return;
|
||||||
|
|
||||||
|
// Platform only supports 1 voice channel per bot per guild.
|
||||||
|
// If another channel already has 24/7, disable it first.
|
||||||
|
if (channels.size >= MAX_247_CHANNELS) {
|
||||||
|
for (const oldId of channels) {
|
||||||
|
if (oldId !== id) {
|
||||||
|
ctx.markIntentionalLeave?.(oldId);
|
||||||
|
const oldPlayer = ctx.players.playerMap.get(oldId)
|
||||||
|
?? [...ctx.players.playerMap.values()].find(p =>
|
||||||
|
cleanId(p?._channelId ?? "") === oldId &&
|
||||||
|
cleanId(p?._guildId ?? "") === cleanId(guildId)
|
||||||
|
);
|
||||||
|
if (oldPlayer) {
|
||||||
|
const activeId = cleanId(oldPlayer._channelId ?? oldId);
|
||||||
|
ctx.players.playerMap.delete(activeId);
|
||||||
|
if (activeId !== oldId) ctx.players.playerMap.delete(oldId);
|
||||||
|
await oldPlayer.leave().catch(() => {});
|
||||||
|
oldPlayer.destroy();
|
||||||
|
}
|
||||||
|
channels.delete(oldId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
channels.add(id);
|
||||||
|
save247Channels(set, channels);
|
||||||
|
const playerExists = ctx.players.playerMap.has(id) ||
|
||||||
|
[...ctx.players.playerMap.values()].some(p =>
|
||||||
|
cleanId(p?._channelId ?? "") === id && cleanId(p?._guildId ?? "") === cleanId(guildId)
|
||||||
|
);
|
||||||
|
if (!playerExists) {
|
||||||
|
try { await ctx._spawnPlayer(guildId, id); } catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Handle the !247 toggle command. If the user is in a 24/7 channel, disable it;
|
||||||
|
* otherwise, enable it for the user's current voice channel.
|
||||||
|
* @param {object} ctx - The bot (Remix) context.
|
||||||
|
* @param {object} message - The command message.
|
||||||
|
* @param {ServerSettings} set - The guild settings instance.
|
||||||
|
* @param {string} guildId - The guild ID.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function handle247Toggle(ctx, message, set, guildId) {
|
||||||
|
const loc = tWrap(ctx, guildId);
|
||||||
|
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
|
||||||
|
|
||||||
|
const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message);
|
||||||
|
if (!userChannelId) {
|
||||||
|
return message.reply(build247Panel(set, ctx, guildId, null));
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = cleanId(userChannelId);
|
||||||
|
const channels = get247Channels(set);
|
||||||
|
|
||||||
|
if (channels.has(id)) {
|
||||||
|
await disable247(ctx, set, guildId, userChannelId);
|
||||||
|
return message.reply(build247Panel(set, ctx, guildId, id));
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await enable247(ctx, set, guildId, userChannelId);
|
||||||
|
if (result?.max) {
|
||||||
|
return message.reply(embed(
|
||||||
|
loc("responses.settings.max247Channels", { max: MAX_247_CHANNELS, prefix: ctx.handler.getPrefix(guildId) })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
return message.reply(build247Panel(set, ctx, guildId, id));
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/settings/setters
|
||||||
|
* @description Value application (applySet) and
|
||||||
|
* shortcut dispatch (handleShortcut) for the settings command. Bodies are
|
||||||
|
* verbatim from the original single-file command.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { cleanId, getMessageGuildId } from "../../src/ui/index.mjs";
|
||||||
|
import runnables from "../../settings/runnables.mjs";
|
||||||
|
import {
|
||||||
|
parseBool, displayValue, getGuildName, embed, tWrap, prettifySettingLabel,
|
||||||
|
BOOL_SETTINGS, VALID_LOCALES, VOLUME_MIN, VOLUME_MAX, PREFIX_MAX, SHORTCUTS,
|
||||||
|
} from "./utils.mjs";
|
||||||
|
import {
|
||||||
|
get247Channels, save247Channels, build247Panel, disable247, handle247Toggle,
|
||||||
|
} from "./channels247.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Apply a new value to a setting, with type-specific validation.
|
||||||
|
* @param {object} ctx - The bot (Remix) context.
|
||||||
|
* @param {object} message - The command message.
|
||||||
|
* @param {ServerSettings} set - The guild settings instance.
|
||||||
|
* @param {string} key - The setting key.
|
||||||
|
* @param {string} rawValue - The raw string value from the command.
|
||||||
|
* @returns {Promise<string|null>} Error message string, or null on success.
|
||||||
|
*/
|
||||||
|
export async function applySet(ctx, message, set, key, rawValue) {
|
||||||
|
if (BOOL_SETTINGS.has(key)) {
|
||||||
|
const bool = parseBool(rawValue);
|
||||||
|
if (bool === null) {
|
||||||
|
return ctx.t(message, "responses.settings.mustBeBool", { setting: key });
|
||||||
|
}
|
||||||
|
set.set(key, bool);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key === "volume") {
|
||||||
|
const num = parseInt(rawValue, 10);
|
||||||
|
if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) {
|
||||||
|
return ctx.t(message, "responses.settings.volumeRange");
|
||||||
|
}
|
||||||
|
set.set(key, num);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key === "locale") {
|
||||||
|
if (!VALID_LOCALES.has(rawValue)) {
|
||||||
|
return ctx.t(message, "responses.settings.invalidLocale", {
|
||||||
|
locale: rawValue,
|
||||||
|
locales: [...VALID_LOCALES].map(l => "`" + l + "`").join(", ")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
set.set(key, rawValue);
|
||||||
|
const gid = getMessageGuildId(message);
|
||||||
|
if (gid) ctx.locale.invalidateCache(gid);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key === "prefix") {
|
||||||
|
if (!rawValue || rawValue.length > PREFIX_MAX) {
|
||||||
|
return ctx.t(message, "responses.settings.prefixLength");
|
||||||
|
}
|
||||||
|
if (/\s/.test(rawValue)) {
|
||||||
|
return ctx.t(message, "responses.settings.prefixSpaces");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (runnables[key]) {
|
||||||
|
const err = runnables[key].call(ctx, rawValue, { msg: message });
|
||||||
|
if (err) return "\u274c " + err;
|
||||||
|
}
|
||||||
|
|
||||||
|
set.set(key, rawValue);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* @async
|
||||||
|
* Handle a settings shortcut command (e.g. `prefix`, `247`).
|
||||||
|
* Dispatches to 24/7 toggle, value display, or value set depending on arguments.
|
||||||
|
* @param {object} ctx - The bot (Remix) context.
|
||||||
|
* @param {object} message - The command message.
|
||||||
|
* @param {string} settingKey - The resolved setting key.
|
||||||
|
* @param {string[]} valueTokens - Remaining argument tokens after the shortcut alias.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function handleShortcut(ctx, message, settingKey, valueTokens) {
|
||||||
|
const set = ctx.getSettings(message);
|
||||||
|
const guildId = getMessageGuildId(message);
|
||||||
|
const t247 = ctx.locale?.translate?.bind(ctx.locale);
|
||||||
|
|
||||||
|
if (valueTokens.length === 0) {
|
||||||
|
if (settingKey === "stay_247") {
|
||||||
|
return handle247Toggle(ctx, message, set, guildId);
|
||||||
|
}
|
||||||
|
const val = set.get(settingKey);
|
||||||
|
const label = prettifySettingLabel(settingKey, t247, guildId);
|
||||||
|
return message.reply(embed("**" + label + "**\nValue: " + displayValue(settingKey, val)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawValue = valueTokens.join(" ");
|
||||||
|
|
||||||
|
if (settingKey === "stay_247") {
|
||||||
|
const mode = rawValue.toLowerCase().trim();
|
||||||
|
if (mode === "off" || mode === "false" || mode === "disable" || mode === "0") {
|
||||||
|
const loc = tWrap(ctx, guildId);
|
||||||
|
if (!guildId) return message.reply(embed(loc("responses.settings.noServer")));
|
||||||
|
const { channelId } = await ctx.players.checkVoiceChannels(message);
|
||||||
|
if (channelId) {
|
||||||
|
await disable247(ctx, set, guildId, channelId);
|
||||||
|
return message.reply(build247Panel(set, ctx, guildId, cleanId(channelId)));
|
||||||
|
}
|
||||||
|
for (const [chId, player] of [...ctx.players.playerMap.entries()]) {
|
||||||
|
if (cleanId(player?._guildId ?? "") === cleanId(guildId)) {
|
||||||
|
const activeId = cleanId(player._channelId ?? chId);
|
||||||
|
ctx.markIntentionalLeave?.(activeId);
|
||||||
|
ctx.players.playerMap.delete(activeId);
|
||||||
|
if (activeId !== chId) ctx.players.playerMap.delete(chId);
|
||||||
|
await player.leave().catch(() => {});
|
||||||
|
player.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
save247Channels(set, new Set());
|
||||||
|
return message.reply(build247Panel(set, ctx, guildId, null));
|
||||||
|
}
|
||||||
|
return handle247Toggle(ctx, message, set, guildId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const err = await applySet(ctx, message, set, settingKey, rawValue);
|
||||||
|
if (err) return message.reply(embed(err));
|
||||||
|
|
||||||
|
const val = set.get(settingKey);
|
||||||
|
const label = prettifySettingLabel(settingKey, t247, guildId);
|
||||||
|
return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label, value: displayValue(settingKey, val) })));
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
/**
|
||||||
|
* @module commands/settings/utils
|
||||||
|
* @description Constants and pure helpers
|
||||||
|
* shared by the settings command modules. Bodies are verbatim from the
|
||||||
|
* original single-file command; `export ` prefixes and setValidLocales()
|
||||||
|
* are the only additions.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getGlobalColor, cleanId } from "../../src/ui/index.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command alias to setting key mapping.
|
||||||
|
* @type {Object.<string, string>}
|
||||||
|
*/
|
||||||
|
export const SHORTCUTS = {
|
||||||
|
prefix: "prefix",
|
||||||
|
pfx: "prefix",
|
||||||
|
"247": "stay_247",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** @private @type {Set<string>} Strings that evaluate to boolean true. */
|
||||||
|
const BOOL_TRUE = new Set(["true", "1", "yes", "on", "enable", "enabled"]);
|
||||||
|
/** @private @type {Set<string>} Strings that evaluate to boolean false. */
|
||||||
|
const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]);
|
||||||
|
/** @private @type {Set<string>} Setting keys that use boolean display formatting. */
|
||||||
|
export const BOOL_SETTINGS = new Set(["songAnnouncements"]);
|
||||||
|
|
||||||
|
/** @private @type {Set<string>} Available locale codes, populated at load time. */
|
||||||
|
export let VALID_LOCALES = new Set(["en"]);
|
||||||
|
|
||||||
|
/** @private @type {number} Minimum allowed volume value. */
|
||||||
|
export const VOLUME_MIN = 1;
|
||||||
|
/** @private @type {number} Maximum allowed volume value. */
|
||||||
|
export const VOLUME_MAX = 200;
|
||||||
|
/** @private @type {number} Maximum prefix length in characters. */
|
||||||
|
export const PREFIX_MAX = 5;
|
||||||
|
/** @private @type {number} Maximum number of 24/7 channels per guild. */
|
||||||
|
export const MAX_247_CHANNELS = 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace the set of known locale codes (called by the settings command
|
||||||
|
* factory at load time). Importers read VALID_LOCALES as a live binding,
|
||||||
|
* so this stays behavior-identical to the original module-level assignment.
|
||||||
|
* @param {Iterable<string>} locales
|
||||||
|
*/
|
||||||
|
export function setValidLocales(locales) {
|
||||||
|
VALID_LOCALES = locales;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether a string looks like a valid Fluxer ID (Snowflake-like).
|
||||||
|
* @param {string} id - The ID to validate.
|
||||||
|
* @returns {boolean} True if the ID is 15-22 characters after cleaning.
|
||||||
|
*/
|
||||||
|
export function isValidFluxerId(id) {
|
||||||
|
const cleaned = cleanId(id);
|
||||||
|
return cleaned.length >= 15 && cleaned.length <= 22;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Parse a string into a boolean, or return null if unrecognised.
|
||||||
|
* @param {string} str - The string to parse.
|
||||||
|
* @returns {boolean|null} True, false, or null if not a boolean string.
|
||||||
|
*/
|
||||||
|
export function parseBool(str) {
|
||||||
|
const s = String(str).toLowerCase().trim();
|
||||||
|
if (BOOL_TRUE.has(s)) return true;
|
||||||
|
if (BOOL_FALSE.has(s)) return false;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Format a setting value for display in embed messages.
|
||||||
|
* @param {string} key - The setting key.
|
||||||
|
* @param {*} value - The setting value.
|
||||||
|
* @returns {string} Formatted display string.
|
||||||
|
*/
|
||||||
|
export function displayValue(key, value) {
|
||||||
|
if (BOOL_SETTINGS.has(key)) return value ? "\u2705 enabled" : "\u274c disabled";
|
||||||
|
if (value === null || value === undefined || value === "none") return "none";
|
||||||
|
return "`" + value + "`";
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Get the display name of the guild from a message object.
|
||||||
|
* @param {object} message - The command message wrapper.
|
||||||
|
* @returns {string} The guild name, or a fallback string.
|
||||||
|
*/
|
||||||
|
export function getGuildName(message) {
|
||||||
|
return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server";
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Create a simple embed payload with global color, description, and optional title/footer.
|
||||||
|
* @param {string} desc - The embed description text.
|
||||||
|
* @param {object} [opts={}] - Optional overrides for title, iconURL, and footer.
|
||||||
|
* @returns {object} Embed payload for message.reply().
|
||||||
|
*/
|
||||||
|
export function embed(desc, opts = {}) {
|
||||||
|
const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc);
|
||||||
|
if (opts.title) b.setTitle(opts.title);
|
||||||
|
if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL });
|
||||||
|
if (opts.footer) b.setFooter({ text: opts.footer });
|
||||||
|
return { embeds: [b] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Create a translation function bound to the given context and guild.
|
||||||
|
* @param {object} ctx - The bot (Remix) context.
|
||||||
|
* @param {string} guildId - The guild ID for localization.
|
||||||
|
* @returns {Function} A translation function with signature (key, data?) => string.
|
||||||
|
*/
|
||||||
|
export function tWrap(ctx, guildId) {
|
||||||
|
const tFn = ctx.locale?.translate?.bind(ctx.locale);
|
||||||
|
return (key, data = {}) => tFn ? tFn(guildId, key, data) : key;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* @private
|
||||||
|
* Get a human-readable label for a setting key, using locale translations when available.
|
||||||
|
* @param {string} key - The setting key.
|
||||||
|
* @param {Function|null} t - Translation function (guildId, key, data) => string.
|
||||||
|
* @param {string} guildId - The guild ID for localization.
|
||||||
|
* @returns {string} The pretty-printed setting label.
|
||||||
|
*/
|
||||||
|
export function prettifySettingLabel(key, t, guildId) {
|
||||||
|
const localeMap = {
|
||||||
|
songAnnouncements: "responses.settings.labelSongAnnouncements",
|
||||||
|
prefix: "responses.settings.labelPrefix",
|
||||||
|
pfx: "responses.settings.labelPfp",
|
||||||
|
locale: "responses.settings.labelLocale",
|
||||||
|
stay_247: "responses.settings.label247",
|
||||||
|
volume: "responses.settings.labelVolume",
|
||||||
|
};
|
||||||
|
if (localeMap[key] && t && guildId) return t(guildId, localeMap[key]);
|
||||||
|
const fallback = {
|
||||||
|
songAnnouncements: "Song announcements",
|
||||||
|
prefix: "Prefix",
|
||||||
|
pfp: "Bot avatar style",
|
||||||
|
locale: "Locale",
|
||||||
|
stay_247: "24/7 mode",
|
||||||
|
volume: "Default volume",
|
||||||
|
};
|
||||||
|
return fallback[key] ?? key.replace(/_/g, " ");
|
||||||
|
}
|
||||||
@@ -3,9 +3,9 @@
|
|||||||
* @description Randomly re-order the tracks in the playback queue.
|
* @description Randomly re-order the tracks in the playback queue.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
|
|||||||
+2
-2
@@ -3,9 +3,9 @@
|
|||||||
* @description Skip the currently playing track.
|
* @description Skip the currently playing track.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.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()
|
||||||
|
|||||||
+45
-5
@@ -5,11 +5,11 @@
|
|||||||
|
|
||||||
import * as fs from "node:fs";
|
import * as fs from "node:fs";
|
||||||
import * as path from "node:path";
|
import * as path from "node:path";
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @type {CommandBuilder}
|
* @type {CommandBuilder}
|
||||||
@@ -33,6 +33,9 @@ const RATE_LIMIT_MAX_RETRIES = 2;
|
|||||||
const RATE_LIMIT_MAX_WAIT_MS = 15_000;
|
const RATE_LIMIT_MAX_WAIT_MS = 15_000;
|
||||||
/** Where the warm cache is persisted (cwd-relative, same convention as ./storage/defaults.json). */
|
/** Where the warm cache is persisted (cwd-relative, same convention as ./storage/defaults.json). */
|
||||||
const CACHE_FILE = path.join(process.cwd(), "storage", "stats-cache.json");
|
const CACHE_FILE = path.join(process.cwd(), "storage", "stats-cache.json");
|
||||||
|
/** Last-resort label for the gateway line when locale files lack the key
|
||||||
|
* (customized deployments keep their own locale files across updates). */
|
||||||
|
const GATEWAY_FALLBACK_LABEL = "\u{1F310} **Gateway**";
|
||||||
|
|
||||||
let cache = { guilds: null, users: null, scrobbles: null, linkedUsers: null, updatedAt: 0 };
|
let cache = { guilds: null, users: null, scrobbles: null, linkedUsers: null, updatedAt: 0 };
|
||||||
let lastPing = null;
|
let lastPing = null;
|
||||||
@@ -180,6 +183,23 @@ function withBudget(promise, ms, fallback) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read the gateway heartbeat ACK latency from the WebSocket manager
|
||||||
|
* (`client.ws.ping`). Returns -1 when unavailable (not logged in yet, or
|
||||||
|
* no heartbeat ACK received yet).
|
||||||
|
* @private
|
||||||
|
* @param {object} client - The client instance.
|
||||||
|
* @returns {number} Gateway latency in ms, or -1.
|
||||||
|
*/
|
||||||
|
function readGatewayPing(client) {
|
||||||
|
try {
|
||||||
|
const ping = client?.ws?.ping;
|
||||||
|
return typeof ping === "number" && Number.isFinite(ping) ? ping : -1;
|
||||||
|
} catch (_) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Run a message send/edit action, transparently retrying when the REST
|
* Run a message send/edit action, transparently retrying when the REST
|
||||||
* library throws a 429 RateLimitError. Waits exactly as long as the API
|
* library throws a 429 RateLimitError. Waits exactly as long as the API
|
||||||
@@ -236,6 +256,22 @@ function getLivePlayerCount(playerMap) {
|
|||||||
return live;
|
return live;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translate with a hardcoded fallback. 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.
|
||||||
|
* @private
|
||||||
|
* @param {Function} t - Translation function.
|
||||||
|
* @param {object} msg - The command message wrapper.
|
||||||
|
* @param {string} key - Locale key.
|
||||||
|
* @param {string} fallback - Label used when the key is missing.
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
function tOr(t, msg, key, fallback) {
|
||||||
|
const value = t(msg, key);
|
||||||
|
return value === key ? fallback : value;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build the stats embed with all bot information.
|
* Build the stats embed with all bot information.
|
||||||
* @private
|
* @private
|
||||||
@@ -247,7 +283,8 @@ function getLivePlayerCount(playerMap) {
|
|||||||
* @param {number} s.playerCount - Number of active players.
|
* @param {number} s.playerCount - Number of active players.
|
||||||
* @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.
|
* @param {number} s.ping - Bot response ping in ms (REST reply round trip).
|
||||||
|
* @param {number} s.gatewayPing - Gateway heartbeat ACK latency in ms (-1 if unknown).
|
||||||
* @param {string} s.uptime - Formatted uptime string.
|
* @param {string} s.uptime - Formatted uptime string.
|
||||||
* @param {string} s.comHash - Git commit hash.
|
* @param {string} s.comHash - Git commit hash.
|
||||||
* @param {string} s.comLink - Git commit link URL.
|
* @param {string} s.comLink - Git commit link URL.
|
||||||
@@ -276,6 +313,7 @@ function buildEmbed(t, msg, s, pending = []) {
|
|||||||
|
|
||||||
description.push(
|
description.push(
|
||||||
`${t(msg, "responses.stats.ping")} — ${field("ping", `${num(s.ping)}ms`)}`,
|
`${t(msg, "responses.stats.ping")} — ${field("ping", `${num(s.ping)}ms`)}`,
|
||||||
|
s.gatewayPing >= 0 ? `${tOr(t, msg, "responses.stats.gateway", GATEWAY_FALLBACK_LABEL)} — \`${num(s.gatewayPing)}ms\`` : null,
|
||||||
`${t(msg, "responses.stats.uptime")} — \`${s.uptime}\``,
|
`${t(msg, "responses.stats.uptime")} — \`${s.uptime}\``,
|
||||||
`${t(msg, "responses.stats.build")} — [\`${s.comHash}\`](${s.comLink})`,
|
`${t(msg, "responses.stats.build")} — [\`${s.comHash}\`](${s.comLink})`,
|
||||||
s.reason ? `${t(msg, "responses.stats.lastRestart")} — \`${s.reason}\`` : null,
|
s.reason ? `${t(msg, "responses.stats.lastRestart")} — \`${s.reason}\`` : null,
|
||||||
@@ -330,6 +368,7 @@ export async function run(message) {
|
|||||||
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0,
|
||||||
lastfmEnabled,
|
lastfmEnabled,
|
||||||
ping: lastPing ?? 0,
|
ping: lastPing ?? 0,
|
||||||
|
gatewayPing: readGatewayPing(this.client),
|
||||||
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
|
uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000),
|
||||||
comHash: this.comHash,
|
comHash: this.comHash,
|
||||||
comLink: this.comLink,
|
comLink: this.comLink,
|
||||||
@@ -374,6 +413,7 @@ export async function run(message) {
|
|||||||
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,
|
||||||
|
gatewayPing: readGatewayPing(this.client),
|
||||||
};
|
};
|
||||||
|
|
||||||
const stillPending = [];
|
const stillPending = [];
|
||||||
|
|||||||
@@ -3,9 +3,9 @@
|
|||||||
* @description Displays a link and invitation to the bot's support server.
|
* @description Displays a link and invitation to the bot's support server.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the support command. */
|
/** @type {CommandBuilder} @description Command definition for the support command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
|
|||||||
+3
-3
@@ -3,10 +3,10 @@
|
|||||||
* @description Owner-only diagnostic command to display voice channel user counts.
|
* @description Owner-only diagnostic command to display voice channel user counts.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the test command (owner-only). */
|
/** @type {CommandBuilder} @description Command definition for the test command (owner-only). */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
|
|||||||
@@ -3,9 +3,9 @@
|
|||||||
* @description Display the thumbnail artwork of the currently playing track.
|
* @description Display the thumbnail artwork of the currently playing track.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.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()
|
||||||
|
|||||||
@@ -3,12 +3,12 @@
|
|||||||
* @description Set custom start/end times for tracks with named alias support.
|
* @description Set custom start/end times for tracks with named alias support.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
import { ERROR_COLOR } from "../src/constants/UI.mjs";
|
import { ERROR_COLOR } from "../src/utils/UI.mjs";
|
||||||
|
|
||||||
/** @private @type {string} The default alias name for non-named track options. */
|
/** @private @type {string} The default alias name for non-named track options. */
|
||||||
const DEFAULT_ALIAS = "default";
|
const DEFAULT_ALIAS = "default";
|
||||||
|
|||||||
+3
-3
@@ -3,10 +3,10 @@
|
|||||||
* @description Get or change the playback volume for the current voice channel.
|
* @description Get or change the playback volume for the current voice channel.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { MAX_VOLUME } from "../src/constants/UI.mjs";
|
import { MAX_VOLUME } from "../src/utils/UI.mjs";
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -3,11 +3,11 @@
|
|||||||
* @description View or set the server default volume. Requires Manage Server permission to set.
|
* @description View or set the server default volume. Requires Manage Server permission to set.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { PermissionFlags } from "@fluxerjs/core";
|
import { PermissionFlags } from "@fluxerjs/core";
|
||||||
import { MAX_VOLUME } from "../src/constants/UI.mjs";
|
import { MAX_VOLUME } from "../src/utils/UI.mjs";
|
||||||
|
|
||||||
/** @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()
|
||||||
|
|||||||
+6
-6
@@ -3,13 +3,13 @@
|
|||||||
* @description View voting info, check voters, or browse voter lists for a server/bot on FluxerList.
|
* @description View voting info, check voters, or browse voter lists for a server/bot on FluxerList.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder } from "../src/CommandHandler.mjs";
|
import { CommandBuilder } from "../src/commands/index.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getGlobalColor } from "../src/MessageHandler.mjs";
|
import { getGlobalColor } from "../src/ui/index.mjs";
|
||||||
import { Utils } from "../src/Utils.mjs";
|
import { Utils } from "../src/utils/Utils.mjs";
|
||||||
import { FLUXERLIST, buildVoteLink } from "../src/constants/API.mjs";
|
import { FLUXERLIST, buildVoteLink } from "../src/utils/API.mjs";
|
||||||
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs";
|
import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
|
||||||
/** @type {CommandBuilder} @description Command definition for the vote command. */
|
/** @type {CommandBuilder} @description Command definition for the vote command. */
|
||||||
export const command = new CommandBuilder()
|
export const command = new CommandBuilder()
|
||||||
|
|||||||
+9
-1
@@ -62,7 +62,7 @@
|
|||||||
"dashboard": {
|
"dashboard": {
|
||||||
"enabled": false,
|
"enabled": false,
|
||||||
"redis": {
|
"redis": {
|
||||||
"url": "redis://localhost:6379"
|
"url": "redis://127.0.0.1:6379"
|
||||||
},
|
},
|
||||||
"Comment": "Optional dashboard backend. When enabled, the bot speaks Redis RPC (request/response/info channels) with an external web frontend. Login codes are verified (bcrypt) from the MySQL login_codes table. Keep Redis network-isolated — the RPC channel has no shared secret."
|
"Comment": "Optional dashboard backend. When enabled, the bot speaks Redis RPC (request/response/info channels) with an external web frontend. Login codes are verified (bcrypt) from the MySQL login_codes table. Keep Redis network-isolated — the RPC channel has no shared secret."
|
||||||
},
|
},
|
||||||
@@ -116,5 +116,13 @@
|
|||||||
"searchSessionTimeout": 30000,
|
"searchSessionTimeout": 30000,
|
||||||
"playerSessionTimeout": 300000,
|
"playerSessionTimeout": 300000,
|
||||||
"intentionalLeaveTTL": 8000
|
"intentionalLeaveTTL": 8000
|
||||||
|
},
|
||||||
|
"sharding-Comment": "Optional process-level sharding (@fluxerjs/sharding 3.0, beta). Only read by 'node shard.mjs' / 'npm run shard' — plain 'npm start' ignores this block entirely. totalShards: total gateway shards (use an explicit number, never 'auto'); shardsPerProcess: how many shards each child process runs; respawn: restart dead children; spawnTimeout: ms to wait for a child's ready IPC; spawnDelay: ms between successive spawns. The FLUXER_TOTAL_SHARDS / FLUXER_SHARDS_PER_PROCESS env vars override the first two (handy for Docker). Sharding only matters at ~2500+ guilds; leave at defaults otherwise. Caveats: DMs only reach shard 0, and the dashboard is single-process-first.",
|
||||||
|
"sharding": {
|
||||||
|
"totalShards": 1,
|
||||||
|
"shardsPerProcess": 1,
|
||||||
|
"respawn": true,
|
||||||
|
"spawnTimeout": 30000,
|
||||||
|
"spawnDelay": 5000
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -36,7 +36,7 @@ USER remix
|
|||||||
EXPOSE 80
|
EXPOSE 80
|
||||||
|
|
||||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
||||||
CMD pgrep -f "node index.mjs" >/dev/null 2>&1 || exit 1
|
CMD pgrep -f "node .*index.mjs" >/dev/null 2>&1 || pgrep -f "node .*shard.mjs" >/dev/null 2>&1 || exit 1
|
||||||
|
|
||||||
ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"]
|
ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"]
|
||||||
|
|
||||||
|
|||||||
@@ -21,4 +21,8 @@ if [ "$1" = "node" ] && [ "$2" = "index.mjs" ]; then
|
|||||||
echo "[Docker] Starting Remix bot..."
|
echo "[Docker] Starting Remix bot..."
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [ "$1" = "node" ] && [ "$2" = "shard.mjs" ]; then
|
||||||
|
echo "[Docker] Starting Remix bot (sharded supervisor)..."
|
||||||
|
fi
|
||||||
|
|
||||||
exec "$@"
|
exec "$@"
|
||||||
Generated
-1741
File diff suppressed because it is too large.
Load diff
+5
-4
@@ -4,10 +4,10 @@
|
|||||||
"node": ">=22.13.0"
|
"node": ">=22.13.0"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@discordjs/opus": "^0.10.0",
|
"@fluxerjs/core": "^3.0.0",
|
||||||
"@fluxerjs/core": "^2.2.0",
|
"@fluxerjs/sharding": "^3.0.0",
|
||||||
"@fluxerjs/util": "^2.2.0",
|
"@fluxerjs/util": "^3.0.0",
|
||||||
"@fluxerjs/voice": "^2.2.0",
|
"@fluxerjs/voice": "^3.0.0",
|
||||||
"bcryptjs": "^3.0.3",
|
"bcryptjs": "^3.0.3",
|
||||||
"ffprobe-static": "^3.1.0",
|
"ffprobe-static": "^3.1.0",
|
||||||
"lavalink-client": "^2.10.3",
|
"lavalink-client": "^2.10.3",
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
"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",
|
||||||
"migrate": "node settings/migrate.mjs"
|
"migrate": "node settings/migrate.mjs"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+2
-2
@@ -5,7 +5,7 @@ Per-guild settings for Remix, backed by MySQL.
|
|||||||
## How it works
|
## How it works
|
||||||
|
|
||||||
- Defaults live in `storage/defaults.json`. Every guild starts from this template.
|
- Defaults live in `storage/defaults.json`. Every guild starts from this template.
|
||||||
- `src/Settings.mjs` contains the implementation:
|
- `src/db/Settings.mjs` contains the implementation:
|
||||||
- `SettingsManager` — defines the setting keys, their defaults and descriptions.
|
- `SettingsManager` — defines the setting keys, their defaults and descriptions.
|
||||||
- `ServerSettings` — per-guild view; `get`/`set`/`reset` operate in memory and persist with an 80 ms debounced write.
|
- `ServerSettings` — per-guild view; `get`/`set`/`reset` operate in memory and persist with an 80 ms debounced write.
|
||||||
- `RemoteSettingsManager` — loads every guild row from the MySQL `settings` table (`id` primary key + `data` JSON column) and writes individual keys back with `JSON_SET`.
|
- `RemoteSettingsManager` — loads every guild row from the MySQL `settings` table (`id` primary key + `data` JSON column) and writes individual keys back with `JSON_SET`.
|
||||||
@@ -22,7 +22,7 @@ Per-guild settings for Remix, backed by MySQL.
|
|||||||
|
|
||||||
| File | Purpose |
|
| File | Purpose |
|
||||||
| :--- | :--- |
|
| :--- | :--- |
|
||||||
| `Settings.mjs` | Re-export of `src/Settings.mjs` classes |
|
| `Settings.mjs` | Re-export of `src/db/Settings.mjs` classes |
|
||||||
| `migrate.mjs` | One-shot tool that clones every guild row from one settings table/bot ID to another (`npm run migrate`) |
|
| `migrate.mjs` | One-shot tool that clones every guild row from one settings table/bot ID to another (`npm run migrate`) |
|
||||||
| `runnables.mjs` | Validators applied when a setting changes (e.g. `prefix` must be ≤ 5 chars with no whitespace, `pfp` only accepts `default`) |
|
| `runnables.mjs` | Validators applied when a setting changes (e.g. `prefix` must be ≤ 5 chars with no whitespace, `pfp` only accepts `default`) |
|
||||||
|
|
||||||
|
|||||||
@@ -2,4 +2,4 @@
|
|||||||
* @module settings/Settings
|
* @module settings/Settings
|
||||||
* @description Re-exports the core Settings classes from `src/Settings.mjs`.
|
* @description Re-exports the core Settings classes from `src/Settings.mjs`.
|
||||||
*/
|
*/
|
||||||
export { SettingsManager, ServerSettings, RemoteSettingsManager } from "../src/Settings.mjs";
|
export { SettingsManager, ServerSettings, RemoteSettingsManager } from "../src/db/Settings.mjs";
|
||||||
@@ -5,9 +5,9 @@
|
|||||||
* Reads `config.json` for MySQL credentials and runs once on the "ready" event.
|
* Reads `config.json` for MySQL credentials and runs once on the "ready" event.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { RemoteSettingsManager } from "../src/Settings.mjs";
|
import { RemoteSettingsManager } from "../src/db/Settings.mjs";
|
||||||
import fs from "node:fs";
|
import fs from "node:fs";
|
||||||
import { logger } from "../src/constants/Logger.mjs";
|
import { logger } from "../src/core/Logger.mjs";
|
||||||
|
|
||||||
const config = JSON.parse(fs.readFileSync(new URL("../config.json", import.meta.url)));
|
const config = JSON.parse(fs.readFileSync(new URL("../config.json", import.meta.url)));
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
/**
|
||||||
|
* @module shard
|
||||||
|
* @description Opt-in process-level sharding supervisor for the Remix music
|
||||||
|
* bot, built on @fluxerjs/sharding 3.0 (beta).
|
||||||
|
*
|
||||||
|
* Forks one child process per shard slice; every child runs the standard
|
||||||
|
* `index.mjs` boot path, attaches the child-side ShardClientUtil before
|
||||||
|
* login (see src/core/Bot.mjs), and reports readiness over IPC. The manager
|
||||||
|
* owns the shared per-IP IDENTIFY budget so children never collectively
|
||||||
|
* exceed the gateway's identify limit.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* node shard.mjs (or `npm run shard`)
|
||||||
|
*
|
||||||
|
* Single-process operation (`npm start` / `node index.mjs`) is unchanged and
|
||||||
|
* remains the default — sharding is purely additive.
|
||||||
|
*
|
||||||
|
* Configuration (config.json, optional `sharding` object):
|
||||||
|
* {
|
||||||
|
* "sharding": {
|
||||||
|
* "totalShards": 4, // gateway shards across all children
|
||||||
|
* "shardsPerProcess": 2, // gateway shards per child process
|
||||||
|
* "respawn": true, // restart dead children
|
||||||
|
* "spawnTimeout": 30000, // ms to wait for a child's ready IPC
|
||||||
|
* "spawnDelay": 5000 // ms between successive spawns
|
||||||
|
* }
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
* Environment overrides (win over config.json — handy for Docker):
|
||||||
|
* FLUXER_TOTAL_SHARDS, FLUXER_SHARDS_PER_PROCESS
|
||||||
|
*
|
||||||
|
* Notes:
|
||||||
|
* - DMs and guild-less events only reach shard 0 (Fluxer limitation).
|
||||||
|
* - Prefer an explicit totalShards number: Fluxer's /gateway/bot always
|
||||||
|
* reports `shards: 1`, so `'auto'` is not offered here.
|
||||||
|
* - The FLUXER_SHARD_* / FLUXER_TOKEN env vars are set by the manager on
|
||||||
|
* its children — never export them manually.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as fs from "node:fs";
|
||||||
|
import { fileURLToPath } from "node:url";
|
||||||
|
import { ShardingManager } from "@fluxerjs/sharding";
|
||||||
|
import { logger } from "./src/core/Logger.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load config.json with the same fatal-error semantics as src/core/Bot.mjs.
|
||||||
|
* @returns {{token: string, sharding?: object}} The parsed config.
|
||||||
|
*/
|
||||||
|
function loadConfig() {
|
||||||
|
let config;
|
||||||
|
try {
|
||||||
|
config = JSON.parse(fs.readFileSync("config.json", "utf8"));
|
||||||
|
} catch (e) {
|
||||||
|
const reason = e.code === "ENOENT"
|
||||||
|
? "config.json not found. Copy config_example.json → config.json and fill in your values."
|
||||||
|
: `config.json is malformed JSON: ${e.message}`;
|
||||||
|
console.error(`[Sharding] FATAL: ${reason}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (config.token == null) {
|
||||||
|
console.error('[Sharding] FATAL: config.json is missing required key "token".');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a positive integer from an env var (undefined when unset/invalid).
|
||||||
|
* @param {string} name - The env var name.
|
||||||
|
* @returns {number|undefined}
|
||||||
|
*/
|
||||||
|
function envPositiveInt(name) {
|
||||||
|
const raw = process.env[name];
|
||||||
|
if (raw === undefined || raw === "") return undefined;
|
||||||
|
const n = Number(raw);
|
||||||
|
return Number.isFinite(n) && n > 0 ? Math.floor(n) : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a positive integer from the sharding config with a default.
|
||||||
|
* @param {object} shardingCfg - The config's `sharding` object.
|
||||||
|
* @param {string} key - The key to read.
|
||||||
|
* @param {number} fallback - Default value.
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
function cfgPositiveInt(shardingCfg, key, fallback) {
|
||||||
|
const n = Number(shardingCfg?.[key]);
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = loadConfig();
|
||||||
|
const shardingCfg = config.sharding ?? {};
|
||||||
|
|
||||||
|
const totalShards = envPositiveInt("FLUXER_TOTAL_SHARDS")
|
||||||
|
?? cfgPositiveInt(shardingCfg, "totalShards", 1);
|
||||||
|
const shardsPerProcess = envPositiveInt("FLUXER_SHARDS_PER_PROCESS")
|
||||||
|
?? cfgPositiveInt(shardingCfg, "shardsPerProcess", 1);
|
||||||
|
const respawn = shardingCfg.respawn !== false;
|
||||||
|
const spawnTimeout = cfgPositiveInt(shardingCfg, "spawnTimeout", 30_000);
|
||||||
|
const spawnDelay = Math.max(0, Number(shardingCfg.spawnDelay) >= 0 ? Number(shardingCfg.spawnDelay) : 5_000);
|
||||||
|
|
||||||
|
// Absolute path to the bot entry — robust regardless of cwd (fork resolves
|
||||||
|
// relative paths against cwd, but the manager may be started from anywhere).
|
||||||
|
const entryFile = fileURLToPath(new URL("./index.mjs", import.meta.url));
|
||||||
|
|
||||||
|
const manager = new ShardingManager(entryFile, {
|
||||||
|
token: config.token,
|
||||||
|
totalShards,
|
||||||
|
shardsPerProcess,
|
||||||
|
respawn,
|
||||||
|
spawnTimeout,
|
||||||
|
spawnDelay,
|
||||||
|
});
|
||||||
|
|
||||||
|
manager.on("shardCreate", (shard) => {
|
||||||
|
logger.player(`[Sharding] Spawning shard process ${shard.id} (gateway shards ${shard.shardIds.join(", ")})...`);
|
||||||
|
});
|
||||||
|
manager.on("shardReady", (shard) => {
|
||||||
|
logger.player(`[Sharding] Shard process ${shard.id} ready (gateway shards ${shard.shardIds.join(", ")}).`);
|
||||||
|
});
|
||||||
|
manager.on("shardDeath", (shard, info) => {
|
||||||
|
logger.warn(
|
||||||
|
`[Sharding] Shard process ${shard.id} died (code=${info?.code} signal=${info?.signal})` +
|
||||||
|
`${respawn ? " — respawning" : ""}.`
|
||||||
|
);
|
||||||
|
});
|
||||||
|
manager.on("error", (err) => {
|
||||||
|
logger.error("[Sharding] Manager error:", err?.message ?? err);
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Graceful shutdown: destroy all children, then exit.
|
||||||
|
* @param {string} sig - The received signal name. */
|
||||||
|
let shuttingDown = false;
|
||||||
|
const shutdown = async (sig) => {
|
||||||
|
if (shuttingDown) return;
|
||||||
|
shuttingDown = true;
|
||||||
|
logger.recovery(`\n[Sharding] ${sig} received — destroying shard processes...`);
|
||||||
|
try {
|
||||||
|
await manager.destroy();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Sharding] destroy error:", e?.message);
|
||||||
|
}
|
||||||
|
process.exit(0);
|
||||||
|
};
|
||||||
|
process.once("SIGINT", () => shutdown("SIGINT"));
|
||||||
|
process.once("SIGTERM", () => shutdown("SIGTERM"));
|
||||||
|
process.on("SIGPIPE", () => {});
|
||||||
|
|
||||||
|
manager.spawn().then((shards) => {
|
||||||
|
logger.player(
|
||||||
|
`[Sharding] ${shards.size} shard process(es) online — ${totalShards} gateway shard(s), ` +
|
||||||
|
`${shardsPerProcess} per process (respawn ${respawn ? "on" : "off"}).`
|
||||||
|
);
|
||||||
|
}).catch((e) => {
|
||||||
|
logger.error("[Sharding] Spawn failed:", e?.message ?? e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -1,927 +0,0 @@
|
|||||||
/** @module src/CommandHandler @description Command registration, loading, parsing, and execution framework with builder pattern, subcommands, and flags. */
|
|
||||||
import { pathToFileURL } from "node:url";
|
|
||||||
import { logger } from "./constants/Logger.mjs";
|
|
||||||
import { Utils } from "./Utils.mjs";
|
|
||||||
import { EventEmitter } from "node:events";
|
|
||||||
import { Message, MessageHandler, PageBuilder, REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs";
|
|
||||||
import { Client, PermissionFlags } from "@fluxerjs/core";
|
|
||||||
import { SettingsManager } from "./Settings.mjs";
|
|
||||||
import path from "node:path";
|
|
||||||
import * as fs from "node:fs";
|
|
||||||
|
|
||||||
/** @class CommandBuilder @description Fluent builder for constructing command definitions with name, description, options, subcommands, aliases, and requirements. */
|
|
||||||
export class CommandBuilder {
|
|
||||||
/** Create a new CommandBuilder with default empty state. */
|
|
||||||
constructor() {
|
|
||||||
this.name = null;
|
|
||||||
this.description = null;
|
|
||||||
this.id = null;
|
|
||||||
this.aliases = [];
|
|
||||||
this.subcommands = [];
|
|
||||||
this.options = [];
|
|
||||||
this.requirements = [];
|
|
||||||
this.category = "default";
|
|
||||||
this.examples = [];
|
|
||||||
|
|
||||||
this.uid = Utils.uid();
|
|
||||||
|
|
||||||
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
|
|
||||||
this.parent = null;
|
|
||||||
}
|
|
||||||
/** Set the command name and add it as the primary alias. @param {string} n @returns {CommandBuilder} */
|
|
||||||
setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; }
|
|
||||||
/** Set the command description. @param {string} d @returns {CommandBuilder} */
|
|
||||||
setDescription(d) { this.description = d; return this; }
|
|
||||||
/** Set the command ID. @param {string} id @returns {CommandBuilder} */
|
|
||||||
setId(id) { this.id = id; return this; }
|
|
||||||
/** @returns {string} Full command path including parent chain (e.g. "music play"). */
|
|
||||||
get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; }
|
|
||||||
/** Add a permission/owner-only requirement. @param {Function} config @returns {CommandBuilder} */
|
|
||||||
setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; }
|
|
||||||
/** Add a subcommand builder. @param {Function} config @returns {CommandBuilder} */
|
|
||||||
addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; }
|
|
||||||
/** Add a string option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
|
||||||
addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; }
|
|
||||||
/** Add a number option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
|
||||||
addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; }
|
|
||||||
/** Add a boolean option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
|
||||||
addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; }
|
|
||||||
/** Add a channel option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
|
||||||
addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; }
|
|
||||||
/** Add a user option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
|
||||||
addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; }
|
|
||||||
/** Add a text (remaining-args) option. Only one is allowed per command. @param {Function} config @returns {CommandBuilder} @throws {Error} If a text option already exists. */
|
|
||||||
addTextOption(config) {
|
|
||||||
if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option.");
|
|
||||||
this.options.push(config(new Option("text")));
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
/** Add a choice option (enum-like). @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
|
||||||
addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; }
|
|
||||||
/** Add an alias. @param {string} alias @returns {CommandBuilder} */
|
|
||||||
addAlias(alias) { if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this; this.aliases.push(alias.toLowerCase()); return this; }
|
|
||||||
/** Add multiple aliases. @param {...string} aliases @returns {CommandBuilder} */
|
|
||||||
addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; }
|
|
||||||
/** Set the command category. @param {string} cat @returns {CommandBuilder} */
|
|
||||||
setCategory(cat) { this.category = cat; return this; }
|
|
||||||
/** Add usage examples. @param {...string} examples @returns {CommandBuilder} */
|
|
||||||
addExamples(...examples) { this.examples.push(...examples); return this; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @class CommandRequirement @description Defines permission and owner-only requirements for commands. */
|
|
||||||
export class CommandRequirement {
|
|
||||||
/** @type {boolean} Whether the command is restricted to bot owners. */
|
|
||||||
ownerOnly = false;
|
|
||||||
/** Create a new CommandRequirement. */
|
|
||||||
constructor() {
|
|
||||||
this.permissions = [];
|
|
||||||
this.permissionError = "You don't have the needed permissions to run this command!";
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
/** @param {boolean} bool @returns {CommandRequirement} */
|
|
||||||
setOwnerOnly(bool) { this.ownerOnly = bool; return this; }
|
|
||||||
/** @param {string} p @returns {CommandRequirement} */
|
|
||||||
addPermission(p) { this.permissions.push(p); return this; }
|
|
||||||
/** @param {...string} p @returns {CommandRequirement} */
|
|
||||||
addPermissions(...p) { this.permissions.push(...p); return this; }
|
|
||||||
/** @returns {string[]} */
|
|
||||||
getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; }
|
|
||||||
/** @param {string} e @returns {CommandRequirement} */
|
|
||||||
setPermissionError(e) { this.permissionError = e; return this; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @class Option @description Represents a command option (string, number, boolean, channel, choice, flag) with validation and formatting. */
|
|
||||||
export class Option {
|
|
||||||
/** @type {number} @description Maximum choices before switching to compact format. */
|
|
||||||
static THRESHOLD = 10;
|
|
||||||
/** @type {number} @description Number of choice columns per line in compact format. */
|
|
||||||
static COLS_PER_LINE = 5;
|
|
||||||
|
|
||||||
/** Format choice values in a compact multi-column layout. @param {string[]} choices @param {number} [perLine=Option.COLS_PER_LINE] @returns {string} */
|
|
||||||
static formatChoicesCompact(choices, perLine = Option.COLS_PER_LINE) {
|
|
||||||
const lines = [];
|
|
||||||
for (let i = 0; i < choices.length; i += perLine) {
|
|
||||||
lines.push(choices.slice(i, i + perLine).map(c => '`' + c + '`').join(' · '));
|
|
||||||
}
|
|
||||||
return lines.join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Format choice values inline, switching to compact layout above the threshold. @param {string[]} choices @returns {string} */
|
|
||||||
static formatChoicesInline(choices) {
|
|
||||||
if (choices.length <= Option.THRESHOLD) {
|
|
||||||
return '`' + choices.join('`, `') + '`';
|
|
||||||
}
|
|
||||||
return Option.formatChoicesCompact(choices, 6);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Format choice values for a usage string, truncating with "…" if over max. @param {string[]} choices @param {number} [max=6] @returns {string} */
|
|
||||||
static formatChoicesUsage(choices, max = 6) {
|
|
||||||
if (choices.length <= max) return choices.join(' | ');
|
|
||||||
return choices.slice(0, max).join(' | ') + ' | ...';
|
|
||||||
}
|
|
||||||
channelRegex = /^<#(?<id>\d+)>/;
|
|
||||||
userRegex = /^<@!?(?<id>\d+)>/;
|
|
||||||
idRegex = /^(?<id>\d+)/;
|
|
||||||
|
|
||||||
/** @type {Function|null} Dynamic default value resolver. */
|
|
||||||
dynamicDefault;
|
|
||||||
|
|
||||||
/** Create a new Option. @param {string} [type="string"] */
|
|
||||||
constructor(type = "string") {
|
|
||||||
this.name = null;
|
|
||||||
this.description = null;
|
|
||||||
this.required = false;
|
|
||||||
this.id = null;
|
|
||||||
this.uid = Utils.uid();
|
|
||||||
this.type = type;
|
|
||||||
this.tError = null;
|
|
||||||
this.aliases = [null];
|
|
||||||
this.choices = [];
|
|
||||||
this.translations = {};
|
|
||||||
this.defaultValue = null;
|
|
||||||
this.dynamicDefault = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Factory to create an Option or Flag instance. @param {string} type @param {boolean} [flag=false] @returns {Option|Flag} */
|
|
||||||
static create(type, flag = false) {
|
|
||||||
return (!flag) ? new Option(type) : new Flag(type);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Set the option name. @param {string} n @returns {Option} */
|
|
||||||
setName(n) { this.name = n; this.aliases[0] = n; return this; }
|
|
||||||
/** Set the option description. @param {string} d @returns {Option} */
|
|
||||||
setDescription(d) { this.description = d; return this; }
|
|
||||||
/** Set whether the option is required. @param {boolean} r @returns {Option} */
|
|
||||||
setRequired(r) { this.required = r; return this; }
|
|
||||||
/** Set the option ID. @param {string} id @returns {Option} */
|
|
||||||
setId(id) { this.id = id; return this; }
|
|
||||||
/** Set the option type. @param {string} t @returns {Option} */
|
|
||||||
setType(t) { this.type = t; return this; }
|
|
||||||
/** Add flag aliases (e.g. "v" for "-v"). @param {...string} a @returns {Option} */
|
|
||||||
addFlagAliases(...a) { this.aliases.push(...a); return this; }
|
|
||||||
/** Add a single valid choice value. @param {string} c @returns {Option} @throws {Error} If option type is not "choice". */
|
|
||||||
addChoice(c) { if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!"); this.choices.push(c); return this; }
|
|
||||||
/** Add multiple valid choice values. @param {...string} cs @returns {Option} @throws {Error} If option type is not "choice". */
|
|
||||||
addChoices(...cs) { if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!"); cs.forEach(c => this.addChoice(c)); return this; }
|
|
||||||
/** Set the default value when the option is omitted. @param {*} value @returns {Option} */
|
|
||||||
setDefault(value) { this.defaultValue = value; return this; }
|
|
||||||
/** Set a dynamic default resolver function. @param {Function} callback @returns {Option} */
|
|
||||||
setDynamicDefault(callback) { this.dynamicDefault = callback; return this; }
|
|
||||||
|
|
||||||
/** Check whether a value is considered empty/omitted. @param {*} i @returns {boolean} */
|
|
||||||
empty(i) {
|
|
||||||
if (i === undefined || i === null) return true;
|
|
||||||
return (!i && !(String(i).includes("0")));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Validate an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {boolean} */
|
|
||||||
validateInput(i, client, msg, type) {
|
|
||||||
switch (type || this.type) {
|
|
||||||
case "text":
|
|
||||||
case "string":
|
|
||||||
return !!i;
|
|
||||||
case "number":
|
|
||||||
return !isNaN(i) && !isNaN(parseFloat(i));
|
|
||||||
case "boolean":
|
|
||||||
return i === "0" || i === "1" || i?.toLowerCase() === "true" || i?.toLowerCase() === "false";
|
|
||||||
case "choice":
|
|
||||||
return this.choices.includes(i);
|
|
||||||
case "user":
|
|
||||||
return this.userRegex.test(i) || this.idRegex.test(i);
|
|
||||||
case "channel":
|
|
||||||
if (i === undefined) return false;
|
|
||||||
return this.channelRegex.test(i) || this.idRegex.test(i) || client.channels.some(c => c.name === i);
|
|
||||||
case "voiceChannel": {
|
|
||||||
if (!i) return false;
|
|
||||||
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
|
||||||
const guildId = msg?.channel?.guildId ?? msg?.guildId;
|
|
||||||
|
|
||||||
const voiceTypes = [2, 13];
|
|
||||||
const byName = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
|
|
||||||
const cObj = results
|
|
||||||
? client.channels.get(results.groups["id"])
|
|
||||||
: (byName ?? null);
|
|
||||||
return cObj ? voiceTypes.includes(cObj.type) : false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Format/parse an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {*} */
|
|
||||||
formatInput(i, client, msg, type) {
|
|
||||||
switch (type || this.type) {
|
|
||||||
case "text":
|
|
||||||
case "string":
|
|
||||||
return i;
|
|
||||||
case "number":
|
|
||||||
return parseFloat(i);
|
|
||||||
case "boolean":
|
|
||||||
return i?.toLowerCase() === "true" || i === "1";
|
|
||||||
case "choice":
|
|
||||||
return i;
|
|
||||||
case "user": {
|
|
||||||
const rs = this.userRegex.exec(i) ?? this.idRegex.exec(i);
|
|
||||||
return rs?.groups["id"] ?? null;
|
|
||||||
}
|
|
||||||
case "channel": {
|
|
||||||
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
|
||||||
const channel = client.channels.find(c => c.name === i);
|
|
||||||
return results ? results.groups["id"] : (channel ? channel.id : null);
|
|
||||||
}
|
|
||||||
case "voiceChannel": {
|
|
||||||
const r = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
|
||||||
const guildId = msg?.channel?.guildId ?? msg?.guildId;
|
|
||||||
if (guildId === "eval") return r ? r.groups["id"] : (i || null);
|
|
||||||
const voiceTypes = [2, 13];
|
|
||||||
const c = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
|
|
||||||
return r ? r.groups["id"] : (c ? c.id : null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Generate a type-error message for this option. @returns {string} */
|
|
||||||
get typeError() {
|
|
||||||
if (this.tError) return this.tError;
|
|
||||||
switch (this.type) {
|
|
||||||
case "choice": {
|
|
||||||
const choiceStr = this.choices.length > Option.THRESHOLD
|
|
||||||
? Option.formatChoicesCompact(this.choices)
|
|
||||||
: this.choices.map(c => '- ' + c).join('\n');
|
|
||||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be one of the following: \n" + choiceStr + "\nSchematic: `$previousCmd <" + this.type + ">`";
|
|
||||||
}
|
|
||||||
case "voiceChannel":
|
|
||||||
case "channel":
|
|
||||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be a channel mention, id, or name.\nSchematic: `$previousCmd <" + this.type + ">`";
|
|
||||||
default:
|
|
||||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** Set a custom type-error message template. @param {string} e */
|
|
||||||
set typeError(e) { this.tError = e; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @class Flag @description A flag-type option that cannot be text. Extends Option. */
|
|
||||||
export class Flag extends Option {
|
|
||||||
/** Create a Flag (non-text option). @param {string} [type="string"] */
|
|
||||||
constructor(type = "string") {
|
|
||||||
if (type === "text") throw new Error("Flags can't be of type 'text'!");
|
|
||||||
super(type);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @class PrefixManager @description Manages per-guild command prefixes (falling back to config or default). */
|
|
||||||
export class PrefixManager {
|
|
||||||
/** @type {RemoteSettingsManager} */
|
|
||||||
settings;
|
|
||||||
/** @type {string|null} */
|
|
||||||
configPrefix;
|
|
||||||
/** @param {RemoteSettingsManager} settings @param {string|null} [configPrefix=null] */
|
|
||||||
constructor(settings, configPrefix = null) { this.settings = settings; this.configPrefix = configPrefix; }
|
|
||||||
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
|
|
||||||
getPrefix(guildId) {
|
|
||||||
const serverPrefix = this.settings.getServer(guildId).get("prefix");
|
|
||||||
return serverPrefix ?? this.configPrefix ?? "%";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @class HelpHandler @description Generates paginated help text for commands. */
|
|
||||||
export class HelpHandler {
|
|
||||||
/** @type {CommandHandler} */
|
|
||||||
commands;
|
|
||||||
/** @type {number} Commands per help page. */
|
|
||||||
commandsPerPage = 5;
|
|
||||||
|
|
||||||
/** Default pagination handler that builds paginated help pages. @param {object} msg - Message wrapper with message data. @param {HelpHandler} helpHandler @param {Array} cmds @returns {string|null} */
|
|
||||||
paginationHandler = (msg, helpHandler, cmds) => {
|
|
||||||
const guildId = msg.message.guildId;
|
|
||||||
let form = this.commands.t(guildId, "cmdHandler.help.pageStructure");
|
|
||||||
|
|
||||||
const contents = cmds.map((cmd, i) => {
|
|
||||||
return (i + 1) + ". **" + cmd.name + "**: " + (cmd.description || "").split("\n")[0];
|
|
||||||
});
|
|
||||||
|
|
||||||
const pages = new PageBuilder(contents)
|
|
||||||
.setForm(helpHandler.commands.format(form, msg.message.guildId))
|
|
||||||
.setMaxLines(helpHandler.commandsPerPage);
|
|
||||||
|
|
||||||
helpHandler.commands.messages.initPagination(pages, msg);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @type {Function|null} Custom help handler function override. */
|
|
||||||
customHelpHandler = null;
|
|
||||||
|
|
||||||
/** @param {CommandHandler} commands */
|
|
||||||
constructor(commands) { this.commands = commands; }
|
|
||||||
|
|
||||||
/** @param {string} string @returns {string} Capitalised first letter. */
|
|
||||||
static capitalise(string) {
|
|
||||||
if (string.length < 1) return string;
|
|
||||||
if (string.length === 1) return string.toUpperCase();
|
|
||||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param {Array} [cmds] @returns {Array} Non-owner-only commands. */
|
|
||||||
userCommands(cmds) {
|
|
||||||
return (cmds || this.commands.commands).filter(c =>
|
|
||||||
c.requirements.findIndex(r => r.ownerOnly) === -1
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @returns {number} Total number of help pages. */
|
|
||||||
pageNumber() {
|
|
||||||
return Math.ceil(this.commands.commands.length / this.commandsPerPage);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param {object} message @returns {string|null} */
|
|
||||||
help(message) {
|
|
||||||
if (this.customHelpHandler) return this.customHelpHandler(message);
|
|
||||||
if (this.paginationHandler) return this.genHelp(null, message, true);
|
|
||||||
return this.getHelpPage(0, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param {number} n @param {object} msg @param {Array} [cmds=null] @returns {string} */
|
|
||||||
getHelpPage(n, msg, cmds = null) {
|
|
||||||
if (!cmds) cmds = this.commands.commands;
|
|
||||||
if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds);
|
|
||||||
let offset = this.commandsPerPage * n;
|
|
||||||
const commands = cmds.slice(offset, offset + this.commandsPerPage);
|
|
||||||
let max = Math.ceil(cmds.length / this.commandsPerPage);
|
|
||||||
return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @param {object|null} page @param {object} msg @param {boolean} [paginate=false] @param {Array} [cmds=null] @returns {string} */
|
|
||||||
genHelp(page, msg, paginate = false, cmds = null) {
|
|
||||||
cmds = this.userCommands(cmds);
|
|
||||||
if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds);
|
|
||||||
|
|
||||||
const guildId = msg.message.guildId;
|
|
||||||
let p = (page) ? ` (page ${page.curr}/${page.max})` : "";
|
|
||||||
const indexOffset = (page) ? page.offset : 0;
|
|
||||||
let content = this.commands.t(guildId, "cmdHandler.help.availableCommands", { $page: p }) + "\n\n";
|
|
||||||
if (page && page.curr !== 1) content += (indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
|
|
||||||
cmds.forEach((cmd, i) => { content += (i + 1 + indexOffset) + ". **" + cmd.name + "**: " + cmd.description + "\n"; });
|
|
||||||
if (page && page.curr !== page.max) content += (cmds.length + indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
|
|
||||||
content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.runHelp"), guildId);
|
|
||||||
if (page) content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.pageTip"), guildId);
|
|
||||||
|
|
||||||
return this.commands.format(content, guildId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Get the description of a command. @param {CommandBuilder} command @returns {string} */
|
|
||||||
commandDescription(command) { return command.description; }
|
|
||||||
|
|
||||||
/** Build a usage string for a command including options and flags. @param {CommandBuilder} cmd @param {object} msg @returns {string} */
|
|
||||||
commandUsage(cmd, msg) {
|
|
||||||
if (cmd.subcommands.length > 0) {
|
|
||||||
return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]";
|
|
||||||
}
|
|
||||||
let options = this.commands.format("$prefix" + cmd.command, msg.message.guildId);
|
|
||||||
cmd.options.forEach(o => {
|
|
||||||
if (o.type === "text") return;
|
|
||||||
if (o instanceof Flag)
|
|
||||||
return options += (o.type === "choice") ? "-" + o.aliases[0] + " <" + Option.formatChoicesUsage(o.choices) + ">" : " -" + o.aliases[0] + " '" + o.type + "'";
|
|
||||||
options += (o.type === "choice") ? " <" + Option.formatChoicesUsage(o.choices) + ">" : " '" + o.name + ": " + o.type + "'";
|
|
||||||
});
|
|
||||||
let o = cmd.options.find(e => e.type === "text");
|
|
||||||
if (o) options += "'" + o.name + ": " + o.type + "'";
|
|
||||||
return options.trim();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Generate detailed help for a single command. @param {object} command @param {object} msg @returns {string} */
|
|
||||||
getCommandHelp(command, msg) {
|
|
||||||
const guildId = msg.message.guildId;
|
|
||||||
let content = `${HelpHandler.capitalise(command.name)}\n`;
|
|
||||||
content += this.commandDescription(command, msg) + "\n\n";
|
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.usage") + "\n💻 `" + this.commandUsage(command, msg) + "`\n\n";
|
|
||||||
if (command.examples.length > 0)
|
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.examples") + "\n- `" + command.examples.map(e => this.commands.format(e, guildId)).join("`\n- `") + "`\n\n";
|
|
||||||
if (command.aliases.length > 1) {
|
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.aliases") + "\n";
|
|
||||||
command.aliases.forEach(alias => { content += "- " + alias + "\n"; });
|
|
||||||
content += "\n";
|
|
||||||
}
|
|
||||||
if (command.subcommands.length > 0) {
|
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.subcommands") + "\n";
|
|
||||||
command.subcommands.forEach(s => {
|
|
||||||
const optCount = s.options.length > 0 ? "; (`" + this.commands.t(guildId, "cmdHandler.help.optionCount", { $count: s.options.length }) + "`)" : "";
|
|
||||||
content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + optCount + "\n";
|
|
||||||
});
|
|
||||||
content += "\n";
|
|
||||||
} else if (command.options.length > 0) {
|
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.arguments") + "\n";
|
|
||||||
command.options.forEach(o => {
|
|
||||||
const optional = ((o.required) ? "" : "?");
|
|
||||||
const flag = (o instanceof Flag) ? "-" : "";
|
|
||||||
if (o.type === "choice") {
|
|
||||||
const choiceDisplay = Option.formatChoicesInline(o.choices);
|
|
||||||
const aliasDisplay = o.aliases.filter(a => a !== null).join('`, `');
|
|
||||||
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";
|
|
||||||
});
|
|
||||||
content += "\n";
|
|
||||||
}
|
|
||||||
if (command.requirements.length > 0) {
|
|
||||||
content += this.commands.t(guildId, "cmdHandler.help.requirements") + "\n";
|
|
||||||
command.requirements.forEach(r => {
|
|
||||||
content += "- " + r.getPermissions().map(e => this.commands.t(guildId, "cmdHandler.help.permission", { $permission: e })).join("\n- ");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return content.trim();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @class CommandHandler @description Main command dispatcher. Parses incoming messages, matches commands, validates arguments, checks permissions, and emits run events. @extends {EventEmitter} */
|
|
||||||
export class CommandHandler extends EventEmitter {
|
|
||||||
/** @type {Function|null} Custom handler when the bot is pinged. */
|
|
||||||
onPing = null;
|
|
||||||
/** @type {boolean} Whether the bot responds to pings as a prefix. */
|
|
||||||
pingPrefix = true;
|
|
||||||
/** @type {string[]} Bot owner user IDs. */
|
|
||||||
owners = [];
|
|
||||||
|
|
||||||
messages;
|
|
||||||
client;
|
|
||||||
prefixes;
|
|
||||||
helpHandler;
|
|
||||||
|
|
||||||
commandNames = [];
|
|
||||||
commands = [];
|
|
||||||
|
|
||||||
locale = null;
|
|
||||||
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`";
|
|
||||||
textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string.";
|
|
||||||
|
|
||||||
/** @private @type {Map<string, number>} Per-user last command timestamps for cooldown enforcement. */
|
|
||||||
_cmdCooldowns = new Map();
|
|
||||||
/** @private @type {number} Cooldown duration in milliseconds between commands per non-owner user. */
|
|
||||||
_cmdCooldownMs = 1500;
|
|
||||||
|
|
||||||
/** @param {MessageHandler} handler - The message handler instance. @param {string} [prefix="%"] - Default command prefix. */
|
|
||||||
constructor(handler, prefix = "%") {
|
|
||||||
super();
|
|
||||||
this.messages = handler;
|
|
||||||
this.client = handler.client;
|
|
||||||
this.prefix = prefix;
|
|
||||||
this.helpHandler = new HelpHandler(this);
|
|
||||||
this.helpCommand = "help";
|
|
||||||
this.replyHandler = (message, msg) => {
|
|
||||||
msg.reply(this.format(message, msg.channel.channel.guildId));
|
|
||||||
};
|
|
||||||
this.messages.onMessage(this.messageHandler.bind(this));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
|
|
||||||
getPrefix(guildId) { return this.prefixes.getPrefix(guildId); }
|
|
||||||
/** Enable or disable ping-as-prefix. @param {boolean} bool */
|
|
||||||
setPingPrefix(bool) { this.pingPrefix = bool; }
|
|
||||||
/** Set the prefix manager instance. @param {PrefixManager} manager */
|
|
||||||
setPrefixManager(manager) { this.prefixes = manager; }
|
|
||||||
/** Set a custom help handler. @param {HelpHandler} handler */
|
|
||||||
setHelpHandler(handler) { this.helpHandler = handler; }
|
|
||||||
/** Set the locale manager. @param {object} locale */
|
|
||||||
setLocale(locale) { this.locale = locale; }
|
|
||||||
|
|
||||||
/** Translate a locale key. @param {string} guildId @param {string} key @param {object} [replacements={}] @returns {string} */
|
|
||||||
t(guildId, key, replacements = {}) {
|
|
||||||
if (!this.locale) return key;
|
|
||||||
return this.locale.translate(guildId, key, replacements);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Replace $prefix and $helpCmd placeholders in text. @param {string} text @param {string} guildId @returns {string} */
|
|
||||||
format(text, guildId) {
|
|
||||||
const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId);
|
|
||||||
return text
|
|
||||||
.replace(/\$prefix/gi, prefix)
|
|
||||||
.replace(/\$helpCmd/gi, this.helpCommand);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Remove a command from the registry. @param {CommandBuilder} command */
|
|
||||||
removeCommand(command) {
|
|
||||||
command.aliases.forEach(a => {
|
|
||||||
const idx = this.commandNames.indexOf(a);
|
|
||||||
if (idx !== -1) this.commandNames.splice(idx, 1);
|
|
||||||
});
|
|
||||||
const idx = this.commands.findIndex(c => c.uid === command.uid);
|
|
||||||
if (idx !== -1) this.commands.splice(idx, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @private Handle an incoming message and route to command processing. @param {Message} msg */
|
|
||||||
messageHandler(msg) {
|
|
||||||
if (!msg || !msg.content) return;
|
|
||||||
const trimmed = msg.content.trim();
|
|
||||||
if (/^<@!?\d+>$/.test(trimmed)) {
|
|
||||||
const botId = this.client.user?.id;
|
|
||||||
if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) {
|
|
||||||
return this.onPing?.(msg);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
|
||||||
const prefix = this.getPrefix(guildId);
|
|
||||||
const ping = `<@${this.client.user?.id}>`;
|
|
||||||
const pingBang = `<@!${this.client.user?.id}>`;
|
|
||||||
if (!(msg.content.startsWith(prefix) || msg.content.startsWith(ping) || msg.content.startsWith(pingBang))) return;
|
|
||||||
|
|
||||||
const userId = msg.message?.author?.id ?? msg.author?.id;
|
|
||||||
if (userId && !this.owners.includes(userId)) {
|
|
||||||
const now = Date.now();
|
|
||||||
const last = this._cmdCooldowns.get(userId) ?? 0;
|
|
||||||
if (now - last < this._cmdCooldownMs) return;
|
|
||||||
this._cmdCooldowns.set(userId, now);
|
|
||||||
if (this._cmdCooldowns.size > 500) {
|
|
||||||
const cutoff = now - this._cmdCooldownMs * 2;
|
|
||||||
for (const [uid, ts] of this._cmdCooldowns) {
|
|
||||||
if (ts < cutoff) this._cmdCooldowns.delete(uid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const len = msg.content.startsWith(prefix) ? prefix.length : (msg.content.startsWith(pingBang) ? pingBang.length : ping.length);
|
|
||||||
const args = msg.content.slice(len).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
|
||||||
|
|
||||||
if (!args[0]) return;
|
|
||||||
|
|
||||||
if (args[0] === this.helpCommand) {
|
|
||||||
if (!args[1]) {
|
|
||||||
const res = this.helpHandler.help(msg);
|
|
||||||
return (typeof res === "string") ? this.replyHandler(res, msg) : undefined;
|
|
||||||
}
|
|
||||||
if (args.length > 1 && Utils.isNumber(args[1])) {
|
|
||||||
const pageNumber = parseInt(args[1]);
|
|
||||||
if (pageNumber < 1 || pageNumber > this.helpHandler.pageNumber()) {
|
|
||||||
return this.replyHandler(this.t(guildId, "cmdHandler.page.invalid", { number: pageNumber }), msg);
|
|
||||||
}
|
|
||||||
return this.replyHandler(this.helpHandler.getHelpPage(pageNumber - 1, msg), msg);
|
|
||||||
}
|
|
||||||
if (args.length <= 2) {
|
|
||||||
let idx = this.commands.findIndex(e => e.aliases.some(al => al.toLowerCase() === args[1].toLowerCase()));
|
|
||||||
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + args[1], guildId) }), msg);
|
|
||||||
return this.replyHandler(this.helpHandler.getCommandHelp(this.commands[idx], msg), msg);
|
|
||||||
}
|
|
||||||
let currCmd = null;
|
|
||||||
let prefix2 = "";
|
|
||||||
for (let i = 0; i < args.slice(1).length; i++) {
|
|
||||||
let a = args.slice(1)[i];
|
|
||||||
let curr = (currCmd) ? currCmd.subcommands : this.commands;
|
|
||||||
let idx = curr.findIndex(e => e.aliases.some(al => al.toLowerCase() === a.toLowerCase()));
|
|
||||||
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + prefix2 + a, guildId) }), msg);
|
|
||||||
currCmd = curr[idx];
|
|
||||||
prefix2 += a + " ";
|
|
||||||
}
|
|
||||||
return this.replyHandler(this.helpHandler.getCommandHelp(currCmd, msg), msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this.commandNames.includes(args[0].toLowerCase())) {
|
|
||||||
this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix$helpCmd", guildId) }), msg);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Parse and execute a command with its options. @param {CommandBuilder} cmd @param {string[]} args @param {Message} msg @param {string|boolean} [previous=false] @param {boolean} [external=false] @returns {object|undefined} */
|
|
||||||
processCommand(cmd, args, msg, previous = false, external = false) {
|
|
||||||
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
|
||||||
|
|
||||||
if (!external) {
|
|
||||||
const channel = msg.channel?.channel ?? msg.channel;
|
|
||||||
if (channel?.guild) {
|
|
||||||
const botPermResult = this.messages.checkAllBotPermissions(channel);
|
|
||||||
if (botPermResult.criticalMissing.length > 0) {
|
|
||||||
const permEmbed = this.messages.buildPermissionEmbed(botPermResult.missing, channel.guildId);
|
|
||||||
try {
|
|
||||||
msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false });
|
|
||||||
} catch (_) {
|
|
||||||
try {
|
|
||||||
const names = botPermResult.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
|
||||||
msg.message?.reply?.("I'm missing critical permissions: **" + names.join("**, **") + "**. Ask an admin to fix this.", { ping: false });
|
|
||||||
} catch (__) { logger.warn("[CommandHandler] Fallback perm reply failed"); }
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cmd.requirements.length > 0 && !external) {
|
|
||||||
if (!this.assertRequirements(cmd, msg)) return;
|
|
||||||
}
|
|
||||||
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
|
||||||
if (!external) this.emit("command", { command: cmd, message: msg });
|
|
||||||
|
|
||||||
if (cmd.subcommands.length !== 0) {
|
|
||||||
const idx = cmd.subcommands.findIndex(el => {
|
|
||||||
if (!args[1]) return false;
|
|
||||||
return el.name.toLowerCase() === args[1].toLowerCase();
|
|
||||||
});
|
|
||||||
if (idx === -1) {
|
|
||||||
const list = cmd.subcommands.map(s => s.name).join(" | ");
|
|
||||||
const subGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
|
||||||
const e = this.t(subGuildId, "cmdBuilder.subcommand.invalid").replace(/\$previousCmd/gi, previous).replace(/\$cmdList/gi, list);
|
|
||||||
return (!external) ? this.replyHandler(e, msg) : e;
|
|
||||||
}
|
|
||||||
return this.processCommand(cmd.subcommands[idx], args.slice(1), msg, previous + this.format(" " + cmd.subcommands[idx].name), external);
|
|
||||||
}
|
|
||||||
|
|
||||||
const opts = [];
|
|
||||||
const texts = [];
|
|
||||||
|
|
||||||
/** @private Collect quoted arguments spanning multiple tokens. @param {number} index @param {string} currVal @param {string[]} as @returns {{args: string[], index: number}|null} */
|
|
||||||
const collectArguments = (index, currVal, as) => {
|
|
||||||
const lastChar = currVal.charAt(currVal.length - 1);
|
|
||||||
if (lastChar === '"') return { args: as, index };
|
|
||||||
const a = args[++index];
|
|
||||||
if (!a) return null;
|
|
||||||
as.push(a);
|
|
||||||
return collectArguments(index, a, as);
|
|
||||||
};
|
|
||||||
|
|
||||||
const options = cmd.options.slice().sort((a, b) => {
|
|
||||||
const aText = (a.type === "text") ? 1 : 2;
|
|
||||||
const bText = (b.type === "text") ? 1 : 2;
|
|
||||||
return aText - bText;
|
|
||||||
});
|
|
||||||
|
|
||||||
const STRING_TYPES = ["string", "text", "channel", "voiceChannel"];
|
|
||||||
const usedOptions = [];
|
|
||||||
let usedArgumentCount = 0;
|
|
||||||
|
|
||||||
for (let i = 0, argIndex = 1; i < options.length; i++) {
|
|
||||||
const o = options[i];
|
|
||||||
if (o?.type === "text") { texts.push(o); continue; }
|
|
||||||
if ((args[argIndex] || "").startsWith("-")) {
|
|
||||||
const flagName = args[argIndex].slice(1);
|
|
||||||
const op = cmd.options.find(e => e.aliases.includes(flagName));
|
|
||||||
if (!op) {
|
|
||||||
const flagGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
|
||||||
const error = this.t(flagGuildId, "cmdHandler.invalidFlag").replace(/\$previousCmd/gi, previous).replace(/\$invalidFlag/gi, "-" + flagName);
|
|
||||||
return (!external) ? this.replyHandler(error, msg) : error;
|
|
||||||
}
|
|
||||||
previous += " " + args[argIndex];
|
|
||||||
let value = args[++argIndex];
|
|
||||||
if ((value || "").startsWith('"') && (STRING_TYPES.includes(op.type))) {
|
|
||||||
const data = collectArguments(argIndex, value, [value]);
|
|
||||||
if (!data) { const twGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; return this.replyHandler(this._textWrapErrorMsg(twGuildId, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg); }
|
|
||||||
argIndex += data.index - argIndex;
|
|
||||||
const _joined = data.args.join(" ");
|
|
||||||
value = _joined.slice(1, _joined.length - 1);
|
|
||||||
}
|
|
||||||
argIndex++;
|
|
||||||
i--;
|
|
||||||
const valid = op.validateInput(value, this.client, msg.message);
|
|
||||||
if (!valid && (op.required || !op.empty(value))) {
|
|
||||||
const errGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
|
||||||
const e = this._optionTypeError(errGuildId, op, value, previous);
|
|
||||||
return (!external) ? this.replyHandler(e, msg) : e;
|
|
||||||
}
|
|
||||||
usedArgumentCount += 2;
|
|
||||||
previous += " " + value;
|
|
||||||
opts.push({ value: op.formatInput(value, this.client, msg.message), name: op.name, id: op.id, uid: op.uid });
|
|
||||||
usedOptions.push(op.uid);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!o) continue;
|
|
||||||
if (o instanceof Flag) continue;
|
|
||||||
if (opts.findIndex(op => op.uid === o.uid) !== -1) continue;
|
|
||||||
let value = args[argIndex];
|
|
||||||
if ((args[argIndex] || "").startsWith('"') && (STRING_TYPES.includes(o.type))) {
|
|
||||||
const data = collectArguments(argIndex, args[argIndex], [args[argIndex]]);
|
|
||||||
if (!data) { const twGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId; return this.replyHandler(this._textWrapErrorMsg(twGuildId2, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg); }
|
|
||||||
argIndex += data.index - argIndex;
|
|
||||||
value = data.args.join(" ");
|
|
||||||
value = value.slice(1, value.length - 1);
|
|
||||||
}
|
|
||||||
let valid = o.validateInput(value, this.client, msg.message);
|
|
||||||
if (!valid && o.dynamicDefault) {
|
|
||||||
value = o.dynamicDefault(this.client, msg);
|
|
||||||
valid = o.validateInput(value, this.client, msg.message);
|
|
||||||
}
|
|
||||||
if (!valid && (o.required || !o.empty(value))) {
|
|
||||||
const errGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
|
||||||
const e = this._optionTypeError(errGuildId2, o, value, previous);
|
|
||||||
return (!external) ? this.replyHandler(e, msg) : e;
|
|
||||||
}
|
|
||||||
if (o.empty(value)) value = o.defaultValue;
|
|
||||||
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
|
|
||||||
usedOptions.push(o.uid);
|
|
||||||
previous += " " + value;
|
|
||||||
argIndex++;
|
|
||||||
usedArgumentCount++;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (texts.length > 0) {
|
|
||||||
let o = texts[0];
|
|
||||||
let text = args.slice(usedArgumentCount + 1).join(" ");
|
|
||||||
if (o.required && !o.validateInput(text, this.client, msg.message)) {
|
|
||||||
const textErrGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
|
||||||
let e = this._optionTypeError(textErrGuildId, o, text, previous);
|
|
||||||
return (!external) ? this.replyHandler(e, msg) : e;
|
|
||||||
}
|
|
||||||
const quote = (['"', "'"].includes(text.charAt(0))) ? text.charAt(0) : null;
|
|
||||||
if (quote && text.charAt(text.length - 1) === quote) text = text.slice(1, text.length - 1);
|
|
||||||
opts.push({ name: o.name, value: text, id: o.id, uid: o.uid });
|
|
||||||
usedOptions.push(o.uid);
|
|
||||||
}
|
|
||||||
|
|
||||||
options.filter(o => !usedOptions.includes(o.uid)).forEach(o => {
|
|
||||||
if (!o.defaultValue) return;
|
|
||||||
opts.push({ name: o.name, value: o.defaultValue, id: o.id, uid: o.uid });
|
|
||||||
});
|
|
||||||
|
|
||||||
const commandRunData = {
|
|
||||||
command: cmd,
|
|
||||||
commandId: cmd.id,
|
|
||||||
options: opts,
|
|
||||||
message: msg,
|
|
||||||
get: function (oName) { return this.options.find(o => o.name === oName); },
|
|
||||||
getById: function (id) { return this.options.find(o => o.id === id); }
|
|
||||||
};
|
|
||||||
if (!external) this.emit("run", commandRunData);
|
|
||||||
return commandRunData;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Check whether the message author meets all command requirements (owner, permissions). @param {CommandBuilder} cmd @param {Message} msg @returns {boolean} */
|
|
||||||
assertRequirements(cmd, msg) {
|
|
||||||
const authorId = msg.message?.author?.id;
|
|
||||||
const isOwner = this.owners.includes(authorId);
|
|
||||||
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
|
||||||
|
|
||||||
for (let i = 0; i < cmd.requirements.length; i++) {
|
|
||||||
let req = cmd.requirements[i];
|
|
||||||
if (req.ownerOnly && !isOwner) return false;
|
|
||||||
if (req.permissions.length > 0 && !isOwner) {
|
|
||||||
const guild = msg.message?.guild ?? null;
|
|
||||||
if (!guild) {
|
|
||||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const member = guild.members.get(authorId) ?? null;
|
|
||||||
if (member?.permissions) {
|
|
||||||
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
|
||||||
if (missing.length > 0) {
|
|
||||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const fetchPromise = typeof guild.fetchMember === "function"
|
|
||||||
? guild.fetchMember(authorId)
|
|
||||||
: typeof guild.members?.fetch === "function"
|
|
||||||
? guild.members.fetch(authorId)
|
|
||||||
: Promise.reject(new Error("No member fetch API available"));
|
|
||||||
fetchPromise.then(member => {
|
|
||||||
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
|
||||||
if (missing.length > 0) {
|
|
||||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
|
||||||
} else {
|
|
||||||
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
|
||||||
const prefix2 = this.getPrefix(guildId2);
|
|
||||||
const rawContent = msg.message.content;
|
|
||||||
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
|
||||||
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
|
||||||
this.processCommand(cmd, args, msg, false, true);
|
|
||||||
}
|
|
||||||
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Validate an input for a given option type. @param {string} type @param {*} i @param {object} m @returns {boolean} */
|
|
||||||
validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); }
|
|
||||||
/** Format an input for a given option type. @param {string} type @param {*} i @param {object} m @returns {*} */
|
|
||||||
formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); }
|
|
||||||
|
|
||||||
/** @private Build a type-error message for an option. @param {string} guildId @param {Option} option @param {*} value @param {string} previous @returns {string} */
|
|
||||||
_optionTypeError(guildId, option, value, previous) {
|
|
||||||
if (option.tError) {
|
|
||||||
return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
|
|
||||||
}
|
|
||||||
const localeKey = option.type === 'choice' ? 'cmdBuilder.option.invalidChoice'
|
|
||||||
: (option.type === 'channel' || option.type === 'voiceChannel') ? 'cmdBuilder.option.invalidChannel'
|
|
||||||
: 'cmdBuilder.option.invalidType';
|
|
||||||
const choiceStr = option.type === 'choice'
|
|
||||||
? (option.choices.length > Option.THRESHOLD ? Option.formatChoicesCompact(option.choices) : option.choices.map(c => '- ' + c).join('\n'))
|
|
||||||
: '';
|
|
||||||
return this.t(guildId, localeKey, {
|
|
||||||
$currValue: value,
|
|
||||||
$optionName: option.name,
|
|
||||||
$type: option.type,
|
|
||||||
$choices: choiceStr
|
|
||||||
}).replace(/\$previousCmd/gi, previous);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @private Build a text-wrap error message. @param {string} guildId @param {string} value @param {string} quote @returns {string} */
|
|
||||||
_textWrapErrorMsg(guildId, value, quote) {
|
|
||||||
return this.t(guildId, 'cmdHandler.textWrapError', { $value: value, $quote: quote });
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Register a command builder and sort the command list alphabetically. @param {CommandBuilder} builder @returns {CommandBuilder[]} */
|
|
||||||
addCommand(builder) {
|
|
||||||
this.commandNames.push(...builder.aliases);
|
|
||||||
this.commands.push(builder);
|
|
||||||
this.commands.sort((a, b) => {
|
|
||||||
let A = a.name.toUpperCase();
|
|
||||||
let B = b.name.toUpperCase();
|
|
||||||
return (A < B) ? -1 : (A > B) ? 1 : 0;
|
|
||||||
});
|
|
||||||
return this.commands;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @class CommandLoader @description Dynamically loads command files from a directory, registers builders, and binds run handlers. */
|
|
||||||
export class CommandLoader {
|
|
||||||
/** @type {CommandHandler} Reference to the command handler. */
|
|
||||||
commands;
|
|
||||||
/** @type {Map<string, string>} Command UID → file path. */
|
|
||||||
commandFiles = new Map();
|
|
||||||
/** @type {Map<string, Function>} Command UID → run function. */
|
|
||||||
runnables = new Map();
|
|
||||||
/** @type {object} Shared context (the bot instance). */
|
|
||||||
context;
|
|
||||||
|
|
||||||
/** @param {CommandHandler} commands @param {object} context - Bot context object. */
|
|
||||||
constructor(commands, context) {
|
|
||||||
this.commands = commands;
|
|
||||||
this.context = context;
|
|
||||||
this.context.loader ??= this;
|
|
||||||
this.context.commandFiles = this.commandFiles;
|
|
||||||
this.context.runnables = this.runnables;
|
|
||||||
|
|
||||||
this.commands.on("run", (data) => {
|
|
||||||
if (!this.runnables.has(data.command.uid)) return;
|
|
||||||
const runFc = this.runnables.get(data.command.uid);
|
|
||||||
const sendErrorReply = (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));
|
|
||||||
};
|
|
||||||
try {
|
|
||||||
const result = runFc.call(this.context, data.message, data);
|
|
||||||
if (result && typeof result.catch === "function") {
|
|
||||||
result.catch(e => {
|
|
||||||
const id = Utils.uid();
|
|
||||||
logger.error("Error running command; error id #" + id, e);
|
|
||||||
sendErrorReply(id);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
const id = Utils.uid();
|
|
||||||
logger.error("Error running command; error id #" + id, e);
|
|
||||||
sendErrorReply(id);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Normalize a module export to { command, run, exportDef }. @param {object} cData @returns {object} */
|
|
||||||
canonData(cData) {
|
|
||||||
if (cData.command !== undefined) {
|
|
||||||
return {
|
|
||||||
command: cData.command,
|
|
||||||
run: cData.run,
|
|
||||||
exportDef: cData.exportDef ?? cData.export ?? null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const d = cData.default ?? cData;
|
|
||||||
return {
|
|
||||||
command: d.command,
|
|
||||||
run: d.run,
|
|
||||||
exportDef: d.exportDef ?? d.export ?? null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @async Load all command files from a directory. @param {string} dir @returns {Promise<undefined[]>} */
|
|
||||||
loadFromDir(dir) {
|
|
||||||
const files = fs.readdirSync(dir)
|
|
||||||
.filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs")));
|
|
||||||
|
|
||||||
return Promise.all(files.map(async commandFile => {
|
|
||||||
const file = path.join(dir, commandFile);
|
|
||||||
|
|
||||||
const cData = this.canonData(await import(pathToFileURL(file).href));
|
|
||||||
|
|
||||||
const builder = (typeof cData.command === "function")
|
|
||||||
? cData.command.call(this.context)
|
|
||||||
: cData.command;
|
|
||||||
|
|
||||||
if (!builder) return logger.warn("No builder returned. Skipping '" + commandFile + "'");
|
|
||||||
|
|
||||||
if (cData.exportDef)
|
|
||||||
this.context[cData.exportDef.name] = cData.exportDef.object;
|
|
||||||
|
|
||||||
this.commands.addCommand(builder);
|
|
||||||
this.commandFiles.set(builder.uid, file);
|
|
||||||
|
|
||||||
if (!cData.run) return;
|
|
||||||
|
|
||||||
this.runnables.set(builder.uid, cData.run);
|
|
||||||
builder.subcommands.forEach(sub => {
|
|
||||||
this.runnables.set(sub.uid, cData.run);
|
|
||||||
});
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,879 +0,0 @@
|
|||||||
/** @module src/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. Supports MP3/AAC/radio streams via Lavalink resolve-through. */
|
|
||||||
|
|
||||||
import { logger } from "./constants/Logger.mjs";
|
|
||||||
import { WebMOpusMuxer, OPUS_FRAME_MS } from "./constants/audio/WebMOpusMuxer.mjs";
|
|
||||||
import { EventEmitter } from "node:events";
|
|
||||||
import { Readable } from "node:stream";
|
|
||||||
import http from "node:http";
|
|
||||||
import https from "node:https";
|
|
||||||
import prismMedia from "prism-media";
|
|
||||||
|
|
||||||
const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus;
|
|
||||||
|
|
||||||
/** @type {number} @description Maximum number of HTTP redirect hops to follow. */
|
|
||||||
const MAX_REDIRECTS = 5;
|
|
||||||
|
|
||||||
/** @type {number} @description Timeout (ms) for HTTP requests to Lavalink REST endpoints (trackstream, loadtracks JSON). */
|
|
||||||
const REST_REQUEST_TIMEOUT_MS = 15_000;
|
|
||||||
|
|
||||||
/** @type {number} @description Timeout (ms) to wait for the first byte from loadstream (Lavalink may need time to resolve HLS/external streams). */
|
|
||||||
const LOADSTREAM_CONNECT_TIMEOUT_MS = 60_000;
|
|
||||||
|
|
||||||
/** @type {number} @description Idle timeout (ms) once loadstream data is flowing — if no data arrives for this long, abort. */
|
|
||||||
const LOADSTREAM_IDLE_TIMEOUT_MS = 30_000;
|
|
||||||
|
|
||||||
/** @type {number} @description PCM sample rate expected from NodeLink loadstream (48kHz stereo s16le). */
|
|
||||||
const PCM_RATE = 48000;
|
|
||||||
/** @type {number} @description PCM channel count expected from NodeLink loadstream. */
|
|
||||||
const PCM_CHANNELS = 2;
|
|
||||||
/** @type {number} @description Opus frame size in samples per channel (20ms @ 48kHz). */
|
|
||||||
const PCM_FRAME_SIZE = 960;
|
|
||||||
/** @type {number} @description Opus encoding bitrate. */
|
|
||||||
const OPUS_BITRATE = 128000;
|
|
||||||
|
|
||||||
/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */
|
|
||||||
const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
|
|
||||||
/** @type {Buffer} @description OGG container magic bytes ("OggS"). */
|
|
||||||
const OGG_MAGIC = Buffer.from("OggS", "ascii");
|
|
||||||
|
|
||||||
/** @type {number} @description livekit TrackKind.KIND_AUDIO — publications with this kind are managed by the bridge. */
|
|
||||||
const TRACK_KIND_AUDIO = 1;
|
|
||||||
|
|
||||||
/** @extends {EventEmitter} */
|
|
||||||
export class FluxerAudioBridge extends EventEmitter {
|
|
||||||
_conn = null;
|
|
||||||
_stream = null;
|
|
||||||
_encoder = null;
|
|
||||||
_sourceStream = null;
|
|
||||||
_sourceReq = null;
|
|
||||||
_playing = false;
|
|
||||||
_stopped = false;
|
|
||||||
_startedAt = 0;
|
|
||||||
_currentUri = null;
|
|
||||||
_lavalink = null;
|
|
||||||
_playGeneration = 0;
|
|
||||||
_durationTimer = null;
|
|
||||||
_endResolve = null;
|
|
||||||
_endReject = null;
|
|
||||||
_usedTrackstream = false;
|
|
||||||
|
|
||||||
/** @type {boolean} @description Whether audio is currently playing. */
|
|
||||||
get playing() { return this._playing; }
|
|
||||||
/** @type {number} @description Timestamp (ms) when playback started. */
|
|
||||||
get startedAt() { return this._startedAt; }
|
|
||||||
/** @type {string|null} @description URI of the currently playing track. */
|
|
||||||
get currentUri() { return this._currentUri; }
|
|
||||||
|
|
||||||
/** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */
|
|
||||||
constructor(lavalinkManager = null) {
|
|
||||||
super();
|
|
||||||
this._lavalink = lavalinkManager;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Play a track through a Fluxer voice connection, entirely in-process.
|
|
||||||
* Routing order:
|
|
||||||
* 1. trackstream passthrough (seek=0, no filters) — NodeLink hands back a WebM/Opus
|
|
||||||
* direct URL which the voice connection plays natively (zero re-encode).
|
|
||||||
* 2. loadstream — NodeLink returns raw PCM (48k stereo s16le) with server-side
|
|
||||||
* seek/filters; PCM is Opus-encoded in-process and muxed to WebM.
|
|
||||||
* 3. direct URL fallback — magic-byte sniff: WebM passthrough or Ogg/Opus remux.
|
|
||||||
* @param {object} conn - Fluxer voice connection
|
|
||||||
* @param {object} trackInfo - Track metadata (encoded, title, url, guildId)
|
|
||||||
* @param {object} [options]
|
|
||||||
* @param {number} [options.seekSeconds=0]
|
|
||||||
* @param {number} [options.durationMs=0]
|
|
||||||
* @param {object} [options.filterPayload]
|
|
||||||
* @returns {Promise<"finished"|"stopped">}
|
|
||||||
*/
|
|
||||||
async play(conn, trackInfo, options = {}) {
|
|
||||||
this.stop();
|
|
||||||
if (!conn) throw new Error("[AudioBridge] No voice connection provided");
|
|
||||||
|
|
||||||
this._unpublishStaleAudioTracks(conn);
|
|
||||||
|
|
||||||
const generation = ++this._playGeneration;
|
|
||||||
this._conn = conn;
|
|
||||||
this._playing = true;
|
|
||||||
this._stopped = false;
|
|
||||||
this._startedAt = Date.now();
|
|
||||||
this._currentUri = trackInfo?.url ?? trackInfo?.title ?? "unknown";
|
|
||||||
this._usedTrackstream = false;
|
|
||||||
|
|
||||||
const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000);
|
|
||||||
let durationMs = options.durationMs || 0;
|
|
||||||
|
|
||||||
try {
|
|
||||||
if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) {
|
|
||||||
try {
|
|
||||||
const direct = await this._getTrackstreamUrl(trackInfo);
|
|
||||||
if (direct?.url && /webm|opus/i.test(direct.format || "")) {
|
|
||||||
this._usedTrackstream = true;
|
|
||||||
logger.player("[AudioBridge] Passthrough webm/opus via trackstream (zero-copy): " + (trackInfo.title || "unknown"));
|
|
||||||
|
|
||||||
await conn.play(direct.url);
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
if (durationMs > 0) await this._waitDuration(durationMs);
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
if (this._playing && !this._stopped) {
|
|
||||||
this._playing = false;
|
|
||||||
logger.player("[AudioBridge] Track finished naturally (trackstream passthrough)");
|
|
||||||
return "finished";
|
|
||||||
}
|
|
||||||
return "stopped";
|
|
||||||
}
|
|
||||||
if (direct?.url && this._lavalink && trackInfo.url && trackInfo.url.startsWith("http")) {
|
|
||||||
logger.player("[AudioBridge] trackstream format " + (direct.format || "?") + " — resolving original source URL via Lavalink for fresh encoded track...");
|
|
||||||
const freshEncoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
|
|
||||||
if (freshEncoded) {
|
|
||||||
trackInfo.encoded = freshEncoded;
|
|
||||||
logger.player("[AudioBridge] Fresh encoded track obtained — retrying trackstream for webm/opus...");
|
|
||||||
try {
|
|
||||||
const freshDirect = await this._getTrackstreamUrl(trackInfo);
|
|
||||||
if (freshDirect?.url && /webm|opus/i.test(freshDirect.format || "")) {
|
|
||||||
this._usedTrackstream = true;
|
|
||||||
logger.player("[AudioBridge] Fresh trackstream is webm/opus — zero-copy passthrough: " + (trackInfo.title || "unknown"));
|
|
||||||
await conn.play(freshDirect.url);
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
if (durationMs > 0) await this._waitDuration(durationMs);
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
if (this._playing && !this._stopped) {
|
|
||||||
this._playing = false;
|
|
||||||
logger.player("[AudioBridge] Track finished naturally (fresh trackstream passthrough)");
|
|
||||||
return "finished";
|
|
||||||
}
|
|
||||||
return "stopped";
|
|
||||||
}
|
|
||||||
logger.player("[AudioBridge] Fresh trackstream also " + (freshDirect?.format || "?") + ", falling through to loadstream");
|
|
||||||
} catch (e2) {
|
|
||||||
logger.player("[AudioBridge] Fresh trackstream failed, falling through to loadstream: " + e2.message);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
logger.player("[AudioBridge] Could not resolve source URL via Lavalink, using original encoded track for loadstream");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), falling through to loadstream");
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message);
|
|
||||||
this._playing = true;
|
|
||||||
this._stopped = false;
|
|
||||||
this._startedAt = Date.now();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (trackInfo.encoded && this._lavalink) {
|
|
||||||
const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload);
|
|
||||||
if (generation !== this._playGeneration) {
|
|
||||||
loaded.stream.destroy();
|
|
||||||
return "stopped";
|
|
||||||
}
|
|
||||||
|
|
||||||
const routed = await this._routeByMagic(loaded.stream);
|
|
||||||
this._sourceStream = loaded.stream;
|
|
||||||
this._sourceReq = loaded.req || null;
|
|
||||||
|
|
||||||
if (routed.kind === "webm") {
|
|
||||||
logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") +
|
|
||||||
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : ""));
|
|
||||||
this._stream = routed.stream;
|
|
||||||
await conn.play(routed.stream);
|
|
||||||
} else if (routed.kind === "ogg") {
|
|
||||||
logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown"));
|
|
||||||
const oggResult = await this._remuxOggToWebM(routed.stream);
|
|
||||||
this._stream = oggResult;
|
|
||||||
if (durationMs <= 0) durationMs = oggResult.getDurationMs();
|
|
||||||
await conn.play(this._stream);
|
|
||||||
} else {
|
|
||||||
logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") +
|
|
||||||
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") +
|
|
||||||
(options.filterPayload ? " [filters]" : ""));
|
|
||||||
this._stream = this._buildPcmPipeline(routed.stream);
|
|
||||||
await conn.play(this._stream);
|
|
||||||
}
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
await this._awaitEnd(durationMs);
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
if (this._playing && !this._stopped) {
|
|
||||||
this._playing = false;
|
|
||||||
logger.player("[AudioBridge] Track finished naturally (loadstream)");
|
|
||||||
return "finished";
|
|
||||||
}
|
|
||||||
return "stopped";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (trackInfo.url && trackInfo.url.startsWith("http")) {
|
|
||||||
logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "...");
|
|
||||||
const response = await fetch(trackInfo.url, {
|
|
||||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
|
|
||||||
redirect: "follow",
|
|
||||||
});
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error("HTTP " + response.status + " for " + trackInfo.url);
|
|
||||||
}
|
|
||||||
const stream = Readable.fromWeb(response.body);
|
|
||||||
this._sourceStream = stream;
|
|
||||||
|
|
||||||
const routed = await this._routeByMagic(stream);
|
|
||||||
if (routed.kind === "webm") {
|
|
||||||
logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown"));
|
|
||||||
this._stream = routed.stream;
|
|
||||||
await conn.play(routed.stream);
|
|
||||||
} else if (routed.kind === "ogg") {
|
|
||||||
logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown"));
|
|
||||||
const oggResult = await this._remuxOggToWebM(routed.stream);
|
|
||||||
this._stream = oggResult;
|
|
||||||
await conn.play(this._stream);
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
await new Promise(r => {
|
|
||||||
if (this._stream.readableEnded) return r();
|
|
||||||
const done = () => { this._stream.off("end", done); this._stream.off("close", done); r(); };
|
|
||||||
this._stream.once("end", done);
|
|
||||||
this._stream.once("close", done);
|
|
||||||
});
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
const fullDurationMs = oggResult.getDurationMs();
|
|
||||||
const elapsedMs = Date.now() - this._startedAt;
|
|
||||||
const remainingMs = Math.max(0, fullDurationMs - elapsedMs);
|
|
||||||
logger.player("[AudioBridge] Route 3b: OGG " + fullDurationMs + "ms total, " + elapsedMs + "ms elapsed, waiting " + remainingMs + "ms more");
|
|
||||||
|
|
||||||
if (remainingMs > 0) await this._awaitEnd(remainingMs);
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
if (this._playing && !this._stopped) {
|
|
||||||
this._playing = false;
|
|
||||||
logger.player("[AudioBridge] Track finished naturally (direct URL, OGG remux)");
|
|
||||||
return "finished";
|
|
||||||
}
|
|
||||||
return "stopped";
|
|
||||||
} else {
|
|
||||||
stream.destroy();
|
|
||||||
this._sourceStream = null;
|
|
||||||
logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink...");
|
|
||||||
|
|
||||||
if (this._lavalink) {
|
|
||||||
const encoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
|
|
||||||
if (encoded) {
|
|
||||||
trackInfo.encoded = encoded;
|
|
||||||
logger.player("[AudioBridge] Route 3c: Got encoded track from Lavalink, retrying via loadstream...");
|
|
||||||
const loaded = await this._streamFromLoadstream(trackInfo, 0, null);
|
|
||||||
if (generation !== this._playGeneration) {
|
|
||||||
loaded.stream.destroy();
|
|
||||||
return "stopped";
|
|
||||||
}
|
|
||||||
|
|
||||||
const routed2 = await this._routeByMagic(loaded.stream);
|
|
||||||
this._sourceStream = loaded.stream;
|
|
||||||
this._sourceReq = loaded.req || null;
|
|
||||||
|
|
||||||
if (routed2.kind === "webm") {
|
|
||||||
logger.player("[AudioBridge] Route 3c (Lavalink): webm/opus passthrough");
|
|
||||||
this._stream = routed2.stream;
|
|
||||||
await conn.play(routed2.stream);
|
|
||||||
} else if (routed2.kind === "ogg") {
|
|
||||||
logger.player("[AudioBridge] Route 3c (Lavalink): ogg/opus remux to webm");
|
|
||||||
const oggResult3c = await this._remuxOggToWebM(routed2.stream);
|
|
||||||
this._stream = oggResult3c;
|
|
||||||
if (durationMs <= 0) durationMs = oggResult3c.getDurationMs();
|
|
||||||
await conn.play(this._stream);
|
|
||||||
} else {
|
|
||||||
logger.player("[AudioBridge] Route 3c (Lavalink): PCM -> Opus -> WebM");
|
|
||||||
this._stream = this._buildPcmPipeline(routed2.stream);
|
|
||||||
await conn.play(this._stream);
|
|
||||||
}
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
await this._awaitEnd(durationMs);
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
if (this._playing && !this._stopped) {
|
|
||||||
this._playing = false;
|
|
||||||
logger.player("[AudioBridge] Track finished naturally (Route 3c Lavalink resolve)");
|
|
||||||
return "finished";
|
|
||||||
}
|
|
||||||
return "stopped";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error(
|
|
||||||
"[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " +
|
|
||||||
"Lavalink resolve also failed or is unavailable. " +
|
|
||||||
"Make sure your Lavalink/NodeLink node is running and can decode this stream format."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
await this._awaitEnd(durationMs);
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
|
|
||||||
if (this._playing && !this._stopped) {
|
|
||||||
this._playing = false;
|
|
||||||
logger.player("[AudioBridge] Track finished naturally (direct URL)");
|
|
||||||
return "finished";
|
|
||||||
}
|
|
||||||
return "stopped";
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new Error("Could not get audio stream for: " + (trackInfo.title || trackInfo.url || "unknown"));
|
|
||||||
|
|
||||||
} catch (e) {
|
|
||||||
if (generation !== this._playGeneration) return "stopped";
|
|
||||||
if (this._stopped || !this._playing) return "stopped";
|
|
||||||
this._playing = false;
|
|
||||||
logger.error("[AudioBridge] Playback error: " + e.message);
|
|
||||||
throw e;
|
|
||||||
} finally {
|
|
||||||
this._cleanup();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wait for playback end: duration timer for fixed-length tracks, pipeline
|
|
||||||
* end event for live/radio streams (durationMs = 0). Rejects early on
|
|
||||||
* pipeline errors so the player can skip to the next track.
|
|
||||||
* @param {number} durationMs
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_awaitEnd(durationMs) { return new Promise((resolve, reject) => {
|
|
||||||
this._endResolve = resolve;
|
|
||||||
this._endReject = reject;
|
|
||||||
const failFast = (err) => {
|
|
||||||
if (this._playing && !this._stopped) {
|
|
||||||
this._playing = false;
|
|
||||||
reject(err);
|
|
||||||
} else {
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if (durationMs > 0) {
|
|
||||||
this._durationTimer = setTimeout(resolve, durationMs);
|
|
||||||
} else {
|
|
||||||
const stream = this._stream;
|
|
||||||
if (!stream) return resolve();
|
|
||||||
const onEnd = () => resolve();
|
|
||||||
stream.once("end", onEnd);
|
|
||||||
stream.once("close", onEnd);
|
|
||||||
stream.once("error", failFast);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this._sourceStream) {
|
|
||||||
this._sourceStream.once("error", failFast);
|
|
||||||
}
|
|
||||||
if (this._encoder) {
|
|
||||||
this._encoder.once("error", failFast);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Simple timed wait used by the trackstream passthrough route (no local
|
|
||||||
* pipeline to watch). Resolves early if stopped.
|
|
||||||
* @param {number} durationMs
|
|
||||||
* @returns {Promise<void>}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_waitDuration(durationMs) {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
this._durationTimer = null;
|
|
||||||
resolve();
|
|
||||||
}, durationMs);
|
|
||||||
this._durationTimer = timer;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Peek at the first bytes of a stream and classify it, pushing the peeked
|
|
||||||
* bytes back so nothing is lost.
|
|
||||||
* @param {Readable} stream
|
|
||||||
* @returns {Promise<{stream: Readable, kind: "webm"|"ogg"|"pcm"}>}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
async _routeByMagic(stream) {
|
|
||||||
const head = await this._peek(stream, 4);
|
|
||||||
if (head.length >= 4 && head.subarray(0, 4).equals(WEBM_MAGIC)) return { stream, kind: "webm" };
|
|
||||||
if (head.length >= 4 && head.subarray(0, 4).equals(OGG_MAGIC)) return { stream, kind: "ogg" };
|
|
||||||
return { stream, kind: "pcm" };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Read up to `n` bytes from a paused-mode stream, then unshift them.
|
|
||||||
* @param {Readable} stream
|
|
||||||
* @param {number} n
|
|
||||||
* @returns {Promise<Buffer>}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_peek(stream, n) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const tryRead = () => {
|
|
||||||
const chunks = [];
|
|
||||||
let total = 0;
|
|
||||||
let chunk;
|
|
||||||
while (total < n && (chunk = stream.read()) !== null) {
|
|
||||||
chunks.push(chunk);
|
|
||||||
total += chunk.length;
|
|
||||||
}
|
|
||||||
if (total >= n || stream.readableEnded) {
|
|
||||||
const buf = Buffer.concat(chunks);
|
|
||||||
cleanup();
|
|
||||||
if (buf.length > 0) stream.unshift(buf);
|
|
||||||
resolve(buf.subarray(0, n));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
const onReadable = () => { cleanup(); tryRead(); };
|
|
||||||
const onEnd = () => { cleanup(); tryRead(); };
|
|
||||||
const onError = (err) => { cleanup(); reject(err); };
|
|
||||||
const cleanup = () => {
|
|
||||||
stream.off("readable", onReadable);
|
|
||||||
stream.off("end", onEnd);
|
|
||||||
stream.off("error", onError);
|
|
||||||
};
|
|
||||||
stream.once("readable", onReadable);
|
|
||||||
stream.once("end", onEnd);
|
|
||||||
stream.once("error", onError);
|
|
||||||
tryRead();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Build the in-process PCM -> Opus -> WebM pipeline.
|
|
||||||
* @param {Readable} pcmStream - s16le 48kHz stereo byte stream
|
|
||||||
* @returns {WebMOpusMuxer} - byte stream consumable by conn.play()
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_buildPcmPipeline(pcmStream) {
|
|
||||||
let encoder;
|
|
||||||
try {
|
|
||||||
encoder = new PrismOpusEncoder({
|
|
||||||
rate: PCM_RATE,
|
|
||||||
channels: PCM_CHANNELS,
|
|
||||||
frameSize: PCM_FRAME_SIZE,
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
pcmStream.destroy();
|
|
||||||
throw new Error(
|
|
||||||
"No Opus encoder available (" + e.message + "). Install one: npm install @discordjs/opus (or opusscript)"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
try { encoder.setBitrate(OPUS_BITRATE); } catch (_) {}
|
|
||||||
|
|
||||||
const muxer = new WebMOpusMuxer({ sampleRate: PCM_RATE, channels: PCM_CHANNELS });
|
|
||||||
this._encoder = encoder;
|
|
||||||
|
|
||||||
pcmStream.on("error", (err) => {
|
|
||||||
logger.warn("[AudioBridge] PCM source error: " + err.message);
|
|
||||||
encoder.destroy(err);
|
|
||||||
});
|
|
||||||
encoder.on("error", (err) => {
|
|
||||||
muxer.destroy(err);
|
|
||||||
});
|
|
||||||
|
|
||||||
pcmStream.pipe(encoder).pipe(muxer);
|
|
||||||
return muxer;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remux an Ogg/Opus stream into WebM/Opus (packet-level, no re-encode).
|
|
||||||
* @param {Readable} oggStream
|
|
||||||
* @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
async _remuxOggToWebM(oggStream) {
|
|
||||||
const demuxer = new PrismOggDemuxer();
|
|
||||||
const muxer = new WebMOpusMuxer();
|
|
||||||
oggStream.on("error", (err) => demuxer.destroy(err));
|
|
||||||
demuxer.on("error", (err) => muxer.destroy(err));
|
|
||||||
let frameCount = 0;
|
|
||||||
demuxer.on("data", () => { frameCount++; });
|
|
||||||
const headPromise = new Promise((resolve, reject) => {
|
|
||||||
demuxer.once("head", () => resolve());
|
|
||||||
demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message)));
|
|
||||||
oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message)));
|
|
||||||
});
|
|
||||||
oggStream.pipe(demuxer).pipe(muxer);
|
|
||||||
await headPromise;
|
|
||||||
const wrapper = Object.create(muxer);
|
|
||||||
wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS;
|
|
||||||
return wrapper;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {object} trackInfo
|
|
||||||
* @returns {Promise<{url: string, format: string}>}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
async _getTrackstreamUrl(trackInfo) {
|
|
||||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
|
||||||
if (!nlInfo) throw new Error("NodeLink info not available");
|
|
||||||
|
|
||||||
const protocol = nlInfo.secure ? "https" : "http";
|
|
||||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
|
||||||
|
|
||||||
const headers = { "Authorization": nlInfo.password };
|
|
||||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
|
||||||
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
|
|
||||||
|
|
||||||
const params = "encodedTrack=" + encodeURIComponent(trackInfo.encoded);
|
|
||||||
const url = baseUrl + "/v4/trackstream?" + params;
|
|
||||||
|
|
||||||
logger.player("[AudioBridge] Querying /v4/trackstream...");
|
|
||||||
|
|
||||||
const body = await this._httpGetJson(url, headers);
|
|
||||||
|
|
||||||
const directUrl = body?.url;
|
|
||||||
if (!directUrl || typeof directUrl !== "string") {
|
|
||||||
throw new Error("trackstream returned no URL");
|
|
||||||
}
|
|
||||||
|
|
||||||
const format = body?.format || "";
|
|
||||||
logger.player("[AudioBridge] trackstream: format=" + format + " url=" + directUrl.substring(0, 100) + "...");
|
|
||||||
|
|
||||||
return { url: directUrl, format };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {object} trackInfo
|
|
||||||
* @param {number} [seekMs=0]
|
|
||||||
* @param {object|null} [filterPayload]
|
|
||||||
* @returns {Promise<{stream: Readable, inputFormat: string|null}>}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
async _streamFromLoadstream(trackInfo, seekMs = 0, filterPayload = null) {
|
|
||||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
|
||||||
if (!nlInfo) {
|
|
||||||
throw new Error("NodeLink info not available");
|
|
||||||
}
|
|
||||||
|
|
||||||
const protocol = nlInfo.secure ? "https" : "http";
|
|
||||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
|
||||||
|
|
||||||
const headers = { "Authorization": nlInfo.password };
|
|
||||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
|
||||||
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
|
|
||||||
|
|
||||||
let baseParams = "encodedTrack=" + encodeURIComponent(trackInfo.encoded) + "&position=" + seekMs + "&volume=100";
|
|
||||||
if (filterPayload) {
|
|
||||||
baseParams += "&filters=" + encodeURIComponent(JSON.stringify(filterPayload));
|
|
||||||
}
|
|
||||||
|
|
||||||
const url = baseUrl + "/v4/loadstream?" + baseParams;
|
|
||||||
logger.player("[AudioBridge] Querying /v4/loadstream (seek: " + seekMs + "ms)...");
|
|
||||||
|
|
||||||
return this._httpRequestStream(url, headers);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve a direct audio URL through Lavalink's /v4/loadtracks to get an encoded track.
|
|
||||||
* This allows MP3/AAC radio streams and direct audio URLs to be played through
|
|
||||||
* the loadstream pipeline without any FFmpeg dependency.
|
|
||||||
* @param {string} url - The HTTP(S) audio stream URL to resolve.
|
|
||||||
* @param {string} [guildId] - Optional guild ID for the request.
|
|
||||||
* @returns {Promise<string|null>} The encoded track string, or null if resolution failed.
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
async _resolveUrlViaLavalink(url, guildId) {
|
|
||||||
try {
|
|
||||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
|
||||||
if (!nlInfo) {
|
|
||||||
logger.warn("[AudioBridge] _resolveUrlViaLavalink: no NodeLink info");
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const protocol = nlInfo.secure ? "https" : "http";
|
|
||||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
|
||||||
|
|
||||||
const headers = { "Authorization": nlInfo.password };
|
|
||||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
|
||||||
if (guildId) headers["Guild-Id"] = guildId;
|
|
||||||
|
|
||||||
const params = "identifier=" + encodeURIComponent(url);
|
|
||||||
const loadtracksUrl = baseUrl + "/v4/loadtracks?" + params;
|
|
||||||
|
|
||||||
logger.player("[AudioBridge] Resolving URL via Lavalink /v4/loadtracks: " + url.substring(0, 80) + "...");
|
|
||||||
|
|
||||||
const body = await this._httpGetJson(loadtracksUrl, headers, 0, 30_000);
|
|
||||||
|
|
||||||
const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data;
|
|
||||||
const encoded = track?.encoded ?? track?.data;
|
|
||||||
|
|
||||||
if (encoded && typeof encoded === "string") {
|
|
||||||
logger.player("[AudioBridge] Lavalink resolved URL to encoded track successfully");
|
|
||||||
return encoded;
|
|
||||||
}
|
|
||||||
|
|
||||||
const loadType = body?.loadType ?? body?.data?.loadType;
|
|
||||||
logger.warn("[AudioBridge] Lavalink loadtracks returned no playable track (loadType=" + loadType + ")");
|
|
||||||
return null;
|
|
||||||
} catch (e) {
|
|
||||||
logger.warn("[AudioBridge] _resolveUrlViaLavalink failed: " + e.message);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} url
|
|
||||||
* @param {object} [headers]
|
|
||||||
* @returns {Promise<object>}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_httpGetJson(url, headers = {}, _redirectCount = 0, timeoutMs = REST_REQUEST_TIMEOUT_MS) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
if (_redirectCount >= MAX_REDIRECTS) {
|
|
||||||
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
|
|
||||||
}
|
|
||||||
const urlObj = new URL(url);
|
|
||||||
const client = urlObj.protocol === "https:" ? https : http;
|
|
||||||
|
|
||||||
const req = client.request({
|
|
||||||
protocol: urlObj.protocol,
|
|
||||||
host: urlObj.hostname,
|
|
||||||
port: urlObj.port,
|
|
||||||
path: urlObj.pathname + urlObj.search,
|
|
||||||
method: "GET",
|
|
||||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
|
|
||||||
}, (res) => {
|
|
||||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
||||||
res.resume();
|
|
||||||
let loc = res.headers.location;
|
|
||||||
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
|
|
||||||
return this._httpGetJson(loc, headers, _redirectCount + 1, timeoutMs).then(resolve, reject);
|
|
||||||
}
|
|
||||||
if (res.statusCode !== 200) {
|
|
||||||
let body = "";
|
|
||||||
res.on("data", (chunk) => { body += chunk; });
|
|
||||||
res.on("end", () => {
|
|
||||||
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let data = "";
|
|
||||||
res.on("data", (chunk) => { data += chunk; });
|
|
||||||
res.on("end", () => {
|
|
||||||
try {
|
|
||||||
resolve(JSON.parse(data));
|
|
||||||
} catch (e) {
|
|
||||||
reject(new Error("Invalid JSON from trackstream: " + data.substring(0, 200)));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
req.on("socket", (socket) => {
|
|
||||||
socket.on("error", () => {});
|
|
||||||
});
|
|
||||||
req.on("error", reject);
|
|
||||||
req.setTimeout(timeoutMs, () => {
|
|
||||||
req.destroy();
|
|
||||||
reject(new Error("REST request timeout (" + timeoutMs / 1000 + "s)"));
|
|
||||||
});
|
|
||||||
req.end();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} url
|
|
||||||
* @param {object} [headers]
|
|
||||||
* @param {number} [_redirectCount=0]
|
|
||||||
* @returns {Promise<{stream: Readable, inputFormat: string|null, req: http.ClientRequest}>}
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_httpRequestStream(url, headers = {}, _redirectCount = 0) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
if (_redirectCount >= MAX_REDIRECTS) {
|
|
||||||
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
|
|
||||||
}
|
|
||||||
|
|
||||||
const urlObj = new URL(url);
|
|
||||||
const client = urlObj.protocol === "https:" ? https : http;
|
|
||||||
let firstByte = true;
|
|
||||||
let connectTimer = null;
|
|
||||||
let idleTimer = null;
|
|
||||||
|
|
||||||
const resetIdleTimeout = () => {
|
|
||||||
if (idleTimer) clearTimeout(idleTimer);
|
|
||||||
idleTimer = setTimeout(() => {
|
|
||||||
req.destroy();
|
|
||||||
reject(new Error("loadstream idle timeout (" + LOADSTREAM_IDLE_TIMEOUT_MS / 1000 + "s no data)"));
|
|
||||||
}, LOADSTREAM_IDLE_TIMEOUT_MS);
|
|
||||||
idleTimer.unref?.();
|
|
||||||
};
|
|
||||||
|
|
||||||
const req = client.request({
|
|
||||||
protocol: urlObj.protocol,
|
|
||||||
host: urlObj.hostname,
|
|
||||||
port: urlObj.port,
|
|
||||||
path: urlObj.pathname + urlObj.search,
|
|
||||||
method: "GET",
|
|
||||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
|
|
||||||
}, (res) => {
|
|
||||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
|
||||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
|
||||||
res.resume();
|
|
||||||
let nextHeaders = headers;
|
|
||||||
let loc = res.headers.location;
|
|
||||||
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
|
|
||||||
try {
|
|
||||||
const redirectHost = new URL(loc).hostname;
|
|
||||||
if (redirectHost !== urlObj.hostname) {
|
|
||||||
const { Authorization, "Session-Id": _, ...safe } = headers;
|
|
||||||
nextHeaders = safe;
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
return this._httpRequestStream(loc, nextHeaders, _redirectCount + 1).then(resolve, reject);
|
|
||||||
}
|
|
||||||
if (res.statusCode !== 200) {
|
|
||||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
|
||||||
let body = "";
|
|
||||||
res.on("data", (chunk) => { body += chunk; });
|
|
||||||
res.on("end", () => {
|
|
||||||
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
|
||||||
resetIdleTimeout();
|
|
||||||
res.once("data", () => resetIdleTimeout());
|
|
||||||
|
|
||||||
logger.player("[AudioBridge] loadstream response: " + res.statusCode + " content-type=" + (res.headers["content-type"] || "?"));
|
|
||||||
resolve({ stream: res, inputFormat: res.headers["content-type"] || null, req });
|
|
||||||
});
|
|
||||||
|
|
||||||
req.on("socket", (socket) => {
|
|
||||||
socket.on("error", () => {});
|
|
||||||
});
|
|
||||||
|
|
||||||
req.on("error", (err) => {
|
|
||||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
|
||||||
if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; }
|
|
||||||
reject(err);
|
|
||||||
});
|
|
||||||
|
|
||||||
connectTimer = setTimeout(() => {
|
|
||||||
req.destroy();
|
|
||||||
reject(new Error("loadstream connect timeout (" + LOADSTREAM_CONNECT_TIMEOUT_MS / 1000 + "s — Lavalink took too long to start stream)"));
|
|
||||||
}, LOADSTREAM_CONNECT_TIMEOUT_MS);
|
|
||||||
connectTimer.unref?.();
|
|
||||||
|
|
||||||
req.end();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Stop current playback and clean up resources. */
|
|
||||||
stop() {
|
|
||||||
const wasPlaying = this._playing;
|
|
||||||
this._stopped = true;
|
|
||||||
this._playing = false;
|
|
||||||
this._playGeneration++;
|
|
||||||
|
|
||||||
this._cleanup();
|
|
||||||
|
|
||||||
if (this._conn) {
|
|
||||||
try { this._conn.stop(); } catch (_) {}
|
|
||||||
this._unpublishStaleAudioTracks(this._conn);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (wasPlaying) {
|
|
||||||
this.emit("stopped");
|
|
||||||
logger.player("[AudioBridge] Playback stopped");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {object} conn - Fluxer voice connection
|
|
||||||
* @param {string|null} [keepSid=null] - Track SID to keep (currently active publication)
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_unpublishStaleAudioTracks(conn, keepSid = null) {
|
|
||||||
try {
|
|
||||||
const room = conn?.room;
|
|
||||||
const participant = room?.localParticipant;
|
|
||||||
if (!room?.isConnected || typeof participant?.unpublishTrack !== "function") return;
|
|
||||||
|
|
||||||
const publications = participant.trackPublications;
|
|
||||||
if (!publications || typeof publications.entries !== "function") return;
|
|
||||||
|
|
||||||
for (const [sid, pub] of publications.entries()) {
|
|
||||||
if (keepSid && sid === keepSid) continue;
|
|
||||||
if (pub?.kind !== TRACK_KIND_AUDIO) continue;
|
|
||||||
try {
|
|
||||||
const p = participant.unpublishTrack(sid, true);
|
|
||||||
if (p?.catch) p.catch(() => {});
|
|
||||||
logger.player("[AudioBridge] Unpublished stale audio track: " + sid);
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
} catch (_) {
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set the playback volume on the voice connection.
|
|
||||||
* @param {number} percent - Volume 0–100.
|
|
||||||
*/
|
|
||||||
setVolume(percent) {
|
|
||||||
if (this._conn) {
|
|
||||||
try { this._conn.setVolume(percent); } catch (e) {
|
|
||||||
logger.warn("[AudioBridge] setVolume error: " + e.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @returns {number} Current volume percentage (0–100). */
|
|
||||||
getVolume() {
|
|
||||||
if (this._conn) {
|
|
||||||
try { return this._conn.getVolume(); } catch (_) {}
|
|
||||||
}
|
|
||||||
return 100;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @returns {boolean} Whether the voice connection is currently active. */
|
|
||||||
isConnected() {
|
|
||||||
if (this._conn) {
|
|
||||||
try { return this._conn.isConnected(); } catch (_) {}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Clear timers, settle pending waits, and tear down the pipeline.
|
|
||||||
* @private
|
|
||||||
*/
|
|
||||||
_cleanup() {
|
|
||||||
if (this._durationTimer) { clearTimeout(this._durationTimer); this._durationTimer = null; }
|
|
||||||
if (this._endResolve) {
|
|
||||||
const resolve = this._endResolve;
|
|
||||||
this._endResolve = null;
|
|
||||||
this._endReject = null;
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
for (const s of [this._stream, this._encoder, this._sourceStream]) {
|
|
||||||
if (s) {
|
|
||||||
try { s.destroy(); } catch (_) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (this._sourceReq) {
|
|
||||||
try { this._sourceReq.destroy(); } catch (_) {}
|
|
||||||
}
|
|
||||||
this._stream = null;
|
|
||||||
this._encoder = null;
|
|
||||||
this._sourceStream = null;
|
|
||||||
this._sourceReq = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Stop playback, release the voice connection, and remove all listeners. */
|
|
||||||
destroy() {
|
|
||||||
this.stop();
|
|
||||||
this._conn = null;
|
|
||||||
this._currentUri = null;
|
|
||||||
this.removeAllListeners();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
-2105
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,166 @@
|
|||||||
|
/**
|
||||||
|
* @module src/commands/CommandBuilder
|
||||||
|
* @description Fluent builder for command definitions (name, description,
|
||||||
|
* options, subcommands, aliases, requirements) plus the permission
|
||||||
|
* requirement model.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Utils } from "../utils/Utils.mjs";
|
||||||
|
import { Option } from "./Option.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class CommandRequirement
|
||||||
|
* @description Permission and owner-only gating for a command.
|
||||||
|
*/
|
||||||
|
export class CommandRequirement {
|
||||||
|
/** @type {boolean} Whether the command is restricted to bot owners. */
|
||||||
|
ownerOnly = false;
|
||||||
|
|
||||||
|
/** Create a new CommandRequirement with no permissions. */
|
||||||
|
constructor() {
|
||||||
|
this.permissions = [];
|
||||||
|
this.permissionError = "You don't have the needed permissions to run this command!";
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {boolean} bool @returns {CommandRequirement} */
|
||||||
|
setOwnerOnly(bool) { this.ownerOnly = bool; return this; }
|
||||||
|
/** @param {string} p @returns {CommandRequirement} */
|
||||||
|
addPermission(p) { this.permissions.push(p); return this; }
|
||||||
|
/** @param {...string} p @returns {CommandRequirement} */
|
||||||
|
addPermissions(...p) { this.permissions.push(...p); return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @returns {string[]} The permission list (with an owner note appended when
|
||||||
|
* the requirement is owner-only).
|
||||||
|
*/
|
||||||
|
getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; }
|
||||||
|
/** @param {string} e @returns {CommandRequirement} */
|
||||||
|
setPermissionError(e) { this.permissionError = e; return this; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class CommandBuilder
|
||||||
|
* @description Fluent builder for constructing command definitions with name,
|
||||||
|
* description, options, subcommands, aliases, requirements and examples.
|
||||||
|
*/
|
||||||
|
export class CommandBuilder {
|
||||||
|
/** Create a new CommandBuilder with default empty state. */
|
||||||
|
constructor() {
|
||||||
|
this.name = null;
|
||||||
|
this.description = null;
|
||||||
|
this.id = null;
|
||||||
|
this.aliases = [];
|
||||||
|
this.subcommands = [];
|
||||||
|
this.options = [];
|
||||||
|
this.requirements = [];
|
||||||
|
this.category = "default";
|
||||||
|
this.examples = [];
|
||||||
|
|
||||||
|
this.uid = Utils.uid();
|
||||||
|
|
||||||
|
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
|
||||||
|
this.parent = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Set the command name and register it as the primary alias. @param {string} n @returns {CommandBuilder} */
|
||||||
|
setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; }
|
||||||
|
/** Set the command description. @param {string} d @returns {CommandBuilder} */
|
||||||
|
setDescription(d) { this.description = d; return this; }
|
||||||
|
/** Set the command ID. @param {string} id @returns {CommandBuilder} */
|
||||||
|
setId(id) { this.id = id; return this; }
|
||||||
|
|
||||||
|
/** @returns {string} Full command path including parent chain (e.g. "music play"). */
|
||||||
|
get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a permission/owner-only requirement via a callback.
|
||||||
|
* @param {Function} config - Callback receiving a fresh {@link CommandRequirement}.
|
||||||
|
* @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a subcommand builder via a callback.
|
||||||
|
* @param {Function} config - Callback receiving a fresh {@link CommandBuilder}.
|
||||||
|
* @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a string option.
|
||||||
|
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; }
|
||||||
|
/**
|
||||||
|
* Add a number option.
|
||||||
|
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; }
|
||||||
|
/**
|
||||||
|
* Add a boolean option.
|
||||||
|
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; }
|
||||||
|
/**
|
||||||
|
* Add a channel option.
|
||||||
|
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; }
|
||||||
|
/**
|
||||||
|
* Add a voice-channel option.
|
||||||
|
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addVoiceChannelOption(config, flag = false) { this.options.push(config(Option.create("voiceChannel", flag))); return this; }
|
||||||
|
/**
|
||||||
|
* Add a user option.
|
||||||
|
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a text (remaining-args) option. Only one is allowed per command.
|
||||||
|
* @param {Function} config
|
||||||
|
* @returns {CommandBuilder}
|
||||||
|
* @throws {Error} If a text option already exists.
|
||||||
|
*/
|
||||||
|
addTextOption(config) {
|
||||||
|
if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option.");
|
||||||
|
this.options.push(config(new Option("text")));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a choice (enum-like) option.
|
||||||
|
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add an alias (case-insensitive, duplicates ignored).
|
||||||
|
* @param {string} alias
|
||||||
|
* @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addAlias(alias) {
|
||||||
|
if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this;
|
||||||
|
this.aliases.push(alias.toLowerCase());
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add multiple aliases.
|
||||||
|
* @param {...string} aliases
|
||||||
|
* @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; }
|
||||||
|
|
||||||
|
/** Set the command category (used by help grouping). @param {string} cat @returns {CommandBuilder} */
|
||||||
|
setCategory(cat) { this.category = cat; return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add usage examples.
|
||||||
|
* @param {...string} examples
|
||||||
|
* @returns {CommandBuilder}
|
||||||
|
*/
|
||||||
|
addExamples(...examples) { this.examples.push(...examples); return this; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,569 @@
|
|||||||
|
/**
|
||||||
|
* @module src/commands/CommandHandler
|
||||||
|
* @description The command dispatcher: parses incoming messages, matches
|
||||||
|
* commands and aliases, validates options/flags, enforces permissions and
|
||||||
|
* per-user cooldowns, and emits "run" events consumed by the CommandLoader.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { EventEmitter } from "node:events";
|
||||||
|
import { PermissionFlags } from "@fluxerjs/core";
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
import { Utils } from "../utils/Utils.mjs";
|
||||||
|
import { Message, REQUIRED_BOT_PERMISSIONS } from "../ui/index.mjs";
|
||||||
|
import { Option, Flag } from "./Option.mjs";
|
||||||
|
import { HelpHandler } from "./HelpHandler.mjs";
|
||||||
|
import { PrefixManager } from "./PrefixManager.mjs";
|
||||||
|
|
||||||
|
/** @type {string[]} Option types whose quoted values may span multiple tokens. */
|
||||||
|
const QUOTABLE_TYPES = ["string", "text", "channel", "voiceChannel"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class CommandHandler
|
||||||
|
* @description Main command dispatcher.
|
||||||
|
* @extends {EventEmitter}
|
||||||
|
*
|
||||||
|
* Events:
|
||||||
|
* - `"command"` — emitted with `{ command, message }` when a command starts.
|
||||||
|
* - `"run"` — emitted with the fully parsed run payload (see processCommand).
|
||||||
|
*/
|
||||||
|
export class CommandHandler extends EventEmitter {
|
||||||
|
/** @type {Function|null} Custom handler when the bot is pinged. */
|
||||||
|
onPing = null;
|
||||||
|
/** @type {boolean} Whether the bot responds to pings as a prefix. */
|
||||||
|
pingPrefix = true;
|
||||||
|
/** @type {string[]} Bot owner user IDs. */
|
||||||
|
owners = [];
|
||||||
|
|
||||||
|
/** @type {import('../ui/MessageHandler.mjs').MessageHandler} */
|
||||||
|
messages;
|
||||||
|
client;
|
||||||
|
/** @type {PrefixManager} */
|
||||||
|
prefixes;
|
||||||
|
/** @type {HelpHandler} */
|
||||||
|
helpHandler;
|
||||||
|
|
||||||
|
/** @type {string[]} All registered command aliases. */
|
||||||
|
commandNames = [];
|
||||||
|
/** @type {import('./CommandBuilder.mjs').CommandBuilder[]} Registered commands. */
|
||||||
|
commands = [];
|
||||||
|
|
||||||
|
/** @type {object|null} Locale manager. */
|
||||||
|
locale = null;
|
||||||
|
|
||||||
|
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`";
|
||||||
|
textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string.";
|
||||||
|
|
||||||
|
/** @private @type {Map<string, number>} Per-user last command timestamps for cooldown enforcement. */
|
||||||
|
_cmdCooldowns = new Map();
|
||||||
|
/** @private @type {number} Cooldown duration in ms between commands per non-owner user. */
|
||||||
|
_cmdCooldownMs = 1500;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {import('../ui/MessageHandler.mjs').MessageHandler} handler
|
||||||
|
* @param {string} [prefix="%"]
|
||||||
|
*/
|
||||||
|
constructor(handler, prefix = "%") {
|
||||||
|
super();
|
||||||
|
this.messages = handler;
|
||||||
|
this.client = handler.client;
|
||||||
|
this.prefix = prefix;
|
||||||
|
this.helpHandler = new HelpHandler(this);
|
||||||
|
this.helpCommand = "help";
|
||||||
|
this.replyHandler = (message, msg) => {
|
||||||
|
msg.reply(this.format(message, msg.channel.channel.guildId));
|
||||||
|
};
|
||||||
|
this.messages.onMessage(this.messageHandler.bind(this));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
|
||||||
|
getPrefix(guildId) { return this.prefixes.getPrefix(guildId); }
|
||||||
|
/** Enable or disable ping-as-prefix. @param {boolean} bool */
|
||||||
|
setPingPrefix(bool) { this.pingPrefix = bool; }
|
||||||
|
/** @param {PrefixManager} manager */
|
||||||
|
setPrefixManager(manager) { this.prefixes = manager; }
|
||||||
|
/** @param {HelpHandler} handler */
|
||||||
|
setHelpHandler(handler) { this.helpHandler = handler; }
|
||||||
|
/** @param {object} locale */
|
||||||
|
setLocale(locale) { this.locale = locale; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translate a locale key.
|
||||||
|
* @param {string} guildId
|
||||||
|
* @param {string} key
|
||||||
|
* @param {object} [replacements={}]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
t(guildId, key, replacements = {}) {
|
||||||
|
if (!this.locale) return key;
|
||||||
|
return this.locale.translate(guildId, key, replacements);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replace $prefix and $helpCmd placeholders in text.
|
||||||
|
* @param {string} text
|
||||||
|
* @param {string} guildId
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
format(text, guildId) {
|
||||||
|
const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId);
|
||||||
|
return text
|
||||||
|
.replace(/\$prefix/gi, prefix)
|
||||||
|
.replace(/\$helpCmd/gi, this.helpCommand);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove a command from the registry.
|
||||||
|
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
|
||||||
|
*/
|
||||||
|
removeCommand(command) {
|
||||||
|
command.aliases.forEach(a => {
|
||||||
|
const idx = this.commandNames.indexOf(a);
|
||||||
|
if (idx !== -1) this.commandNames.splice(idx, 1);
|
||||||
|
});
|
||||||
|
const idx = this.commands.findIndex(c => c.uid === command.uid);
|
||||||
|
if (idx !== -1) this.commands.splice(idx, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Handle an incoming message and route it to command processing.
|
||||||
|
* Handles bare pings, prefix detection, cooldowns and the built-in help.
|
||||||
|
* @param {Message} msg
|
||||||
|
*/
|
||||||
|
messageHandler(msg) {
|
||||||
|
if (!msg || !msg.content) return;
|
||||||
|
const trimmed = msg.content.trim();
|
||||||
|
if (/^<@!?\d+>$/.test(trimmed)) {
|
||||||
|
const botId = this.client.user?.id;
|
||||||
|
if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) {
|
||||||
|
return this.onPing?.(msg);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
const prefix = this.getPrefix(guildId);
|
||||||
|
const ping = `<@${this.client.user?.id}>`;
|
||||||
|
const pingBang = `<@!${this.client.user?.id}>`;
|
||||||
|
if (!(msg.content.startsWith(prefix) || msg.content.startsWith(ping) || msg.content.startsWith(pingBang))) return;
|
||||||
|
|
||||||
|
if (this._isCoolingDown(msg)) return;
|
||||||
|
this._enforceCooldown(msg);
|
||||||
|
|
||||||
|
const len = msg.content.startsWith(prefix) ? prefix.length : (msg.content.startsWith(pingBang) ? pingBang.length : ping.length);
|
||||||
|
const args = msg.content.slice(len).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||||
|
|
||||||
|
if (!args[0]) return;
|
||||||
|
|
||||||
|
if (args[0] === this.helpCommand) {
|
||||||
|
return this._handleHelpInvocation(args, guildId, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.commandNames.includes(args[0].toLowerCase())) {
|
||||||
|
this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix$helpCmd", guildId) }), msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Apply the per-user cooldown gate: records the timestamp for the
|
||||||
|
* invoking user and prunes the cooldown map when it grows too large.
|
||||||
|
* Owners are exempt.
|
||||||
|
* @param {Message} msg
|
||||||
|
*/
|
||||||
|
_enforceCooldown(msg) {
|
||||||
|
const userId = msg.message?.author?.id ?? msg.author?.id;
|
||||||
|
if (!userId || this.owners.includes(userId)) return;
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
this._cmdCooldowns.set(userId, now);
|
||||||
|
if (this._cmdCooldowns.size > 500) {
|
||||||
|
const cutoff = now - this._cmdCooldownMs * 2;
|
||||||
|
for (const [uid, ts] of this._cmdCooldowns) {
|
||||||
|
if (ts < cutoff) this._cmdCooldowns.delete(uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Cooldown gate — returns true when the user invoked a command too
|
||||||
|
* recently and the message should be dropped (owners are exempt).
|
||||||
|
* @param {Message} msg
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
_isCoolingDown(msg) {
|
||||||
|
const userId = msg.message?.author?.id ?? msg.author?.id;
|
||||||
|
if (!userId || this.owners.includes(userId)) return false;
|
||||||
|
const now = Date.now();
|
||||||
|
const last = this._cmdCooldowns.get(userId) ?? 0;
|
||||||
|
return (now - last) < this._cmdCooldownMs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Built-in `%help` invocation handling (bare / page / command / subcommand path).
|
||||||
|
* @param {string[]} args
|
||||||
|
* @param {string} guildId
|
||||||
|
* @param {Message} msg
|
||||||
|
*/
|
||||||
|
_handleHelpInvocation(args, guildId, msg) {
|
||||||
|
if (!args[1]) {
|
||||||
|
const res = this.helpHandler.help(msg);
|
||||||
|
return (typeof res === "string") ? this.replyHandler(res, msg) : undefined;
|
||||||
|
}
|
||||||
|
if (args.length > 1 && Utils.isNumber(args[1])) {
|
||||||
|
const pageNumber = parseInt(args[1]);
|
||||||
|
if (pageNumber < 1 || pageNumber > this.helpHandler.pageNumber()) {
|
||||||
|
return this.replyHandler(this.t(guildId, "cmdHandler.page.invalid", { number: pageNumber }), msg);
|
||||||
|
}
|
||||||
|
return this.replyHandler(this.helpHandler.getHelpPage(pageNumber - 1, msg), msg);
|
||||||
|
}
|
||||||
|
if (args.length <= 2) {
|
||||||
|
let idx = this.commands.findIndex(e => e.aliases.some(al => al.toLowerCase() === args[1].toLowerCase()));
|
||||||
|
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + args[1], guildId) }), msg);
|
||||||
|
return this.replyHandler(this.helpHandler.getCommandHelp(this.commands[idx], msg), msg);
|
||||||
|
}
|
||||||
|
let currCmd = null;
|
||||||
|
let prefix2 = "";
|
||||||
|
for (let i = 0; i < args.slice(1).length; i++) {
|
||||||
|
let a = args.slice(1)[i];
|
||||||
|
let curr = (currCmd) ? currCmd.subcommands : this.commands;
|
||||||
|
let idx = curr.findIndex(e => e.aliases.some(al => al.toLowerCase() === a.toLowerCase()));
|
||||||
|
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + prefix2 + a, guildId) }), msg);
|
||||||
|
currCmd = curr[idx];
|
||||||
|
prefix2 += a + " ";
|
||||||
|
}
|
||||||
|
return this.replyHandler(this.helpHandler.getCommandHelp(currCmd, msg), msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse and execute a command with its options.
|
||||||
|
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
|
||||||
|
* @param {string[]} args
|
||||||
|
* @param {Message} msg
|
||||||
|
* @param {string|boolean} [previous=false] - The command path so far (for error messages).
|
||||||
|
* @param {boolean} [external=false] - When true, errors are returned instead of replied.
|
||||||
|
* @returns {object|undefined} The command run payload.
|
||||||
|
*/
|
||||||
|
processCommand(cmd, args, msg, previous = false, external = false) {
|
||||||
|
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
||||||
|
|
||||||
|
if (!external) {
|
||||||
|
const channel = msg.channel?.channel ?? msg.channel;
|
||||||
|
if (channel?.guild) {
|
||||||
|
const botPermResult = this.messages.checkAllBotPermissions(channel);
|
||||||
|
if (botPermResult.criticalMissing.length > 0) {
|
||||||
|
const permEmbed = this.messages.buildPermissionEmbed(botPermResult.missing, channel.guildId);
|
||||||
|
try {
|
||||||
|
msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false });
|
||||||
|
} catch (_) {
|
||||||
|
try {
|
||||||
|
const names = botPermResult.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
||||||
|
msg.message?.reply?.("I'm missing critical permissions: **" + names.join("**, **") + "**. Ask an admin to fix this.", { ping: false });
|
||||||
|
} catch (__) { logger.warn("[CommandHandler] Fallback perm reply failed"); }
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cmd.requirements.length > 0 && !external) {
|
||||||
|
if (!this.assertRequirements(cmd, msg)) return;
|
||||||
|
}
|
||||||
|
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
||||||
|
if (!external) this.emit("command", { command: cmd, message: msg });
|
||||||
|
|
||||||
|
if (cmd.subcommands.length !== 0) {
|
||||||
|
const idx = cmd.subcommands.findIndex(el => {
|
||||||
|
if (!args[1]) return false;
|
||||||
|
return el.name.toLowerCase() === args[1].toLowerCase();
|
||||||
|
});
|
||||||
|
if (idx === -1) {
|
||||||
|
const list = cmd.subcommands.map(s => s.name).join(" | ");
|
||||||
|
const subGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
const e = this.t(subGuildId, "cmdBuilder.subcommand.invalid").replace(/\$previousCmd/gi, previous).replace(/\$cmdList/gi, list);
|
||||||
|
return (!external) ? this.replyHandler(e, msg) : e;
|
||||||
|
}
|
||||||
|
return this.processCommand(cmd.subcommands[idx], args.slice(1), msg, previous + this.format(" " + cmd.subcommands[idx].name), external);
|
||||||
|
}
|
||||||
|
|
||||||
|
// `error === true` → internal invocation: the error reply was already
|
||||||
|
// sent by _parseOptions and, exactly like the original monolith, the
|
||||||
|
// command must NOT run (no "run" emission). A string is the external-
|
||||||
|
// mode error, returned to the caller as before.
|
||||||
|
const { opts, error } = this._parseOptions(cmd, args, msg, previous, external);
|
||||||
|
if (error) return (error === true) ? undefined : error;
|
||||||
|
|
||||||
|
const commandRunData = {
|
||||||
|
command: cmd,
|
||||||
|
commandId: cmd.id,
|
||||||
|
options: opts,
|
||||||
|
message: msg,
|
||||||
|
get: function (oName) { return this.options.find(o => o.name === oName); },
|
||||||
|
getById: function (id) { return this.options.find(o => o.id === id); }
|
||||||
|
};
|
||||||
|
if (!external) this.emit("run", commandRunData);
|
||||||
|
return commandRunData;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Parse positional options, flags, quoted values and text options.
|
||||||
|
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
|
||||||
|
* @param {string[]} args
|
||||||
|
* @param {Message} msg
|
||||||
|
* @param {string} previous
|
||||||
|
* @param {boolean} external
|
||||||
|
* @returns {{opts: Array, error: *}} Parsed options or a handled error:
|
||||||
|
* `null` on success; `true` when an internal (non-external) invocation
|
||||||
|
* already sent its error reply and the caller must stop (the original
|
||||||
|
* monolith exited processCommand directly at these points); the error
|
||||||
|
* string for external invocations at the option/flag validation sites
|
||||||
|
* (textWrap sites always reply, matching the original's always-reply quirk).
|
||||||
|
*/
|
||||||
|
_parseOptions(cmd, args, msg, previous, external) {
|
||||||
|
const opts = [];
|
||||||
|
const texts = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collect quoted arguments spanning multiple tokens.
|
||||||
|
* @param {number} index
|
||||||
|
* @param {string} currVal
|
||||||
|
* @param {string[]} as
|
||||||
|
* @returns {{args: string[], index: number}|null}
|
||||||
|
*/
|
||||||
|
const collectArguments = (index, currVal, as) => {
|
||||||
|
const lastChar = currVal.charAt(currVal.length - 1);
|
||||||
|
if (lastChar === '"') return { args: as, index };
|
||||||
|
const a = args[++index];
|
||||||
|
if (!a) return null;
|
||||||
|
as.push(a);
|
||||||
|
return collectArguments(index, a, as);
|
||||||
|
};
|
||||||
|
|
||||||
|
const options = cmd.options.slice().sort((a, b) => {
|
||||||
|
const aText = (a.type === "text") ? 1 : 2;
|
||||||
|
const bText = (b.type === "text") ? 1 : 2;
|
||||||
|
return aText - bText;
|
||||||
|
});
|
||||||
|
|
||||||
|
const usedOptions = [];
|
||||||
|
let usedArgumentCount = 0;
|
||||||
|
|
||||||
|
for (let i = 0, argIndex = 1; i < options.length; i++) {
|
||||||
|
const o = options[i];
|
||||||
|
if (o?.type === "text") { texts.push(o); continue; }
|
||||||
|
if ((args[argIndex] || "").startsWith("-")) {
|
||||||
|
const flagName = args[argIndex].slice(1);
|
||||||
|
const op = cmd.options.find(e => e.aliases.includes(flagName));
|
||||||
|
if (!op) {
|
||||||
|
const flagGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
const error = this.t(flagGuildId, "cmdHandler.invalidFlag").replace(/\$previousCmd/gi, previous).replace(/\$invalidFlag/gi, "-" + flagName);
|
||||||
|
return { opts, error: (!external) ? (this.replyHandler(error, msg) ?? true) : error };
|
||||||
|
}
|
||||||
|
previous += " " + args[argIndex];
|
||||||
|
let value = args[++argIndex];
|
||||||
|
if ((value || "").startsWith('"') && (QUOTABLE_TYPES.includes(op.type))) {
|
||||||
|
const data = collectArguments(argIndex, value, [value]);
|
||||||
|
if (!data) {
|
||||||
|
const twGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
return { opts, error: (this.replyHandler(this._textWrapErrorMsg(twGuildId, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg) ?? true) };
|
||||||
|
}
|
||||||
|
argIndex += data.index - argIndex;
|
||||||
|
const _joined = data.args.join(" ");
|
||||||
|
value = _joined.slice(1, _joined.length - 1);
|
||||||
|
}
|
||||||
|
argIndex++;
|
||||||
|
i--;
|
||||||
|
const valid = op.validateInput(value, this.client, msg.message);
|
||||||
|
if (!valid && (op.required || !op.empty(value))) {
|
||||||
|
const errGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
const e = this._optionTypeError(errGuildId, op, value, previous);
|
||||||
|
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
||||||
|
}
|
||||||
|
usedArgumentCount += 2;
|
||||||
|
previous += " " + value;
|
||||||
|
opts.push({ value: op.formatInput(value, this.client, msg.message), name: op.name, id: op.id, uid: op.uid });
|
||||||
|
usedOptions.push(op.uid);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!o) continue;
|
||||||
|
if (o instanceof Flag) continue;
|
||||||
|
if (opts.findIndex(op => op.uid === o.uid) !== -1) continue;
|
||||||
|
let value = args[argIndex];
|
||||||
|
if ((args[argIndex] || "").startsWith('"') && (QUOTABLE_TYPES.includes(o.type))) {
|
||||||
|
const data = collectArguments(argIndex, args[argIndex], [args[argIndex]]);
|
||||||
|
if (!data) {
|
||||||
|
const twGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
return { opts, error: (this.replyHandler(this._textWrapErrorMsg(twGuildId2, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg) ?? true) };
|
||||||
|
}
|
||||||
|
argIndex += data.index - argIndex;
|
||||||
|
value = data.args.join(" ");
|
||||||
|
value = value.slice(1, value.length - 1);
|
||||||
|
}
|
||||||
|
let valid = o.validateInput(value, this.client, msg.message);
|
||||||
|
if (!valid && o.dynamicDefault) {
|
||||||
|
value = o.dynamicDefault(this.client, msg);
|
||||||
|
valid = o.validateInput(value, this.client, msg.message);
|
||||||
|
}
|
||||||
|
if (!valid && (o.required || !o.empty(value))) {
|
||||||
|
const errGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
const e = this._optionTypeError(errGuildId2, o, value, previous);
|
||||||
|
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
||||||
|
}
|
||||||
|
if (o.empty(value)) value = o.defaultValue;
|
||||||
|
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
|
||||||
|
usedOptions.push(o.uid);
|
||||||
|
previous += " " + value;
|
||||||
|
argIndex++;
|
||||||
|
usedArgumentCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (texts.length > 0) {
|
||||||
|
let o = texts[0];
|
||||||
|
let text = args.slice(usedArgumentCount + 1).join(" ");
|
||||||
|
if (o.required && !o.validateInput(text, this.client, msg.message)) {
|
||||||
|
const textErrGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
let e = this._optionTypeError(textErrGuildId, o, text, previous);
|
||||||
|
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
||||||
|
}
|
||||||
|
const quote = (['"', "'"].includes(text.charAt(0))) ? text.charAt(0) : null;
|
||||||
|
if (quote && text.charAt(text.length - 1) === quote) text = text.slice(1, text.length - 1);
|
||||||
|
opts.push({ name: o.name, value: text, id: o.id, uid: o.uid });
|
||||||
|
usedOptions.push(o.uid);
|
||||||
|
}
|
||||||
|
|
||||||
|
options.filter(o => !usedOptions.includes(o.uid)).forEach(o => {
|
||||||
|
if (!o.defaultValue) return;
|
||||||
|
opts.push({ name: o.name, value: o.defaultValue, id: o.id, uid: o.uid });
|
||||||
|
});
|
||||||
|
|
||||||
|
return { opts, error: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether the message author meets all command requirements
|
||||||
|
* (owner-only, guild permissions). When member data must be fetched over
|
||||||
|
* REST, re-invokes processCommand asynchronously once resolved.
|
||||||
|
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
|
||||||
|
* @param {Message} msg
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
assertRequirements(cmd, msg) {
|
||||||
|
const authorId = msg.message?.author?.id;
|
||||||
|
const isOwner = this.owners.includes(authorId);
|
||||||
|
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
|
||||||
|
for (let i = 0; i < cmd.requirements.length; i++) {
|
||||||
|
let req = cmd.requirements[i];
|
||||||
|
if (req.ownerOnly && !isOwner) return false;
|
||||||
|
if (req.permissions.length > 0 && !isOwner) {
|
||||||
|
const guild = msg.message?.guild ?? null;
|
||||||
|
if (!guild) {
|
||||||
|
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const member = guild.members.get(authorId) ?? null;
|
||||||
|
if (member?.permissions) {
|
||||||
|
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
||||||
|
if (missing.length > 0) {
|
||||||
|
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const fetchPromise = typeof guild.fetchMember === "function"
|
||||||
|
? guild.fetchMember(authorId)
|
||||||
|
: typeof guild.members?.fetch === "function"
|
||||||
|
? guild.members.fetch(authorId)
|
||||||
|
: Promise.reject(new Error("No member fetch API available"));
|
||||||
|
fetchPromise.then(member => {
|
||||||
|
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
||||||
|
if (missing.length > 0) {
|
||||||
|
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||||
|
} else {
|
||||||
|
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||||
|
const prefix2 = this.getPrefix(guildId2);
|
||||||
|
const rawContent = msg.message.content;
|
||||||
|
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
||||||
|
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||||
|
this.processCommand(cmd, args, msg, false, true);
|
||||||
|
}
|
||||||
|
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate an input for a given option type.
|
||||||
|
* @param {string} type
|
||||||
|
* @param {*} i
|
||||||
|
* @param {object} m
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format an input for a given option type.
|
||||||
|
* @param {string} type
|
||||||
|
* @param {*} i
|
||||||
|
* @param {object} m
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
|
formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Build a type-error message for an option.
|
||||||
|
* @param {string} guildId
|
||||||
|
* @param {Option} option
|
||||||
|
* @param {*} value
|
||||||
|
* @param {string} previous
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
_optionTypeError(guildId, option, value, previous) {
|
||||||
|
if (option.tError) {
|
||||||
|
return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
|
||||||
|
}
|
||||||
|
const localeKey = option.type === 'choice' ? 'cmdBuilder.option.invalidChoice'
|
||||||
|
: (option.type === 'channel' || option.type === 'voiceChannel') ? 'cmdBuilder.option.invalidChannel'
|
||||||
|
: 'cmdBuilder.option.invalidType';
|
||||||
|
const choiceStr = option.type === 'choice'
|
||||||
|
? (option.choices.length > Option.THRESHOLD ? Option.formatChoicesCompact(option.choices) : option.choices.map(c => '- ' + c).join('\n'))
|
||||||
|
: '';
|
||||||
|
return this.t(guildId, localeKey, {
|
||||||
|
$currValue: value,
|
||||||
|
$optionName: option.name,
|
||||||
|
$type: option.type,
|
||||||
|
$choices: choiceStr
|
||||||
|
}).replace(/\$previousCmd/gi, previous);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @private Build a text-wrap error message.
|
||||||
|
* @param {string} guildId
|
||||||
|
* @param {string} value
|
||||||
|
* @param {string} quote
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
_textWrapErrorMsg(guildId, value, quote) {
|
||||||
|
return this.t(guildId, 'cmdHandler.textWrapError', { $value: value, $quote: quote });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a command builder and sort the command list alphabetically.
|
||||||
|
* @param {import('./CommandBuilder.mjs').CommandBuilder} builder
|
||||||
|
* @returns {import('./CommandBuilder.mjs').CommandBuilder[]}
|
||||||
|
*/
|
||||||
|
addCommand(builder) {
|
||||||
|
this.commandNames.push(...builder.aliases);
|
||||||
|
this.commands.push(builder);
|
||||||
|
this.commands.sort((a, b) => {
|
||||||
|
let A = a.name.toUpperCase();
|
||||||
|
let B = b.name.toUpperCase();
|
||||||
|
return (A < B) ? -1 : (A > B) ? 1 : 0;
|
||||||
|
});
|
||||||
|
return this.commands;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
/**
|
||||||
|
* @module src/commands/CommandLoader
|
||||||
|
* @description Dynamically loads command modules from a directory, registers
|
||||||
|
* their builders, and binds run handlers with error capture + error-id replies.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { pathToFileURL } from "node:url";
|
||||||
|
import path from "node:path";
|
||||||
|
import * as fs from "node:fs";
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
import { Utils } from "../utils/Utils.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class CommandLoader
|
||||||
|
* @description Loads command files from a directory, registers builders with
|
||||||
|
* the CommandHandler, and dispatches "run" events to the matching run function.
|
||||||
|
*
|
||||||
|
* Command module shape (both shapes are accepted):
|
||||||
|
* - `export const command` (builder or builder-factory), `export const run`
|
||||||
|
* - default export object with the same keys
|
||||||
|
* - optional `exportDef: { name, object }` registers a global on the context
|
||||||
|
*/
|
||||||
|
export class CommandLoader {
|
||||||
|
/** @type {import('./CommandHandler.mjs').CommandHandler} */
|
||||||
|
commands;
|
||||||
|
/** @type {Map<string, string>} Command UID → file path. */
|
||||||
|
commandFiles = new Map();
|
||||||
|
/** @type {Map<string, Function>} Command UID → run function. */
|
||||||
|
runnables = new Map();
|
||||||
|
/** @type {object} Shared context (the bot instance). */
|
||||||
|
context;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {import('./CommandHandler.mjs').CommandHandler} commands
|
||||||
|
* @param {object} context - Bot context object (gets loader/runnables refs attached).
|
||||||
|
*/
|
||||||
|
constructor(commands, context) {
|
||||||
|
this.commands = commands;
|
||||||
|
this.context = context;
|
||||||
|
this.context.loader ??= this;
|
||||||
|
this.context.commandFiles = this.commandFiles;
|
||||||
|
this.context.runnables = this.runnables;
|
||||||
|
|
||||||
|
this.commands.on("run", (data) => {
|
||||||
|
if (!this.runnables.has(data.command.uid)) return;
|
||||||
|
const runFc = this.runnables.get(data.command.uid);
|
||||||
|
const sendErrorReply = (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));
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
const result = runFc.call(this.context, data.message, data);
|
||||||
|
if (result && typeof result.catch === "function") {
|
||||||
|
result.catch(e => {
|
||||||
|
const id = Utils.uid();
|
||||||
|
logger.error("Error running command; error id #" + id, e);
|
||||||
|
sendErrorReply(id);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
const id = Utils.uid();
|
||||||
|
logger.error("Error running command; error id #" + id, e);
|
||||||
|
sendErrorReply(id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize a module export to `{ command, run, exportDef }`.
|
||||||
|
* @param {object} cData
|
||||||
|
* @returns {object}
|
||||||
|
*/
|
||||||
|
canonData(cData) {
|
||||||
|
if (cData.command !== undefined) {
|
||||||
|
return {
|
||||||
|
command: cData.command,
|
||||||
|
run: cData.run,
|
||||||
|
exportDef: cData.exportDef ?? cData.export ?? null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const d = cData.default ?? cData;
|
||||||
|
return {
|
||||||
|
command: d.command,
|
||||||
|
run: d.run,
|
||||||
|
exportDef: d.exportDef ?? d.export ?? null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @async Load all command files from a directory.
|
||||||
|
* @param {string} dir
|
||||||
|
* @returns {Promise<undefined[]>}
|
||||||
|
*/
|
||||||
|
loadFromDir(dir) {
|
||||||
|
const files = fs.readdirSync(dir)
|
||||||
|
.filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs")));
|
||||||
|
|
||||||
|
return Promise.all(files.map(async commandFile => {
|
||||||
|
const file = path.join(dir, commandFile);
|
||||||
|
|
||||||
|
const cData = this.canonData(await import(pathToFileURL(file).href));
|
||||||
|
|
||||||
|
const builder = (typeof cData.command === "function")
|
||||||
|
? cData.command.call(this.context)
|
||||||
|
: cData.command;
|
||||||
|
|
||||||
|
if (!builder) return logger.warn("No builder returned. Skipping '" + commandFile + "'");
|
||||||
|
|
||||||
|
if (cData.exportDef)
|
||||||
|
this.context[cData.exportDef.name] = cData.exportDef.object;
|
||||||
|
|
||||||
|
this.commands.addCommand(builder);
|
||||||
|
this.commandFiles.set(builder.uid, file);
|
||||||
|
|
||||||
|
if (!cData.run) return;
|
||||||
|
|
||||||
|
this.runnables.set(builder.uid, cData.run);
|
||||||
|
builder.subcommands.forEach(sub => {
|
||||||
|
this.runnables.set(sub.uid, cData.run);
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
/**
|
||||||
|
* @module src/commands/HelpHandler
|
||||||
|
* @description Text-based help generation: paginated command lists, per-command
|
||||||
|
* usage/aliases/options rendering. Used as the default help renderer behind
|
||||||
|
* `%help <n>` (the rich tabbed help lives in src/ui/HelpCommand.mjs).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { PageBuilder } from "../ui/Paginators.mjs";
|
||||||
|
import { Option, Flag } from "./Option.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class HelpHandler
|
||||||
|
* @description Generates paginated help text for commands.
|
||||||
|
*/
|
||||||
|
export class HelpHandler {
|
||||||
|
/** @type {import('./CommandHandler.mjs').CommandHandler} */
|
||||||
|
commands;
|
||||||
|
/** @type {number} Commands per help page. */
|
||||||
|
commandsPerPage = 5;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default pagination handler that builds paginated help pages.
|
||||||
|
* @param {object} msg - Message wrapper with message data.
|
||||||
|
* @param {HelpHandler} helpHandler
|
||||||
|
* @param {Array} cmds
|
||||||
|
* @returns {string|null}
|
||||||
|
*/
|
||||||
|
paginationHandler = (msg, helpHandler, cmds) => {
|
||||||
|
const guildId = msg.message.guildId;
|
||||||
|
let form = this.commands.t(guildId, "cmdHandler.help.pageStructure");
|
||||||
|
|
||||||
|
const contents = cmds.map((cmd, i) => {
|
||||||
|
return (i + 1) + ". **" + cmd.name + "**: " + (cmd.description || "").split("\n")[0];
|
||||||
|
});
|
||||||
|
|
||||||
|
const pages = new PageBuilder(contents)
|
||||||
|
.setForm(helpHandler.commands.format(form, msg.message.guildId))
|
||||||
|
.setMaxLines(helpHandler.commandsPerPage);
|
||||||
|
|
||||||
|
helpHandler.commands.messages.initPagination(pages, msg);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @type {Function|null} Custom help handler function override. */
|
||||||
|
customHelpHandler = null;
|
||||||
|
|
||||||
|
/** @param {import('./CommandHandler.mjs').CommandHandler} commands */
|
||||||
|
constructor(commands) { this.commands = commands; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} string
|
||||||
|
* @returns {string} Capitalised first letter.
|
||||||
|
*/
|
||||||
|
static capitalise(string) {
|
||||||
|
if (string.length < 1) return string;
|
||||||
|
if (string.length === 1) return string.toUpperCase();
|
||||||
|
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {Array} [cmds]
|
||||||
|
* @returns {Array} Non-owner-only commands.
|
||||||
|
*/
|
||||||
|
userCommands(cmds) {
|
||||||
|
return (cmds || this.commands.commands).filter(c =>
|
||||||
|
c.requirements.findIndex(r => r.ownerOnly) === -1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @returns {number} Total number of help pages. */
|
||||||
|
pageNumber() {
|
||||||
|
return Math.ceil(this.commands.commands.length / this.commandsPerPage);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entry point for help rendering.
|
||||||
|
* @param {object} message
|
||||||
|
* @returns {string|null}
|
||||||
|
*/
|
||||||
|
help(message) {
|
||||||
|
if (this.customHelpHandler) return this.customHelpHandler(message);
|
||||||
|
if (this.paginationHandler) return this.genHelp(null, message, true);
|
||||||
|
return this.getHelpPage(0, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {number} n - 0-based page index.
|
||||||
|
* @param {object} msg
|
||||||
|
* @param {Array} [cmds=null]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
getHelpPage(n, msg, cmds = null) {
|
||||||
|
if (!cmds) cmds = this.commands.commands;
|
||||||
|
if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds);
|
||||||
|
let offset = this.commandsPerPage * n;
|
||||||
|
const commands = cmds.slice(offset, offset + this.commandsPerPage);
|
||||||
|
let max = Math.ceil(cmds.length / this.commandsPerPage);
|
||||||
|
return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object|null} page
|
||||||
|
* @param {object} msg
|
||||||
|
* @param {boolean} [paginate=false]
|
||||||
|
* @param {Array} [cmds=null]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
genHelp(page, msg, paginate = false, cmds = null) {
|
||||||
|
cmds = this.userCommands(cmds);
|
||||||
|
if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds);
|
||||||
|
|
||||||
|
const guildId = msg.message.guildId;
|
||||||
|
let p = (page) ? ` (page ${page.curr}/${page.max})` : "";
|
||||||
|
const indexOffset = (page) ? page.offset : 0;
|
||||||
|
let content = this.commands.t(guildId, "cmdHandler.help.availableCommands", { $page: p }) + "\n\n";
|
||||||
|
if (page && page.curr !== 1) content += (indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
|
||||||
|
cmds.forEach((cmd, i) => { content += (i + 1 + indexOffset) + ". **" + cmd.name + "**: " + cmd.description + "\n"; });
|
||||||
|
if (page && page.curr !== page.max) content += (cmds.length + indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
|
||||||
|
content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.runHelp"), guildId);
|
||||||
|
if (page) content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.pageTip"), guildId);
|
||||||
|
|
||||||
|
return this.commands.format(content, guildId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the description of a command.
|
||||||
|
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
commandDescription(command) { return command.description; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a usage string for a command including options and flags.
|
||||||
|
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
|
||||||
|
* @param {object} msg
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
commandUsage(cmd, msg) {
|
||||||
|
if (cmd.subcommands.length > 0) {
|
||||||
|
return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]";
|
||||||
|
}
|
||||||
|
let options = this.commands.format("$prefix" + cmd.command, msg.message.guildId);
|
||||||
|
cmd.options.forEach(o => {
|
||||||
|
if (o.type === "text") return;
|
||||||
|
if (o instanceof Flag)
|
||||||
|
return options += (o.type === "choice") ? "-" + o.aliases[0] + " <" + Option.formatChoicesUsage(o.choices) + ">" : " -" + o.aliases[0] + " '" + o.type + "'";
|
||||||
|
options += (o.type === "choice") ? " <" + Option.formatChoicesUsage(o.choices) + ">" : " '" + o.name + ": " + o.type + "'";
|
||||||
|
});
|
||||||
|
let o = cmd.options.find(e => e.type === "text");
|
||||||
|
if (o) options += "'" + o.name + ": " + o.type + "'";
|
||||||
|
return options.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate detailed help text for a single command.
|
||||||
|
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
|
||||||
|
* @param {object} msg
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
getCommandHelp(command, msg) {
|
||||||
|
const guildId = msg.message.guildId;
|
||||||
|
let content = `${HelpHandler.capitalise(command.name)}\n`;
|
||||||
|
content += this.commandDescription(command, msg) + "\n\n";
|
||||||
|
content += this.commands.t(guildId, "cmdHandler.help.usage") + "\n💻 `" + this.commandUsage(command, msg) + "`\n\n";
|
||||||
|
if (command.examples.length > 0)
|
||||||
|
content += this.commands.t(guildId, "cmdHandler.help.examples") + "\n- `" + command.examples.map(e => this.commands.format(e, guildId)).join("`\n- `") + "`\n\n";
|
||||||
|
if (command.aliases.length > 1) {
|
||||||
|
content += this.commands.t(guildId, "cmdHandler.help.aliases") + "\n";
|
||||||
|
command.aliases.forEach(alias => { content += "- " + alias + "\n"; });
|
||||||
|
content += "\n";
|
||||||
|
}
|
||||||
|
if (command.subcommands.length > 0) {
|
||||||
|
content += this.commands.t(guildId, "cmdHandler.help.subcommands") + "\n";
|
||||||
|
command.subcommands.forEach(s => {
|
||||||
|
const optCount = s.options.length > 0 ? "; (`" + this.commands.t(guildId, "cmdHandler.help.optionCount", { $count: s.options.length }) + "`)" : "";
|
||||||
|
content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + optCount + "\n";
|
||||||
|
});
|
||||||
|
content += "\n";
|
||||||
|
} else if (command.options.length > 0) {
|
||||||
|
content += this.commands.t(guildId, "cmdHandler.help.arguments") + "\n";
|
||||||
|
command.options.forEach(o => {
|
||||||
|
const optional = ((o.required) ? "" : "?");
|
||||||
|
const flag = (o instanceof Flag) ? "-" : "";
|
||||||
|
if (o.type === "choice") {
|
||||||
|
const choiceDisplay = Option.formatChoicesInline(o.choices);
|
||||||
|
const aliasDisplay = o.aliases.filter(a => a !== null).join('`, `');
|
||||||
|
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";
|
||||||
|
});
|
||||||
|
content += "\n";
|
||||||
|
}
|
||||||
|
if (command.requirements.length > 0) {
|
||||||
|
content += this.commands.t(guildId, "cmdHandler.help.requirements") + "\n";
|
||||||
|
command.requirements.forEach(r => {
|
||||||
|
content += "- " + r.getPermissions().map(e => this.commands.t(guildId, "cmdHandler.help.permission", { $permission: e })).join("\n- ");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return content.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
/**
|
||||||
|
* @module src/commands/Option
|
||||||
|
* @description Command option model — typed inputs (string, number, boolean,
|
||||||
|
* channel, user, choice, text) with validation, formatting and flag support.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Utils } from "../utils/Utils.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class Option
|
||||||
|
* @description Represents a single command option with validation and
|
||||||
|
* user-friendly error formatting. Options are positional; Flags (dashed
|
||||||
|
* `-name` arguments) share the same base class.
|
||||||
|
*/
|
||||||
|
export class Option {
|
||||||
|
/** @type {number} Maximum choices before switching to compact format. */
|
||||||
|
static THRESHOLD = 10;
|
||||||
|
/** @type {number} Number of choice columns per line in compact format. */
|
||||||
|
static COLS_PER_LINE = 5;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format choice values in a compact multi-column layout.
|
||||||
|
* @param {string[]} choices
|
||||||
|
* @param {number} [perLine=Option.COLS_PER_LINE]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
static formatChoicesCompact(choices, perLine = Option.COLS_PER_LINE) {
|
||||||
|
const lines = [];
|
||||||
|
for (let i = 0; i < choices.length; i += perLine) {
|
||||||
|
lines.push(choices.slice(i, i + perLine).map(c => '`' + c + '`').join(' · '));
|
||||||
|
}
|
||||||
|
return lines.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format choice values inline, switching to compact layout above the threshold.
|
||||||
|
* @param {string[]} choices
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
static formatChoicesInline(choices) {
|
||||||
|
if (choices.length <= Option.THRESHOLD) {
|
||||||
|
return '`' + choices.join('`, `') + '`';
|
||||||
|
}
|
||||||
|
return Option.formatChoicesCompact(choices, 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format choice values for a usage string, truncating with "…" if over max.
|
||||||
|
* @param {string[]} choices
|
||||||
|
* @param {number} [max=6]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
static formatChoicesUsage(choices, max = 6) {
|
||||||
|
if (choices.length <= max) return choices.join(' | ');
|
||||||
|
return choices.slice(0, max).join(' | ') + ' | ...';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @type {RegExp} Matches a channel mention like `<#123456>`. */
|
||||||
|
channelRegex = /^<#(?<id>\d+)>/;
|
||||||
|
/** @type {RegExp} Matches a user mention like `<@123>` or `<@!123>`. */
|
||||||
|
userRegex = /^<@!?(?<id>\d+)>/;
|
||||||
|
/** @type {RegExp} Matches a leading numeric ID. */
|
||||||
|
idRegex = /^(?<id>\d+)/;
|
||||||
|
|
||||||
|
/** @type {Function|null} Dynamic default value resolver. */
|
||||||
|
dynamicDefault;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {string} [type="string"] One of: string, number, boolean, channel,
|
||||||
|
* voiceChannel, user, choice, text.
|
||||||
|
*/
|
||||||
|
constructor(type = "string") {
|
||||||
|
this.name = null;
|
||||||
|
this.description = null;
|
||||||
|
this.required = false;
|
||||||
|
this.id = null;
|
||||||
|
this.uid = Utils.uid();
|
||||||
|
this.type = type;
|
||||||
|
this.tError = null;
|
||||||
|
this.aliases = [null];
|
||||||
|
this.choices = [];
|
||||||
|
this.translations = {};
|
||||||
|
this.defaultValue = null;
|
||||||
|
this.dynamicDefault = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory to create an Option or Flag instance.
|
||||||
|
* @param {string} type
|
||||||
|
* @param {boolean} [flag=false]
|
||||||
|
* @returns {Option|Flag}
|
||||||
|
*/
|
||||||
|
static create(type, flag = false) {
|
||||||
|
return (!flag) ? new Option(type) : new Flag(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} n @returns {Option} */
|
||||||
|
setName(n) { this.name = n; this.aliases[0] = n; return this; }
|
||||||
|
/** @param {string} d @returns {Option} */
|
||||||
|
setDescription(d) { this.description = d; return this; }
|
||||||
|
/** @param {boolean} r @returns {Option} */
|
||||||
|
setRequired(r) { this.required = r; return this; }
|
||||||
|
/** @param {string} id @returns {Option} */
|
||||||
|
setId(id) { this.id = id; return this; }
|
||||||
|
/** @param {string} t @returns {Option} */
|
||||||
|
setType(t) { this.type = t; return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add flag aliases (e.g. "v" for "-v").
|
||||||
|
* @param {...string} a
|
||||||
|
* @returns {Option}
|
||||||
|
*/
|
||||||
|
addFlagAliases(...a) { this.aliases.push(...a); return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add a single valid choice value (choice options only).
|
||||||
|
* @param {string} c
|
||||||
|
* @returns {Option}
|
||||||
|
* @throws {Error} If option type is not "choice".
|
||||||
|
*/
|
||||||
|
addChoice(c) {
|
||||||
|
if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!");
|
||||||
|
this.choices.push(c);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add multiple valid choice values (choice options only).
|
||||||
|
* @param {...string} cs
|
||||||
|
* @returns {Option}
|
||||||
|
* @throws {Error} If option type is not "choice".
|
||||||
|
*/
|
||||||
|
addChoices(...cs) {
|
||||||
|
if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!");
|
||||||
|
cs.forEach(c => this.addChoice(c));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the default value used when the option is omitted.
|
||||||
|
* @param {*} value
|
||||||
|
* @returns {Option}
|
||||||
|
*/
|
||||||
|
setDefault(value) { this.defaultValue = value; return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set a dynamic default resolver function (called with (client, msg)).
|
||||||
|
* @param {Function} callback
|
||||||
|
* @returns {Option}
|
||||||
|
*/
|
||||||
|
setDynamicDefault(callback) { this.dynamicDefault = callback; return this; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether a value is considered empty/omitted.
|
||||||
|
* @param {*} i
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
empty(i) {
|
||||||
|
if (i === undefined || i === null) return true;
|
||||||
|
return (!i && !(String(i).includes("0")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate an input value for this option type.
|
||||||
|
* @param {*} i
|
||||||
|
* @param {object} client
|
||||||
|
* @param {object} msg
|
||||||
|
* @param {string} [type]
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
validateInput(i, client, msg, type) {
|
||||||
|
switch (type || this.type) {
|
||||||
|
case "text":
|
||||||
|
case "string":
|
||||||
|
return !!i;
|
||||||
|
case "number":
|
||||||
|
return !isNaN(i) && !isNaN(parseFloat(i));
|
||||||
|
case "boolean":
|
||||||
|
return i === "0" || i === "1" || i?.toLowerCase() === "true" || i?.toLowerCase() === "false";
|
||||||
|
case "choice":
|
||||||
|
return this.choices.includes(i);
|
||||||
|
case "user":
|
||||||
|
return this.userRegex.test(i) || this.idRegex.test(i);
|
||||||
|
case "channel":
|
||||||
|
if (i === undefined) return false;
|
||||||
|
return this.channelRegex.test(i) || this.idRegex.test(i) || client.channels.some(c => c.name === i);
|
||||||
|
case "voiceChannel": {
|
||||||
|
if (!i) return false;
|
||||||
|
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||||
|
const voiceTypes = [2, 13];
|
||||||
|
const byName = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
|
||||||
|
const cObj = results
|
||||||
|
? client.channels.get(results.groups["id"])
|
||||||
|
: (byName ?? null);
|
||||||
|
return cObj ? voiceTypes.includes(cObj.type) : false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format/parse an input value into its canonical form (IDs for mentions,
|
||||||
|
* numbers for numeric options, booleans for bools).
|
||||||
|
* @param {*} i
|
||||||
|
* @param {object} client
|
||||||
|
* @param {object} msg
|
||||||
|
* @param {string} [type]
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
|
formatInput(i, client, msg, type) {
|
||||||
|
switch (type || this.type) {
|
||||||
|
case "text":
|
||||||
|
case "string":
|
||||||
|
return i;
|
||||||
|
case "number":
|
||||||
|
return parseFloat(i);
|
||||||
|
case "boolean":
|
||||||
|
return i?.toLowerCase() === "true" || i === "1";
|
||||||
|
case "choice":
|
||||||
|
return i;
|
||||||
|
case "user": {
|
||||||
|
const rs = this.userRegex.exec(i) ?? this.idRegex.exec(i);
|
||||||
|
return rs?.groups["id"] ?? null;
|
||||||
|
}
|
||||||
|
case "channel": {
|
||||||
|
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||||
|
const channel = client.channels.find(c => c.name === i);
|
||||||
|
return results ? results.groups["id"] : (channel ? channel.id : null);
|
||||||
|
}
|
||||||
|
case "voiceChannel": {
|
||||||
|
const r = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||||
|
const guildId = msg?.channel?.guildId ?? msg?.guildId;
|
||||||
|
if (guildId === "eval") return r ? r.groups["id"] : (i || null);
|
||||||
|
const voiceTypes = [2, 13];
|
||||||
|
const c = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
|
||||||
|
return r ? r.groups["id"] : (c ? c.id : null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a type-error message template for this option.
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
get typeError() {
|
||||||
|
if (this.tError) return this.tError;
|
||||||
|
switch (this.type) {
|
||||||
|
case "choice": {
|
||||||
|
const choiceStr = this.choices.length > Option.THRESHOLD
|
||||||
|
? Option.formatChoicesCompact(this.choices)
|
||||||
|
: this.choices.map(c => '- ' + c).join('\n');
|
||||||
|
return "Invalid value '$currValue'. The option `" + this.name + "` has to be one of the following: \n" + choiceStr + "\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||||
|
}
|
||||||
|
case "voiceChannel":
|
||||||
|
case "channel":
|
||||||
|
return "Invalid value '$currValue'. The option `" + this.name + "` has to be a channel mention, id, or name.\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||||
|
default:
|
||||||
|
return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param {string} e */
|
||||||
|
set typeError(e) { this.tError = e; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class Flag
|
||||||
|
* @description A dashed (`-name`) option. Flags cannot be of type "text".
|
||||||
|
* @extends Option
|
||||||
|
*/
|
||||||
|
export class Flag extends Option {
|
||||||
|
/**
|
||||||
|
* @param {string} [type="string"]
|
||||||
|
* @throws {Error} If type is "text".
|
||||||
|
*/
|
||||||
|
constructor(type = "string") {
|
||||||
|
if (type === "text") throw new Error("Flags can't be of type 'text'!");
|
||||||
|
super(type);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/**
|
||||||
|
* @module src/commands/PrefixManager
|
||||||
|
* @description Per-guild command prefix resolution (guild setting → config → "%").
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class PrefixManager
|
||||||
|
* @description Manages per-guild command prefixes, falling back to the
|
||||||
|
* configured prefix and finally to "%".
|
||||||
|
*/
|
||||||
|
export class PrefixManager {
|
||||||
|
/** @type {import('../db/Settings.mjs').RemoteSettingsManager} */
|
||||||
|
settings;
|
||||||
|
/** @type {string|null} */
|
||||||
|
configPrefix;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {import('../db/Settings.mjs').RemoteSettingsManager} settings
|
||||||
|
* @param {string|null} [configPrefix=null]
|
||||||
|
*/
|
||||||
|
constructor(settings, configPrefix = null) {
|
||||||
|
this.settings = settings;
|
||||||
|
this.configPrefix = configPrefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the command prefix for a guild.
|
||||||
|
* @param {string} guildId
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
getPrefix(guildId) {
|
||||||
|
const serverPrefix = this.settings.getServer(guildId).get("prefix");
|
||||||
|
return serverPrefix ?? this.configPrefix ?? "%";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
/**
|
||||||
|
* @module src/commands
|
||||||
|
* @description Public surface of the command framework layer.
|
||||||
|
*
|
||||||
|
* Import map from the old layout:
|
||||||
|
* - `src/CommandHandler.mjs` → this module
|
||||||
|
*/
|
||||||
|
|
||||||
|
export { CommandBuilder, CommandRequirement } from "./CommandBuilder.mjs";
|
||||||
|
export { Option, Flag } from "./Option.mjs";
|
||||||
|
export { PrefixManager } from "./PrefixManager.mjs";
|
||||||
|
export { HelpHandler } from "./HelpHandler.mjs";
|
||||||
|
export { CommandHandler } from "./CommandHandler.mjs";
|
||||||
|
export { CommandLoader } from "./CommandLoader.mjs";
|
||||||
@@ -5,7 +5,7 @@ import { logger } from "./Logger.mjs";
|
|||||||
/**
|
/**
|
||||||
* Iterate over a guild's voice states, normalising different data shapes.
|
* Iterate over a guild's voice states, normalising different data shapes.
|
||||||
* Yields objects with `{ userId, channelId, isBot }` for each member in a voice channel.
|
* Yields objects with `{ userId, channelId, isBot }` for each member in a voice channel.
|
||||||
* @param {object} guild - Discord guild object with a `voice_states` property.
|
* @param {object} guild - Fluxer guild object with a `voice_states` property.
|
||||||
* @yields {{ userId: string, channelId: string, isBot: boolean }}
|
* @yields {{ userId: string, channelId: string, isBot: boolean }}
|
||||||
*/
|
*/
|
||||||
export function* iterateVoiceStates(guild) {
|
export function* iterateVoiceStates(guild) {
|
||||||
@@ -49,7 +49,7 @@ export function* iterateVoiceStates(guild) {
|
|||||||
* @param {object} opts
|
* @param {object} opts
|
||||||
* @param {string} opts.guildId
|
* @param {string} opts.guildId
|
||||||
* @param {string} opts.channelId
|
* @param {string} opts.channelId
|
||||||
* @param {object} [opts.client] - Discord client with `guilds`.
|
* @param {object} [opts.client] - Fluxer client with `guilds`.
|
||||||
* @param {VoiceStateCache} [opts.voiceCache]
|
* @param {VoiceStateCache} [opts.voiceCache]
|
||||||
* @param {Map} [opts.observedVoiceUsers]
|
* @param {Map} [opts.observedVoiceUsers]
|
||||||
* @param {object} [opts.room] - LiveKit room with `remoteParticipants`.
|
* @param {object} [opts.room] - LiveKit room with `remoteParticipants`.
|
||||||
@@ -112,7 +112,7 @@ export function hasHumansInChannel({ guildId, channelId, client, voiceCache, obs
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the set of channel IDs that contain at least one human user.
|
* Get the set of channel IDs that contain at least one human user.
|
||||||
* @param {object} guild - Discord guild object.
|
* @param {object} guild - Fluxer guild object.
|
||||||
* @returns {Set<string>}
|
* @returns {Set<string>}
|
||||||
*/
|
*/
|
||||||
export function getChannelsWithHumans(guild) {
|
export function getChannelsWithHumans(guild) {
|
||||||
@@ -125,7 +125,7 @@ export function getChannelsWithHumans(guild) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the list of user IDs present in a specific voice channel.
|
* Get the list of user IDs present in a specific voice channel.
|
||||||
* @param {object} guild - Discord guild object.
|
* @param {object} guild - Fluxer guild object.
|
||||||
* @param {string} channelId
|
* @param {string} channelId
|
||||||
* @returns {string[]}
|
* @returns {string[]}
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,588 @@
|
|||||||
|
/**
|
||||||
|
* @module src/core/Bot
|
||||||
|
* @description The Remix bot class: config loading, client construction,
|
||||||
|
* service wiring (settings, commands, players, gateway, dashboard, Last.fm,
|
||||||
|
* FluxerList, track options), presence rotation, alone-check loop, and
|
||||||
|
* WebSocket error guards. Channel/voice operations live in BotVoiceMixin.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import * as fs from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
import childProcess from "node:child_process";
|
||||||
|
import { Client, Events } from "@fluxerjs/core";
|
||||||
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
|
import { initLogger, logger, _wsErrorCooldown } from "./Logger.mjs";
|
||||||
|
import { Locale } from "./Locale.mjs";
|
||||||
|
import { CommandHandler, CommandLoader, PrefixManager } from "../commands/index.mjs";
|
||||||
|
import { MessageHandler, HelpCommand, setGlobalColor } from "../ui/index.mjs";
|
||||||
|
import { cleanId } from "../utils/Utils.mjs";
|
||||||
|
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
|
||||||
|
import { RemoteSettingsManager } from "../db/Settings.mjs";
|
||||||
|
import { PlayerManager } from "../music/PlayerManager.mjs";
|
||||||
|
import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
||||||
|
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||||
|
import { VoiceStateCache } from "../voice/VoiceStateCache.mjs";
|
||||||
|
import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
|
||||||
|
import { LastFmManager } from "../services/lastfm/LastFmManager.mjs";
|
||||||
|
import { FluxerListManager } from "../services/FluxerListManager.mjs";
|
||||||
|
import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs";
|
||||||
|
import { applyMixins } from "../utils/mixins.mjs";
|
||||||
|
import BotVoiceMixin from "./BotVoiceMixin.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a Map-like view object that proxies bot voice-state lookups through
|
||||||
|
* the VoiceStateCache's bot-specific methods.
|
||||||
|
* @param {VoiceStateCache} voiceCache
|
||||||
|
* @returns {Map}
|
||||||
|
*/
|
||||||
|
function createBotView(voiceCache) {
|
||||||
|
return {
|
||||||
|
get size() { return voiceCache.botLocations.size; },
|
||||||
|
get(key) { return voiceCache.botLocations.get(key); },
|
||||||
|
set(key, val) { return voiceCache.setBotUser(key, val); },
|
||||||
|
has(key) { return voiceCache.botLocations.has(key); },
|
||||||
|
delete(key) { return voiceCache.deleteBotUser(key); },
|
||||||
|
forEach(fn) { for (const [k, v] of voiceCache.iterateBotUsers()) fn(v, k, this); },
|
||||||
|
*[Symbol.iterator]() { yield* voiceCache.iterateBotUsers(); },
|
||||||
|
*entries() { yield* voiceCache.iterateBotUsers(); },
|
||||||
|
*keys() { for (const [k] of voiceCache.iterateBotUsers()) yield k; },
|
||||||
|
*values() { for (const [, v] of voiceCache.iterateBotUsers()) yield v; },
|
||||||
|
get observedVoiceBotsSize() { return voiceCache.botLocations.size; },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a runtime presence update payload from a config entry (string or
|
||||||
|
* object with text/emoji/activity).
|
||||||
|
* @param {string|object} entry
|
||||||
|
* @returns {object}
|
||||||
|
*/
|
||||||
|
function buildRuntimePresence(entry) {
|
||||||
|
const isObj = typeof entry === "object" && entry !== null;
|
||||||
|
const customStatus = {};
|
||||||
|
if (isObj) {
|
||||||
|
if (entry.text) customStatus.text = entry.text;
|
||||||
|
if (entry.emoji_name) customStatus.emojiName = entry.emoji_name;
|
||||||
|
if (entry.emoji_id) customStatus.emojiId = entry.emoji_id;
|
||||||
|
} else {
|
||||||
|
customStatus.text = String(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
const update = { status: "online", afk: false, customStatus };
|
||||||
|
|
||||||
|
if (isObj && entry.activity) {
|
||||||
|
update.activities = [{
|
||||||
|
name: entry.activity.name ?? "music",
|
||||||
|
type: entry.activity.type ?? 0,
|
||||||
|
url: entry.activity.url ?? undefined,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
return update;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class Remix
|
||||||
|
* @description Main bot class. Orchestrates client, settings, players,
|
||||||
|
* lavalink, gateway events, commands, and 24/7 voice channel management.
|
||||||
|
*/
|
||||||
|
class Remix {
|
||||||
|
/**
|
||||||
|
* Bootstrap the entire bot: load config, create the Fluxer client,
|
||||||
|
* initialise settings/commands/players/dashboard, set up event handlers,
|
||||||
|
* load modules, and log in.
|
||||||
|
*/
|
||||||
|
constructor() {
|
||||||
|
let config;
|
||||||
|
try {
|
||||||
|
config = JSON.parse(fs.readFileSync("config.json", "utf8"));
|
||||||
|
} catch (e) {
|
||||||
|
const reason = e.code === "ENOENT"
|
||||||
|
? "config.json not found. Copy config_example.json → config.json and fill in your values."
|
||||||
|
: `config.json is malformed JSON: ${e.message}`;
|
||||||
|
console.error(`[Startup] FATAL: ${reason}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const REQUIRED_KEYS = ["token", "mysql"];
|
||||||
|
for (const key of REQUIRED_KEYS) {
|
||||||
|
if (config[key] == null) {
|
||||||
|
console.error(`[Startup] FATAL: config.json is missing required key "${key}".`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.config = config;
|
||||||
|
|
||||||
|
setGlobalColor(config.embedColor);
|
||||||
|
|
||||||
|
this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
|
||||||
|
this.locale.load();
|
||||||
|
|
||||||
|
this.dashboard = new Dashboard(this, {
|
||||||
|
enabled: config.dashboard?.enabled,
|
||||||
|
redis: config.dashboard?.redis,
|
||||||
|
mysql: config.mysql,
|
||||||
|
});
|
||||||
|
|
||||||
|
const presenceContents = config.presenceContents ?? [];
|
||||||
|
const presenceInterval = config.presenceInterval ?? 30_000;
|
||||||
|
|
||||||
|
let presenceRotationIndex = presenceContents.length > 1 ? 1 : 0;
|
||||||
|
let presenceRotationStarted = false;
|
||||||
|
let wsHandlerRearmStarted = false;
|
||||||
|
|
||||||
|
const timers = config.timers ?? {};
|
||||||
|
this.T = {
|
||||||
|
aloneCheckInterval: timers.aloneCheckInterval ?? 60_000,
|
||||||
|
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
|
||||||
|
rejoin247Delay: timers.rejoin247Delay ?? 3_000,
|
||||||
|
leave247RejoinDelay: timers.leave247RejoinDelay ?? 5_000,
|
||||||
|
intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fluxer 3.0: ClientOptions.presence is the normalized PresenceUpdateOptions
|
||||||
|
// shape (customStatus/emojiName/emojiId) — the 2.2 wire format
|
||||||
|
// (custom_status) is no longer read here. buildRuntimePresence() outputs
|
||||||
|
// exactly the normalized shape, so the initial presence reuses it.
|
||||||
|
const client = new Client({
|
||||||
|
waitForGuilds: true,
|
||||||
|
cache: { guilds: false, channels: false, users: false, members: false },
|
||||||
|
...config["fluxer.js"],
|
||||||
|
presence: presenceContents.length === 0 ? undefined : buildRuntimePresence(presenceContents[0]),
|
||||||
|
});
|
||||||
|
|
||||||
|
client.setMaxListeners(50);
|
||||||
|
this.client = client;
|
||||||
|
|
||||||
|
try {
|
||||||
|
getVoiceManager(client);
|
||||||
|
logger.player("[Startup] VoiceManager initialized before login.");
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Startup] VoiceManager pre-login init failed:", e.message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const messages = new MessageHandler(this.client);
|
||||||
|
this.messages = messages;
|
||||||
|
|
||||||
|
const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
|
||||||
|
this.settingsMgr = settings;
|
||||||
|
|
||||||
|
const configPrefix = config.prefix ?? null;
|
||||||
|
if (configPrefix && settings.defaults) {
|
||||||
|
settings.defaults.prefix = configPrefix;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.locale.bind(this.settingsMgr);
|
||||||
|
|
||||||
|
const commands = new CommandHandler(messages, configPrefix);
|
||||||
|
this.handler = commands;
|
||||||
|
|
||||||
|
const prefixMgr = new PrefixManager(settings, configPrefix);
|
||||||
|
commands.setPrefixManager(prefixMgr);
|
||||||
|
commands.setLocale(this.locale);
|
||||||
|
messages.setLocale(this.locale);
|
||||||
|
this.locale.setPrefixResolver((guildId) => commands.getPrefix(guildId));
|
||||||
|
|
||||||
|
new HelpCommand(commands, messages, (msg) => this.getSettings(msg)).register();
|
||||||
|
|
||||||
|
commands.onPing = (msg) => {
|
||||||
|
msg.replyEmbed(
|
||||||
|
this.handler.format(
|
||||||
|
"My prefix in this server is `$prefix`\n\nRun `$prefix$helpCmd` to get started!",
|
||||||
|
msg.message.guildId
|
||||||
|
),
|
||||||
|
false,
|
||||||
|
{
|
||||||
|
icon_url: msg.channel.channel.guild?.icon
|
||||||
|
? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp`
|
||||||
|
: null,
|
||||||
|
title: msg.channel.channel.guild?.name ?? null,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
};
|
||||||
|
commands.owners = config.owners ?? [];
|
||||||
|
|
||||||
|
this.lavalink = null;
|
||||||
|
let lavalinkInitialised = false;
|
||||||
|
|
||||||
|
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
|
||||||
|
|
||||||
|
this.observedVoiceUsers = this.voiceCache;
|
||||||
|
this.observedVoiceBots = createBotView(this.voiceCache);
|
||||||
|
|
||||||
|
this._announcementChannelCache = new Map();
|
||||||
|
this._announcementChannelTTL = 5 * 60 * 1000;
|
||||||
|
setInterval(() => {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const [k, v] of this._announcementChannelCache) {
|
||||||
|
if (v.timestamp && now - v.timestamp > this._announcementChannelTTL) this._announcementChannelCache.delete(k);
|
||||||
|
}
|
||||||
|
}, 60_000);
|
||||||
|
this.intentionalLeaves = new Map();
|
||||||
|
|
||||||
|
this.gatewayHandler = new GatewayHandler(this);
|
||||||
|
this.gatewayHandler.setupEventHandlers();
|
||||||
|
|
||||||
|
this.lastfm = new LastFmManager(config.lastfm, config.mysql);
|
||||||
|
this.fluxerlist = new FluxerListManager(config.fluxerlist);
|
||||||
|
this.trackOptions = new TrackOptionsManager(config.mysql);
|
||||||
|
|
||||||
|
settings.on("ready", () => this._onSettingsReady());
|
||||||
|
|
||||||
|
client.on(Events.Ready, async () => {
|
||||||
|
try {
|
||||||
|
logger.player("Logged in as " + (client.user?.username ?? "bot"));
|
||||||
|
|
||||||
|
this._attachWsErrorHandlers();
|
||||||
|
|
||||||
|
if (!wsHandlerRearmStarted) {
|
||||||
|
wsHandlerRearmStarted = true;
|
||||||
|
setInterval(() => {
|
||||||
|
this._attachWsErrorHandlers();
|
||||||
|
this.gatewayHandler.attachRawListener();
|
||||||
|
}, 5_000).unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
const botId = client.user?.id ?? "0";
|
||||||
|
|
||||||
|
await this.settingsMgr.setBotId(botId);
|
||||||
|
await this.lastfm.setBotId(botId);
|
||||||
|
this.dashboard.setBotId(botId);
|
||||||
|
this.trackOptions.setBotId(botId);
|
||||||
|
|
||||||
|
if (!lavalinkInitialised) {
|
||||||
|
lavalinkInitialised = true;
|
||||||
|
this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" });
|
||||||
|
this.lavalink.on("ready", () => {
|
||||||
|
logger.lavalink("[Lavalink] Session ready");
|
||||||
|
});
|
||||||
|
await this.lavalink.init();
|
||||||
|
this.playerContext.lavalink = this.lavalink;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.gatewayHandler.onReady();
|
||||||
|
|
||||||
|
if (!presenceRotationStarted && presenceContents.length > 1) {
|
||||||
|
presenceRotationStarted = true;
|
||||||
|
setInterval(() => {
|
||||||
|
try {
|
||||||
|
const entry = presenceContents[presenceRotationIndex % presenceContents.length];
|
||||||
|
client.user?.setPresence(buildRuntimePresence(entry));
|
||||||
|
presenceRotationIndex = (presenceRotationIndex + 1) % presenceContents.length;
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Presence] Rotation update failed:", e?.message);
|
||||||
|
}
|
||||||
|
}, presenceInterval).unref?.();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.error("[Ready] Fatal error in Ready handler:", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
client._remix = this;
|
||||||
|
|
||||||
|
this.playerContext = {
|
||||||
|
client: this.client,
|
||||||
|
config,
|
||||||
|
lavalink: null,
|
||||||
|
};
|
||||||
|
this.players = new PlayerManager(settings, commands, {
|
||||||
|
config,
|
||||||
|
player: this.playerContext,
|
||||||
|
dashboard: this.dashboard,
|
||||||
|
locale: this.locale,
|
||||||
|
timers: this.T,
|
||||||
|
trackOptions: this.trackOptions,
|
||||||
|
});
|
||||||
|
this.players.observedVoiceUsers = this.observedVoiceUsers;
|
||||||
|
this.players.voiceCache = this.voiceCache;
|
||||||
|
this.players._lastfm = this.lastfm;
|
||||||
|
|
||||||
|
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
|
||||||
|
setInterval(() => this._runAloneCheck(), ALONE_CHECK_INTERVAL);
|
||||||
|
|
||||||
|
this.players.checkVoiceChannels = (message) => this._checkVoiceChannelsImpl(message);
|
||||||
|
|
||||||
|
const __dirname = import.meta.dirname;
|
||||||
|
try {
|
||||||
|
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();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Git] comhash error:", e?.message);
|
||||||
|
this.comHash = "Newest";
|
||||||
|
this.comHashLong = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
||||||
|
|
||||||
|
const loader = new CommandLoader(commands, this);
|
||||||
|
const dir = path.join(__dirname, "..", "..", "commands");
|
||||||
|
logger.commands("Started loading commands.");
|
||||||
|
loader.loadFromDir(dir)
|
||||||
|
.then(() => logger.commands("Commands loaded."))
|
||||||
|
.catch(e => logger.error("Failed to load commands:", e));
|
||||||
|
|
||||||
|
logger.commands("Loading Modules.");
|
||||||
|
this.loadedModules = new Map();
|
||||||
|
try {
|
||||||
|
this.modules = JSON.parse(fs.readFileSync("./storage/modules.json"));
|
||||||
|
} catch (e) {
|
||||||
|
const reason = e.code === "ENOENT"
|
||||||
|
? "storage/modules.json not found."
|
||||||
|
: `storage/modules.json is malformed JSON: ${e.message}`;
|
||||||
|
console.error(`[Startup] WARN: ${reason} — starting with no modules.`);
|
||||||
|
this.modules = [];
|
||||||
|
}
|
||||||
|
Promise.allSettled(this.modules.map(async m => {
|
||||||
|
if (!m.enabled) return;
|
||||||
|
try {
|
||||||
|
const exported = await import(m.index);
|
||||||
|
const ModClass = exported.default;
|
||||||
|
this.loadedModules.set(m.name, { instance: new ModClass(this), c: ModClass });
|
||||||
|
} catch (e) {
|
||||||
|
logger.error(`[Module] Failed to load "${m.name}":`, e.message);
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.then(results => {
|
||||||
|
const succeeded = results.filter(r => r.status === "fulfilled").length;
|
||||||
|
const failed = results.length - succeeded;
|
||||||
|
logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Fluxer.js 3.0 sharding (opt-in, root `shard.mjs`): a child forked by a
|
||||||
|
// ShardingManager attaches the child-side ShardClientUtil BEFORE login —
|
||||||
|
// it applies FLUXER_SHARD_IDS/FLUXER_SHARD_COUNT to the client options
|
||||||
|
// and routes IDENTIFYs through the parent's shared per-IP budget — then
|
||||||
|
// reports readiness so the supervisor's spawn() promise resolves.
|
||||||
|
const startLogin = async () => {
|
||||||
|
if (ShardingUtils.isShardedProcess()) {
|
||||||
|
try {
|
||||||
|
const { attachShardClientUtil } = await import("@fluxerjs/sharding");
|
||||||
|
this.shardUtil = attachShardClientUtil(client);
|
||||||
|
logger.player(
|
||||||
|
`[Startup] Sharding child attached — ${ShardingUtils.describeSharding(client)}.`
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
// Fatal: without the shard slice this child would identify as shard 0
|
||||||
|
// like every other child and thrash the gateway sessions.
|
||||||
|
logger.error(
|
||||||
|
"[Startup] FATAL: running under a ShardingManager but the sharding attach failed:",
|
||||||
|
e?.message
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await client.login(config.token);
|
||||||
|
if (this.shardUtil) {
|
||||||
|
try { this.shardUtil.notifyReady(); }
|
||||||
|
catch (e) { logger.warn("[Startup] Sharding ready report failed:", e?.message); }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
startLogin().catch(e => {
|
||||||
|
logger.error("[Startup] Login failed:", e?.message ?? e);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings-ready handler: initialise the logger and normalise stay_247
|
||||||
|
* values (single channel per guild, cleaned IDs).
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_onSettingsReady() {
|
||||||
|
initLogger(this.config);
|
||||||
|
logger.settings("[settings] Loaded from DB.");
|
||||||
|
for (const [guildId, serverSettings] of this.settingsMgr.guilds) {
|
||||||
|
const val = serverSettings.get("stay_247");
|
||||||
|
if (!val || val === "none") continue;
|
||||||
|
const rawArr = Array.isArray(val) ? val : [val];
|
||||||
|
const cleaned = rawArr
|
||||||
|
.map(id => cleanId(id))
|
||||||
|
.filter(id => id.length >= 15 && id.length <= 22);
|
||||||
|
|
||||||
|
if (cleaned.length > 1) {
|
||||||
|
// Only 1 channel per guild supported. Keep first, drop the rest.
|
||||||
|
serverSettings.set("stay_247", cleaned.slice(0, 1));
|
||||||
|
logger.settings(
|
||||||
|
`[settings] Trimmed stay_247 for guild ${guildId}: had ${cleaned.length} channels, kept first 1.`
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val);
|
||||||
|
if (needsSave || !Array.isArray(val)) {
|
||||||
|
const newVal = cleaned.length > 0 ? cleaned : "none";
|
||||||
|
serverSettings.set("stay_247", newVal);
|
||||||
|
logger.settings(
|
||||||
|
`[settings] Cleaned stay_247 for guild ${guildId}: ${JSON.stringify(val)} → ${JSON.stringify(newVal)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Periodic alone-check: for every active player, when no humans remain in
|
||||||
|
* the channel, either arm the inactivity timer (music still queued) or
|
||||||
|
* emit autoleave.
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_runAloneCheck() {
|
||||||
|
if (this.players.playerMap.size === 0) return;
|
||||||
|
|
||||||
|
for (const [mapKey, player] of this.players.playerMap) {
|
||||||
|
let channelId;
|
||||||
|
try {
|
||||||
|
if (player._destroyed || player._isJoining) continue;
|
||||||
|
|
||||||
|
const guildId = player._guildId;
|
||||||
|
if (!guildId) continue;
|
||||||
|
|
||||||
|
channelId = player._channelId ?? mapKey;
|
||||||
|
const cleanChanId = cleanId(channelId);
|
||||||
|
if (!cleanChanId) continue;
|
||||||
|
|
||||||
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
|
||||||
|
if (player._is247Enabled()) continue;
|
||||||
|
|
||||||
|
if (!player.connection) continue;
|
||||||
|
|
||||||
|
let hasHuman = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanChanId);
|
||||||
|
|
||||||
|
if (!hasHuman) {
|
||||||
|
try {
|
||||||
|
const guild = this.client?.guilds?.get?.(cleanGuildId);
|
||||||
|
const voiceStates = guild?.voice_states ?? guild?.voiceStates;
|
||||||
|
if (voiceStates) {
|
||||||
|
const entries = Array.isArray(voiceStates)
|
||||||
|
? voiceStates
|
||||||
|
: typeof voiceStates.values === "function"
|
||||||
|
? [...voiceStates.values()]
|
||||||
|
: Object.values(voiceStates);
|
||||||
|
for (const state of entries) {
|
||||||
|
const stateChannel = cleanId(state?.channelId ?? state?.channel_id);
|
||||||
|
if (stateChannel === cleanChanId) {
|
||||||
|
const stateUserId = state?.userId ?? state?.user_id ?? state?.id;
|
||||||
|
const member = guild?.members?.get?.(stateUserId);
|
||||||
|
const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false;
|
||||||
|
if (!isBot) {
|
||||||
|
hasHuman = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[AloneCheck] Voice state check error:", e?.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasHuman) {
|
||||||
|
try {
|
||||||
|
const room = player.connection?.room;
|
||||||
|
if (room?.isConnected && room.remoteParticipants && room.remoteParticipants.size > 0) {
|
||||||
|
hasHuman = true;
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[AloneCheck] LiveKit check error:", e?.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!hasHuman && !player._paused) {
|
||||||
|
if (player.queue?.getCurrent() || !player.queue?.isEmpty()) {
|
||||||
|
player._startInactivityTimer?.();
|
||||||
|
} else {
|
||||||
|
player._stopInactivityTimer?.();
|
||||||
|
player.emit("autoleave");
|
||||||
|
}
|
||||||
|
} else if (hasHuman) {
|
||||||
|
player._stopInactivityTimer?.();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[AloneCheck] Error checking channel", channelId, e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attach proactive error handlers to WebSocket sockets/shards to prevent
|
||||||
|
* unhandled crashes from WebSocket transport errors. Re-armed periodically.
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_attachWsErrorHandlers() {
|
||||||
|
try {
|
||||||
|
const wsManager = this.client?.ws;
|
||||||
|
if (!wsManager) return;
|
||||||
|
|
||||||
|
let attachedNew = false;
|
||||||
|
|
||||||
|
const logWsError = (label, err) => {
|
||||||
|
const now = Date.now();
|
||||||
|
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
|
||||||
|
_wsErrorCooldown.lastLogged = now;
|
||||||
|
logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const attachToSocket = (wsObj, label) => {
|
||||||
|
if (!wsObj) return;
|
||||||
|
if (wsObj._fluxerErrorHandled) return;
|
||||||
|
wsObj._fluxerErrorHandled = true;
|
||||||
|
attachedNew = true;
|
||||||
|
|
||||||
|
if (typeof wsObj.on === "function") {
|
||||||
|
wsObj.on("error", (err) => logWsError(label, err));
|
||||||
|
}
|
||||||
|
if (typeof wsObj.addEventListener === "function") {
|
||||||
|
wsObj.addEventListener("error", (event) => {
|
||||||
|
if (typeof event.preventDefault === "function") event.preventDefault();
|
||||||
|
const err = event?.error ?? event?.message ?? event;
|
||||||
|
logWsError(label, err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const attachToShard = (shard, id) => {
|
||||||
|
if (!shard) return;
|
||||||
|
if (shard._fluxerErrorHandled) return;
|
||||||
|
shard._fluxerErrorHandled = true;
|
||||||
|
attachedNew = true;
|
||||||
|
shard.on("error", (err) => logWsError(`Shard ${id}`, err));
|
||||||
|
if (shard.ws) attachToSocket(shard.ws, `Shard ${id} socket`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Fluxer 3.0: the ws manager exposes shards via getShards() (2.2 used a
|
||||||
|
// `shards` Map property) and a sharded child owns several of them —
|
||||||
|
// attach to every shard connected in this process, not just shard 0.
|
||||||
|
for (const [id, shard] of ShardingUtils.getLocalShards(this.client)) {
|
||||||
|
attachToShard(shard, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wsManager.ws) {
|
||||||
|
attachToSocket(wsManager.ws, "Gateway");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof wsManager.on === "function" && !wsManager._fluxerErrorHandled) {
|
||||||
|
wsManager._fluxerErrorHandled = true;
|
||||||
|
attachedNew = true;
|
||||||
|
wsManager.on("error", ({ shardId, error }) => {
|
||||||
|
logWsError(`WSManager (shard ${shardId})`, error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof wsManager.on === "function" && !wsManager._shardCreateHandled) {
|
||||||
|
wsManager._shardCreateHandled = true;
|
||||||
|
attachedNew = true;
|
||||||
|
wsManager.on("shardCreate", (shard) => {
|
||||||
|
attachToShard(shard, shard.id ?? "?");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attachedNew) {
|
||||||
|
logger.player("[WS] Proactive error handlers attached to gateway sockets.");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[WS] Failed to attach WS error handlers:", e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attach channel/voice operations (spawn, leave, shared servers, helpers).
|
||||||
|
applyMixins(Remix, BotVoiceMixin);
|
||||||
|
|
||||||
|
export { Remix };
|
||||||
|
export default Remix;
|
||||||
@@ -0,0 +1,511 @@
|
|||||||
|
/**
|
||||||
|
* @module src/core/BotVoiceMixin
|
||||||
|
* @description Channel & voice operations for the {@link Remix} bot class:
|
||||||
|
* voice-channel resolution (checkVoiceChannels), 24/7 player spawning with
|
||||||
|
* announcements, programmatic channel leave, shared-server listing, and
|
||||||
|
* small translation/settings/pagination helpers.
|
||||||
|
*
|
||||||
|
* These methods are applied onto the Remix class prototype via
|
||||||
|
* {@link applyMixins} — `this` is a Remix instance.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
|
import { getGlobalColor, PageBuilder } from "../ui/index.mjs";
|
||||||
|
import { cleanId } from "../utils/Utils.mjs";
|
||||||
|
import { remove247ChannelMode } from "../utils/Helpers247.mjs";
|
||||||
|
import { logger } from "./Logger.mjs";
|
||||||
|
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @type {object}
|
||||||
|
* @description Voice/channel mixin — applied to Remix.
|
||||||
|
*/
|
||||||
|
const BotVoiceMixin = {
|
||||||
|
/**
|
||||||
|
* Resolve the user's voice channel for a command invocation. Tries, in
|
||||||
|
* order: the voice-state cache, the VoiceManager, guild voice states, a
|
||||||
|
* cache scan, REST member fetch, and a raw REST member lookup.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @param {object} message - Message wrapper.
|
||||||
|
* @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>}
|
||||||
|
*/
|
||||||
|
async _checkVoiceChannelsImpl(message) {
|
||||||
|
const userId = message?.author?.id ?? message?.message?.author?.id;
|
||||||
|
const guildId =
|
||||||
|
message?.channel?.guildId ??
|
||||||
|
message?.channel?.guild?.id ??
|
||||||
|
message?.channel?.server_id ??
|
||||||
|
message?.channel?.serverId ??
|
||||||
|
message?.message?.guildId ??
|
||||||
|
message?.message?.guild?.id ??
|
||||||
|
message?.message?.channel?.guildId ??
|
||||||
|
message?.message?.channel?.guild?.id ??
|
||||||
|
message?.message?.channel?.server_id ??
|
||||||
|
message?.message?.channel?.serverId;
|
||||||
|
|
||||||
|
const _empty = { channelId: null, alreadyInVoice: false, hasHumans: false };
|
||||||
|
|
||||||
|
if (!userId || !guildId) {
|
||||||
|
logger.voice(`[checkVC] BAIL — missing userId or guildId`);
|
||||||
|
return _empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanGuild = cleanId(guildId);
|
||||||
|
|
||||||
|
const makeResult = (channelId) => {
|
||||||
|
const cId = cleanId(channelId);
|
||||||
|
return {
|
||||||
|
channelId: cId,
|
||||||
|
alreadyInVoice: this.players.playerMap.has(cId),
|
||||||
|
hasHumans: this.voiceCache.hasHumansInChannel(cleanGuild, cId),
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const seedCache = (channelId) => {
|
||||||
|
if (!this.voiceCache.hasHumanUser(userId, cleanGuild)) {
|
||||||
|
this.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
logger.voice(`[checkVC] userId=${userId} guildId=${guildId} cleanGuild=${cleanGuild}`);
|
||||||
|
|
||||||
|
const observed = this.voiceCache.getUserLocation(cleanGuild, userId);
|
||||||
|
if (observed && observed.channelId) {
|
||||||
|
logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`);
|
||||||
|
return makeResult(observed.channelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const vm = getVoiceManager(this.client);
|
||||||
|
const channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? vm?.getVoiceChannelId?.(cleanGuild, userId);
|
||||||
|
logger.voice(`[checkVC] vm.getVoiceChannelId → ${channelId}`);
|
||||||
|
if (channelId) {
|
||||||
|
seedCache(channelId);
|
||||||
|
return makeResult(channelId);
|
||||||
|
}
|
||||||
|
} catch (e) { logger.voice(`[checkVC] vm error: ${e.message}`); }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild);
|
||||||
|
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
||||||
|
if (voiceStates) {
|
||||||
|
const entries = Array.isArray(voiceStates)
|
||||||
|
? voiceStates
|
||||||
|
: typeof voiceStates.values === "function"
|
||||||
|
? [...voiceStates.values()]
|
||||||
|
: Object.values(voiceStates);
|
||||||
|
for (const state of entries) {
|
||||||
|
const sid = state?.userId ?? state?.user_id ?? state?.id;
|
||||||
|
const sch = state?.channelId ?? state?.channel_id;
|
||||||
|
if ((sid === userId || sid === cleanId(userId)) && sch) {
|
||||||
|
logger.voice(`[checkVC] HIT guild.voice_states → ${sch}`);
|
||||||
|
seedCache(sch);
|
||||||
|
return makeResult(sch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const loc = this.voiceCache.getHumanUser(userId, cleanGuild);
|
||||||
|
if (loc && loc.channelId) {
|
||||||
|
logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`);
|
||||||
|
return makeResult(loc.channelId);
|
||||||
|
}
|
||||||
|
} catch (e) { logger.voice(`[checkVC] scan error: ${e.message}`); }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild);
|
||||||
|
if (guild && typeof guild.fetchMember === "function") {
|
||||||
|
logger.voice(`[checkVC] Trying REST fetchMember fallback for user ${userId}`);
|
||||||
|
const member = await guild.fetchMember(userId);
|
||||||
|
const voiceState = member?.voice ?? member?.voiceState ?? null;
|
||||||
|
const restChannelId = voiceState?.channelId ?? voiceState?.channel_id ?? null;
|
||||||
|
if (restChannelId) {
|
||||||
|
logger.voice(`[checkVC] HIT REST member.voice → ${restChannelId}`);
|
||||||
|
seedCache(restChannelId);
|
||||||
|
return makeResult(restChannelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { logger.voice(`[checkVC] REST fallback error: ${e.message}`); }
|
||||||
|
|
||||||
|
try {
|
||||||
|
const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild);
|
||||||
|
if (guild && typeof this.client.rest?.get === "function") {
|
||||||
|
logger.voice(`[checkVC] Trying raw REST /guilds/${cleanGuild}/members/${userId}`);
|
||||||
|
const memberData = await this.client.rest.get(`/guilds/${cleanGuild}/members/${userId}`);
|
||||||
|
const restChannelId = memberData?.voice_state?.channel_id ?? memberData?.channel_id ?? null;
|
||||||
|
if (restChannelId) {
|
||||||
|
logger.voice(`[checkVC] HIT raw REST → ${restChannelId}`);
|
||||||
|
seedCache(restChannelId);
|
||||||
|
return makeResult(restChannelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { logger.voice(`[checkVC] raw REST error: ${e.message}`); }
|
||||||
|
|
||||||
|
logger.voice(`[checkVC] MISS — returning empty`);
|
||||||
|
return _empty;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mark a channel leave as intentional (user-initiated) to prevent the 24/7
|
||||||
|
* auto-rejoin system from rejoining.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @param {string} channelId - The channel ID.
|
||||||
|
* @param {number|null} [ttlMs=null] - TTL in ms (default: config.timers.intentionalLeaveTTL or 10s).
|
||||||
|
*/
|
||||||
|
markIntentionalLeave(channelId, ttlMs = null) {
|
||||||
|
const cleanChId = cleanId(channelId);
|
||||||
|
if (!cleanChId) return;
|
||||||
|
if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000;
|
||||||
|
const existing = this.intentionalLeaves.get(cleanChId);
|
||||||
|
if (existing) clearTimeout(existing);
|
||||||
|
this.intentionalLeaves.set(cleanChId, setTimeout(() => {
|
||||||
|
this.intentionalLeaves.delete(cleanChId);
|
||||||
|
}, ttlMs));
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Spawn a new Player for a channel. Used by 24/7 boot recovery and
|
||||||
|
* enable247. Guards against duplicate players, missing channels, and
|
||||||
|
* pending joins.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @param {string} guildId - The guild ID.
|
||||||
|
* @param {string} channelId - The target voice channel ID.
|
||||||
|
* @returns {Promise<import('../music/player/Player.mjs').Player>}
|
||||||
|
* @throws {Error} If channel not found, not a voice channel, or join fails.
|
||||||
|
*/
|
||||||
|
async _spawnPlayer(guildId, channelId) {
|
||||||
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
const cleanChannelId = cleanId(channelId);
|
||||||
|
|
||||||
|
if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId");
|
||||||
|
|
||||||
|
const existing = this.players.playerMap.get(cleanChannelId)
|
||||||
|
?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId);
|
||||||
|
if (existing) return existing;
|
||||||
|
|
||||||
|
if (!this.lavalink) throw new Error("Audio node not ready yet — try again in a moment");
|
||||||
|
|
||||||
|
const channel = this.client?.channels?.get?.(cleanChannelId);
|
||||||
|
if (!channel) throw new Error("Channel not found");
|
||||||
|
if (channel.type !== 2) throw new Error("Not a voice channel");
|
||||||
|
|
||||||
|
if (this.players._pendingJoins?.has?.(cleanChannelId)) {
|
||||||
|
throw new Error("Join already in progress for this channel");
|
||||||
|
}
|
||||||
|
|
||||||
|
const Player = (await import("../music/player/index.mjs")).default;
|
||||||
|
|
||||||
|
const player = new Player(this.config.token, {
|
||||||
|
client: this.client,
|
||||||
|
config: this.config,
|
||||||
|
lavalink: this.lavalink ?? null,
|
||||||
|
settingsMgr: this.settingsMgr ?? this.settings ?? null,
|
||||||
|
getPrefix: (guildId) => this.handler.getPrefix(guildId),
|
||||||
|
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||||
|
voiceCache: this.voiceCache ?? null,
|
||||||
|
locale: this.locale ?? null,
|
||||||
|
trackOptions: this.trackOptions ?? null,
|
||||||
|
});
|
||||||
|
|
||||||
|
player._home247Channel = cleanChannelId;
|
||||||
|
|
||||||
|
this.players.setupEvents(player, {
|
||||||
|
channelId: cleanChannelId,
|
||||||
|
guildId: cleanGuildId,
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("autoleave", () => {
|
||||||
|
const mode = player._get247Mode();
|
||||||
|
if (mode === "on") {
|
||||||
|
logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 channel ${cleanChannelId} (guild ${cleanGuildId})`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (player._hasHumansInChannel()) {
|
||||||
|
logger.inactivity(`[_spawnPlayer] autoleave suppressed — humans in channel ${cleanChannelId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (player.queue?.getCurrent() || !player.queue?.isEmpty()) {
|
||||||
|
logger.inactivity(`[_spawnPlayer] autoleave suppressed — queue has songs in channel ${cleanChannelId}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeChId = cleanId(player._channelId ?? cleanChannelId) || cleanChannelId;
|
||||||
|
const homeChId = cleanId(player._home247Channel ?? activeChId) || activeChId;
|
||||||
|
this.players.playerMap.delete(activeChId);
|
||||||
|
this.players._unindexPlayer?.(cleanGuildId, activeChId);
|
||||||
|
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId);
|
||||||
|
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChannelId); }
|
||||||
|
if (activeChId !== cleanChannelId) this.players.playerMap.delete(cleanChannelId);
|
||||||
|
if (homeChId !== activeChId) this.players.playerMap.delete(homeChId);
|
||||||
|
player.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("message", async (m) => {
|
||||||
|
try {
|
||||||
|
const serverSettings = this.settingsMgr?.getServer?.(cleanGuildId);
|
||||||
|
const raw = serverSettings?.get?.("songAnnouncements");
|
||||||
|
const disabled = raw === false || raw === 0 ||
|
||||||
|
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
|
||||||
|
if (disabled) return;
|
||||||
|
|
||||||
|
const chMgr = this.client?.channels ?? null;
|
||||||
|
const canPostById = (c) => !!c?.id && !!chMgr && typeof chMgr.send === "function";
|
||||||
|
const asSendable = (c) => {
|
||||||
|
if (!c || typeof c === "string" || typeof c.send === "function") return c;
|
||||||
|
if (!canPostById(c)) return c;
|
||||||
|
const target = { id: c.id, type: c.type };
|
||||||
|
target.isTextBased = () => true;
|
||||||
|
target.send = (options) => chMgr.send(c.id, options);
|
||||||
|
return target;
|
||||||
|
};
|
||||||
|
const usable = (c) => !!c && typeof c === "object" &&
|
||||||
|
(typeof c.send === "function" || canPostById(c));
|
||||||
|
|
||||||
|
const _tc = player.textChannel;
|
||||||
|
let ch = (_tc && typeof _tc === "object" && _tc.channel && typeof _tc.channel === "object")
|
||||||
|
? _tc.channel
|
||||||
|
: _tc;
|
||||||
|
if (!usable(ch)) {
|
||||||
|
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
|
||||||
|
if (savedAnnChId) {
|
||||||
|
ch = this.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!usable(ch)) {
|
||||||
|
const guild = this.client?.guilds?.get?.(cleanGuildId);
|
||||||
|
if (guild?.systemChannelId) {
|
||||||
|
ch = guild.channels?.get?.(guild.systemChannelId) ?? null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!usable(ch)) {
|
||||||
|
const guild = this.client?.guilds?.get?.(cleanGuildId);
|
||||||
|
if (guild?.channels) {
|
||||||
|
for (const c of (guild.channels.values?.() ?? [])) {
|
||||||
|
if (c.isTextBased?.() || c.type === 0 || c.type === "GUILD_TEXT") {
|
||||||
|
ch = c;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!usable(ch)) return;
|
||||||
|
|
||||||
|
ch = asSendable(ch);
|
||||||
|
if (!player.textChannel) player.textChannel = ch;
|
||||||
|
|
||||||
|
const payload = typeof m === "object" && Array.isArray(m.embeds)
|
||||||
|
? { ...m, allowedMentions: { parse: [] } }
|
||||||
|
: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)], allowedMentions: { parse: [] } };
|
||||||
|
ch.send(payload).catch(err => {
|
||||||
|
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||||
|
logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`);
|
||||||
|
} else {
|
||||||
|
logger.warn(`[_spawnPlayer] Failed to send announcement in channel ${ch.id}:`, err?.message ?? err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch(e) {
|
||||||
|
logger.warn("[Player] Song announcement error:", e?.message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (this.players._pendingJoins) {
|
||||||
|
this.players._pendingJoins.add(cleanChannelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await player.join(cleanChannelId);
|
||||||
|
|
||||||
|
this.players.playerMap.set(cleanChannelId, player);
|
||||||
|
this.players._indexPlayer(cleanGuildId, cleanChannelId);
|
||||||
|
if (this.players._pendingJoins) {
|
||||||
|
this.players._pendingJoins.delete(cleanChannelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const savedVol = this.settingsMgr?.getServer?.(cleanGuildId)?.get?.("volume");
|
||||||
|
if (savedVol !== undefined && savedVol !== null) {
|
||||||
|
const vol = Number(savedVol);
|
||||||
|
if (!isNaN(vol)) player.setVolume(vol / 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.player(`[_spawnPlayer] Spawned player for channel ${cleanChannelId} in guild ${cleanGuildId}`);
|
||||||
|
return player;
|
||||||
|
} catch (err) {
|
||||||
|
if (this.players._pendingJoins) {
|
||||||
|
this.players._pendingJoins.delete(cleanChannelId);
|
||||||
|
}
|
||||||
|
this.players.playerMap.delete(cleanChannelId);
|
||||||
|
try { player.destroy(); } catch(e) { logger.warn("[_spawnPlayer] Cleanup destroy error:", e?.message); }
|
||||||
|
logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Leave a voice channel programmatically. Removes 24/7 if active, destroys
|
||||||
|
* the player, and optionally sends a confirmation message.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @param {string} channelId - The channel ID to leave.
|
||||||
|
* @param {string} guildId - The guild ID.
|
||||||
|
* @param {object} [message=null] - Optional message for reply confirmation.
|
||||||
|
* @param {boolean} [force=false] - Whether to force-leave regardless of 24/7 status.
|
||||||
|
* @returns {Promise<boolean>} True on success.
|
||||||
|
*/
|
||||||
|
async leaveChannel(channelId, guildId, message, force = false) {
|
||||||
|
const cleanChId = cleanId(channelId);
|
||||||
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
const set = this.settingsMgr.getServer(cleanGuildId);
|
||||||
|
const raw = set?.get("stay_247");
|
||||||
|
|
||||||
|
const channels = (!raw || raw === "none")
|
||||||
|
? new Set()
|
||||||
|
: Array.isArray(raw)
|
||||||
|
? new Set(raw.map(id => cleanId(id)).filter(Boolean))
|
||||||
|
: new Set([cleanId(raw)]);
|
||||||
|
|
||||||
|
if (channels.has(cleanChId)) {
|
||||||
|
channels.delete(cleanChId);
|
||||||
|
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
|
||||||
|
remove247ChannelMode(set, cleanChId, channels);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.markIntentionalLeave(cleanChId);
|
||||||
|
|
||||||
|
const player = this.players.playerMap.get(cleanChId);
|
||||||
|
if (player) {
|
||||||
|
this.players.playerMap.delete(cleanChId);
|
||||||
|
this.players._unindexPlayer(player._guildId, cleanChId);
|
||||||
|
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChId);
|
||||||
|
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChId); }
|
||||||
|
await player.leave().catch(() => {});
|
||||||
|
player.destroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message) {
|
||||||
|
const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId;
|
||||||
|
message.replyEmbed(this.locale.translate(guildIdForLocale, "responses._common.successfullyLeft"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the server settings for the guild associated with a message.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @param {object} message - The incoming message wrapper.
|
||||||
|
* @returns {object} The ServerSettings for the guild, or a fallback.
|
||||||
|
*/
|
||||||
|
getSettings(message) {
|
||||||
|
const guildId = message?.channel?.channel?.guildId ?? message?.guildId ?? null;
|
||||||
|
return this.settingsMgr.getServer(guildId);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shorthand to translate a locale key for the guild of a given message.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @param {object} message - The message wrapper (used to resolve guild ID).
|
||||||
|
* @param {string} key - The locale key.
|
||||||
|
* @param {object} [data={}] - Interpolation data.
|
||||||
|
* @returns {string} The localised string.
|
||||||
|
*/
|
||||||
|
t(message, key, data = {}) {
|
||||||
|
const guildId = message?.channel?.channel?.guildId
|
||||||
|
?? message?.message?.guildId
|
||||||
|
?? message?.guildId
|
||||||
|
?? null;
|
||||||
|
return this.locale.translate(guildId, key, data);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get or create a player for the given message context.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @param {object} message - The message wrapper.
|
||||||
|
* @param {boolean} promptJoin - Whether to prompt the user to join a voice channel.
|
||||||
|
* @param {boolean} verifyUser - Whether to verify the user is in a voice channel.
|
||||||
|
* @param {boolean} shouldJoin - Whether to auto-join the voice channel.
|
||||||
|
* @returns {Promise<object>} The Player instance.
|
||||||
|
*/
|
||||||
|
getPlayer(message, promptJoin, verifyUser, shouldJoin) {
|
||||||
|
return this.players.getPlayer(message, promptJoin, verifyUser, shouldJoin);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all servers the bot and the given user share (i.e. the user is a
|
||||||
|
* member). Used by the dashboard to determine which servers a user can
|
||||||
|
* manage.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @param {object} user - The Fluxer user.
|
||||||
|
* @returns {Promise<Array<object>>} Array of server summaries with channels.
|
||||||
|
*/
|
||||||
|
async getSharedServers(user) {
|
||||||
|
if (!user) return [];
|
||||||
|
|
||||||
|
const shared = [];
|
||||||
|
|
||||||
|
for (const guild of this.client.guilds?.values?.() ?? []) {
|
||||||
|
let isMember = false;
|
||||||
|
|
||||||
|
if (guild.members?.has?.(user.id)) {
|
||||||
|
isMember = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isMember) {
|
||||||
|
const cleanGuildId = cleanId(guild.id);
|
||||||
|
const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id);
|
||||||
|
if (userLoc) isMember = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isMember) {
|
||||||
|
try {
|
||||||
|
const member = await guild.members.fetch(user.id).catch(() => null);
|
||||||
|
if (member) isMember = true;
|
||||||
|
} catch (e) { logger.warn(`[getSharedServers] Member fetch error for ${user.id}:`, e?.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isMember) continue;
|
||||||
|
|
||||||
|
const guildChannels = guild.channels
|
||||||
|
? [...guild.channels.values()]
|
||||||
|
: [];
|
||||||
|
const allChannels = guildChannels
|
||||||
|
.map(c => Dashboard.convertChannel(c))
|
||||||
|
.filter(c => !c.isCategory);
|
||||||
|
const channelIds = guildChannels.map(c => c.id);
|
||||||
|
|
||||||
|
shared.push({
|
||||||
|
name: guild.name,
|
||||||
|
id: guild.id,
|
||||||
|
icon: guild.icon
|
||||||
|
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
|
||||||
|
: null,
|
||||||
|
description: guild.description ?? null,
|
||||||
|
ownerId: guild.ownerId ?? null,
|
||||||
|
channels: allChannels,
|
||||||
|
channelIds: channelIds,
|
||||||
|
voiceChannels: allChannels.filter(c => c.isVoice),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return shared;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create and attach a paginated message to the given message.
|
||||||
|
* @this {import('./Bot.mjs').Remix}
|
||||||
|
* @param {string} form - The form/locale key for the page title.
|
||||||
|
* @param {string} content - The full content to paginate.
|
||||||
|
* @param {object} msg - The message wrapper.
|
||||||
|
* @param {number} linesPerPage - Maximum lines per page.
|
||||||
|
*/
|
||||||
|
pagination(form, content, msg, linesPerPage) {
|
||||||
|
this.messages.initPagination(
|
||||||
|
new PageBuilder(content).setForm(form).setMaxLines(linesPerPage),
|
||||||
|
msg
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default BotVoiceMixin;
|
||||||
|
export { BotVoiceMixin };
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
/** @module src/core/Locale */
|
||||||
|
|
||||||
|
import { readFileSync, readdirSync, existsSync } from "fs";
|
||||||
|
import path from "path";
|
||||||
|
import { fileURLToPath } from "url";
|
||||||
|
import { logger } from "./Logger.mjs";
|
||||||
|
|
||||||
|
/** @private */
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
/** @private */
|
||||||
|
const LOCALES_DIR = path.resolve(__dirname, "../../storage/locales/bot");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Locale/i18n manager that loads JSON locale files from disk and provides
|
||||||
|
* dot-notation key lookups with `{{placeholder}}` and `$prefix` substitution.
|
||||||
|
* @class
|
||||||
|
*/
|
||||||
|
export class Locale {
|
||||||
|
/**
|
||||||
|
* @param {string} [defaultPrefix="%"] - Fallback prefix used when no prefix
|
||||||
|
* resolver is registered and the settings manager yields no prefix.
|
||||||
|
*/
|
||||||
|
constructor(defaultPrefix = "%") {
|
||||||
|
/** @private */ this.locales = new Map();
|
||||||
|
/** @private */ this._resolved = new Map();
|
||||||
|
/** @type {string} */ this.defaultLocale = "en";
|
||||||
|
/** @private */ this.settingsMgr = null;
|
||||||
|
/** @private */ this._getPrefixFn = null;
|
||||||
|
/** @private */ this._defaultPrefix = defaultPrefix;
|
||||||
|
/** @private */ this._maxResolvedCache = 5000;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bind a settings manager so the locale resolver can look up per-guild locale preferences.
|
||||||
|
* @param {object} settingsMgr - Settings manager exposing `guilds.get(guildId)`.
|
||||||
|
*/
|
||||||
|
bind(settingsMgr) {
|
||||||
|
this.settingsMgr = settingsMgr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load all `.json` locale files from the locales directory.
|
||||||
|
* Clears any previously loaded data and the resolved-cache.
|
||||||
|
*/
|
||||||
|
load() {
|
||||||
|
this.locales.clear();
|
||||||
|
this._resolved.clear();
|
||||||
|
|
||||||
|
if (!existsSync(LOCALES_DIR)) {
|
||||||
|
logger.warn("[Locale] Locales directory not found:", LOCALES_DIR);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let files;
|
||||||
|
try {
|
||||||
|
files = readdirSync(LOCALES_DIR).filter(f => f.endsWith(".json"));
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Locale] Failed to read locales directory:", e.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const file of files) {
|
||||||
|
const filePath = path.join(LOCALES_DIR, file);
|
||||||
|
const code = file.replace(".json", "");
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(readFileSync(filePath, "utf8"));
|
||||||
|
this.locales.set(code, data);
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[Locale] Failed to load " + file + ":", e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("[Locale] Loaded " + this.locales.size + " locale(s): " + [...this.locales.keys()].join(", "));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the set of loaded locale codes.
|
||||||
|
* @returns {Set<string>}
|
||||||
|
*/
|
||||||
|
availableLocales() {
|
||||||
|
return new Set(this.locales.keys());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the locale data object for a guild, using per-guild settings or falling
|
||||||
|
* back to the default locale. Results are cached with an LRU-style cap.
|
||||||
|
* @private
|
||||||
|
* @param {string} guildId
|
||||||
|
* @returns {object} The locale data object.
|
||||||
|
*/
|
||||||
|
_getLocaleData(guildId) {
|
||||||
|
if (!guildId) return this.locales.get(this.defaultLocale) ?? {};
|
||||||
|
|
||||||
|
const cached = this._resolved.get(guildId);
|
||||||
|
if (cached) return cached;
|
||||||
|
|
||||||
|
let code = this.defaultLocale;
|
||||||
|
try {
|
||||||
|
const serverSettings = this.settingsMgr?.guilds?.get?.(guildId);
|
||||||
|
if (serverSettings) {
|
||||||
|
const setting = serverSettings.get("locale");
|
||||||
|
if (setting && this.locales.has(setting)) {
|
||||||
|
code = setting;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[Locale] Error:", e?.message); }
|
||||||
|
|
||||||
|
const data = this.locales.get(code) ?? this.locales.get(this.defaultLocale) ?? {};
|
||||||
|
this._resolved.set(guildId, data);
|
||||||
|
|
||||||
|
while (this._resolved.size > this._maxResolvedCache) {
|
||||||
|
const oldestKey = this._resolved.keys().next().value;
|
||||||
|
this._resolved.delete(oldestKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invalidate the resolved-cache for a specific guild or all guilds.
|
||||||
|
* @param {string} [guildId] - Omit to clear the entire cache.
|
||||||
|
*/
|
||||||
|
invalidateCache(guildId) {
|
||||||
|
if (guildId) {
|
||||||
|
this._resolved.delete(guildId);
|
||||||
|
} else {
|
||||||
|
this._resolved.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register a custom prefix resolver function.
|
||||||
|
* @param {function(string): string} fn - Receives `guildId`, returns the prefix string.
|
||||||
|
*/
|
||||||
|
setPrefixResolver(fn) {
|
||||||
|
this._getPrefixFn = fn;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the command prefix for a guild.
|
||||||
|
* @private
|
||||||
|
* @param {string} guildId
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
_getPrefix(guildId) {
|
||||||
|
if (this._getPrefixFn) return this._getPrefixFn(guildId);
|
||||||
|
try {
|
||||||
|
const serverSettings = this.settingsMgr?.getServer?.(guildId);
|
||||||
|
if (serverSettings) {
|
||||||
|
const prefix = serverSettings.get("prefix");
|
||||||
|
if (prefix) return prefix;
|
||||||
|
}
|
||||||
|
} catch(e) { logger.warn("[Locale] Error:", e?.message); }
|
||||||
|
return this._defaultPrefix || "!";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve a dot-notation key against a nested object.
|
||||||
|
* @private
|
||||||
|
* @param {object} obj
|
||||||
|
* @param {string} key - e.g. "commands.play.description"
|
||||||
|
* @returns {*}
|
||||||
|
*/
|
||||||
|
_resolve(obj, key) {
|
||||||
|
const parts = key.split(".");
|
||||||
|
let current = obj;
|
||||||
|
for (const part of parts) {
|
||||||
|
if (current == null || typeof current !== "object") return undefined;
|
||||||
|
current = current[part];
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Translate a locale key for a guild, applying `{{placeholder}}` replacements
|
||||||
|
* and `$prefix` substitution. Falls back to the default locale, then the raw key.
|
||||||
|
* @param {string} guildId
|
||||||
|
* @param {string} key - Dot-notation locale key.
|
||||||
|
* @param {Object<string, *>} [replacements={}] - Placeholder values to substitute.
|
||||||
|
* @returns {string} The translated (or fallback) string.
|
||||||
|
*/
|
||||||
|
translate(guildId, key, replacements = {}) {
|
||||||
|
const localeData = this._getLocaleData(guildId);
|
||||||
|
|
||||||
|
let value = this._resolve(localeData, key);
|
||||||
|
|
||||||
|
if (value === undefined) {
|
||||||
|
value = this._resolve(this.locales.get(this.defaultLocale) ?? {}, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value === undefined) return key;
|
||||||
|
if (typeof value !== "string") return key;
|
||||||
|
|
||||||
|
for (const [placeholder, val] of Object.entries(replacements)) {
|
||||||
|
const escaped = placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
const replacement = String(val ?? "");
|
||||||
|
value = value.replace(
|
||||||
|
new RegExp(`\\{\\{${escaped}\\}\\}`, "g"),
|
||||||
|
() => replacement
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.includes("$prefix")) {
|
||||||
|
const prefix = this._getPrefix(guildId);
|
||||||
|
value = value.replace(/\$prefix/gi, prefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
/** @module src/core/Logger */
|
||||||
|
|
||||||
|
/** @private */
|
||||||
|
let _config = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initialize the logger with a configuration object.
|
||||||
|
* @param {object} [config] - Application configuration object.
|
||||||
|
* @param {object} [config.logging] - Logging-specific configuration.
|
||||||
|
*/
|
||||||
|
export function initLogger(config) {
|
||||||
|
_config = config?.logging ?? {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether a given log category is enabled.
|
||||||
|
* @private
|
||||||
|
* @param {string} category - The log category name (e.g. "player", "voice").
|
||||||
|
* @returns {boolean} `true` if the category is enabled (or no config is loaded).
|
||||||
|
*/
|
||||||
|
function isEnabled(category) {
|
||||||
|
if (!_config) return true;
|
||||||
|
if (_config.enabled === false) return false;
|
||||||
|
return _config[category] !== false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return an ISO-8601 timestamp string truncated to seconds.
|
||||||
|
* @private
|
||||||
|
* @returns {string} Timestamp in `YYYY-MM-DD HH:MM:SS` format.
|
||||||
|
*/
|
||||||
|
function ts() {
|
||||||
|
return new Date().toISOString().replace("T", " ").slice(0, 19);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cooldown state for WebSocket error logging to avoid spam.
|
||||||
|
* @type {{ lastLogged: number, COOLDOWN_MS: number }}
|
||||||
|
*/
|
||||||
|
export const _wsErrorCooldown = { lastLogged: 0, COOLDOWN_MS: 15_000 };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Log-storm suppression for identical repeated `error`/`warn` lines.
|
||||||
|
* The first occurrence is always emitted; identical repeats within a 60s
|
||||||
|
* window are counted silently, and once per window a single pulse line with
|
||||||
|
* the repeat count is emitted instead. Bounds worst-case volume of any hot
|
||||||
|
* retry loop to one line per minute instead of millions.
|
||||||
|
* @private
|
||||||
|
* @type {Map<string, {n: number, start: number}>}
|
||||||
|
*/
|
||||||
|
const _stormGuard = new Map();
|
||||||
|
const STORM_WINDOW_MS = 60_000;
|
||||||
|
const STORM_MAX_KEYS = 128;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decide whether an error/warn line should be emitted, and with what suffix.
|
||||||
|
* @private
|
||||||
|
* @param {string} level - Log level ("error" | "warn").
|
||||||
|
* @param {string} tag - Caller tag (e.g. "[Redis/Main]").
|
||||||
|
* @param {Array<*>} args - Message arguments.
|
||||||
|
* @returns {{emit: boolean, suffix: string}} Whether to emit, and the pulse suffix.
|
||||||
|
*/
|
||||||
|
function _stormGate(level, tag, args) {
|
||||||
|
const key = level + "|" + tag + "|" + args.map(a => (typeof a === "string" ? a : String(a))).join(" ");
|
||||||
|
const now = Date.now();
|
||||||
|
const st = _stormGuard.get(key);
|
||||||
|
if (st === undefined) {
|
||||||
|
if (_stormGuard.size >= STORM_MAX_KEYS) {
|
||||||
|
// Evict the oldest key to bound memory.
|
||||||
|
_stormGuard.delete(_stormGuard.keys().next().value);
|
||||||
|
}
|
||||||
|
_stormGuard.set(key, { n: 0, start: now });
|
||||||
|
return { emit: true, suffix: "" };
|
||||||
|
}
|
||||||
|
st.n++;
|
||||||
|
if (now - st.start >= STORM_WINDOW_MS) {
|
||||||
|
const n = st.n;
|
||||||
|
st.n = 0;
|
||||||
|
st.start = now;
|
||||||
|
return { emit: true, suffix: `── identical line suppressed ${n}x in the last 60s` };
|
||||||
|
}
|
||||||
|
return { emit: false, suffix: "" };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reset the log-storm suppression state (used by tests).
|
||||||
|
* @returns {void}
|
||||||
|
*/
|
||||||
|
export function _resetStormGuard() {
|
||||||
|
_stormGuard.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Structured logger exposing category-gated log methods.
|
||||||
|
* @namespace logger
|
||||||
|
*/
|
||||||
|
export const logger = {
|
||||||
|
/**
|
||||||
|
* Log an error message (always emitted regardless of config).
|
||||||
|
* @param {string} tag - A tag identifying the source (e.g. "[Player]").
|
||||||
|
* @param {...*} args - Additional values to log.
|
||||||
|
*/
|
||||||
|
error(tag, ...args) {
|
||||||
|
const g = _stormGate("error", tag, args);
|
||||||
|
if (!g.emit) return;
|
||||||
|
console.error(`[${ts()}] ${tag}`, ...args, ...(g.suffix ? [g.suffix] : []));
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Log a warning message. Honours `logging.warn` override when logging is disabled.
|
||||||
|
* @param {string} tag - A tag identifying the source.
|
||||||
|
* @param {...*} args - Additional values to log.
|
||||||
|
*/
|
||||||
|
warn(tag, ...args) {
|
||||||
|
if (_config?.enabled === false && _config?.warn !== true) return;
|
||||||
|
const g = _stormGate("warn", tag, args);
|
||||||
|
if (!g.emit) return;
|
||||||
|
console.warn(`[${ts()}] ${tag}`, ...args, ...(g.suffix ? [g.suffix] : []));
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Log an info message. Suppressed when `logging.enabled === false`.
|
||||||
|
* @param {string} tag - A tag identifying the source.
|
||||||
|
* @param {...*} args - Additional values to log.
|
||||||
|
*/
|
||||||
|
info(tag, ...args) {
|
||||||
|
if (_config?.enabled === false) return;
|
||||||
|
console.log(`[${ts()}] ${tag}`, ...args);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Category-gated player log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated inactivity log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated voice 24/7 log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
voice247(...args) { if (isEnabled("voice247")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated voice-state log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
voiceState(...args) { if (isEnabled("voiceState")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated media-player log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
mediaplayer(...args) { if (isEnabled("mediaplayer")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated commands log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
commands(...args) { if (isEnabled("commands")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated guild log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
guild(...args) { if (isEnabled("guild")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated recovery log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
recovery(...args) { if (isEnabled("recovery")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated settings log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
settings(...args) { if (isEnabled("settings")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated lavalink log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
lavalink(...args) { if (isEnabled("lavalink")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated alone-check log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
aloneCheck(...args) { if (isEnabled("aloneCheck")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated voice log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
voice(...args) { if (isEnabled("voice")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated dashboard log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
dashboard(...args) { if (isEnabled("dashboard")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
/**
|
||||||
|
* Category-gated redis log.
|
||||||
|
* @param {...*} args
|
||||||
|
*/
|
||||||
|
redis(...args) { if (isEnabled("redis")) console.log(`[${ts()}]`, ...args); },
|
||||||
|
};
|
||||||
+34
-634
@@ -2,29 +2,41 @@
|
|||||||
* @module dashboard/Dashboard
|
* @module dashboard/Dashboard
|
||||||
* @description Web dashboard backend controller. Manages Redis pub/sub communication
|
* @description Web dashboard backend controller. Manages Redis pub/sub communication
|
||||||
* with the dashboard frontend, handles remote function calls (join, play, pause, etc.),
|
* with the dashboard frontend, handles remote function calls (join, play, pause, etc.),
|
||||||
* and provides static data-conversion helpers for Discord entities.
|
* and provides static data-conversion helpers for bot entities.
|
||||||
|
*
|
||||||
|
* Base class of the dashboard split: class fields, construction (including the
|
||||||
|
* Redis request-routing switch), the Redis/MySQL lifecycle, setBotId and the
|
||||||
|
* player/user update broadcasts. The remote RPC handler methods (runFunction,
|
||||||
|
* confirmLogin, authorization helpers) live in RpcHandlersMixin.mjs and the static
|
||||||
|
* conversion helpers in Serializers.mjs — both are attached at the bottom of this file.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
|
import { CommandBuilder, CommandHandler, Option } from "../commands/index.mjs";
|
||||||
import { PermissionFlags } from "@fluxerjs/core";
|
import { PermissionFlags } from "@fluxerjs/core";
|
||||||
import Player from "../Player.mjs";
|
import Player from "../music/player/index.mjs";
|
||||||
import { Utils, cleanId } from "../Utils.mjs";
|
import { Utils, cleanId } from "../utils/Utils.mjs";
|
||||||
import { DatabaseManager } from "./DatabaseManager.mjs";
|
import { DatabaseManager } from "../db/DatabaseManager.mjs";
|
||||||
import { RedisHandler } from "./RedisHandler.mjs";
|
import { RedisHandler } from "./RedisHandler.mjs";
|
||||||
import { logger } from "../constants/Logger.mjs";
|
import { logger } from "../core/Logger.mjs";
|
||||||
import { iterateVoiceStates } from "../constants/VoiceStateResolver.mjs";
|
import { iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
||||||
|
import { applyMixins } from "../utils/mixins.mjs";
|
||||||
|
import RpcHandlersMixin from "./RpcHandlersMixin.mjs";
|
||||||
|
import Serializers from "./Serializers.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @class
|
* @class
|
||||||
* @description Orchestrates the web dashboard: wires up Redis request/response handling,
|
* @description Orchestrates the web dashboard: wires up Redis request/response handling,
|
||||||
* converts Discord data for the frontend, and exposes remote control functions.
|
* converts bot data for the frontend, and exposes remote control functions.
|
||||||
*/
|
*/
|
||||||
export class Dashboard {
|
class Dashboard {
|
||||||
/** @type {boolean} Whether the dashboard is enabled. */
|
/** @type {boolean} Whether the dashboard is enabled. */
|
||||||
enabled = false;
|
enabled = false;
|
||||||
/** @type {number} Login code expiry time in milliseconds (default 6 hours). */
|
/** @type {number} Login code expiry time in milliseconds (default 6 hours). */
|
||||||
expiryTime = 1000 * 60 * 60 * 6;
|
expiryTime = 1000 * 60 * 60 * 6;
|
||||||
|
|
||||||
|
/** @private */
|
||||||
|
_playerUpdateTimers = new Map();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a new Dashboard instance.
|
* Create a new Dashboard instance.
|
||||||
* @param {object} remix - The main bot (Remix) instance.
|
* @param {object} remix - The main bot (Remix) instance.
|
||||||
@@ -134,10 +146,9 @@ export class Dashboard {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the bot ID for the Redis platform prefix.
|
* Set the bot ID for the Redis platform prefix.
|
||||||
* @param {string} botId - The bot's Discord user ID.
|
* @param {string} botId - The bot's user ID.
|
||||||
*/
|
*/
|
||||||
setBotId(botId) {
|
setBotId(botId) {
|
||||||
if (!this.enabled || !this.redis) return;
|
if (!this.enabled || !this.redis) return;
|
||||||
@@ -145,590 +156,6 @@ export class Dashboard {
|
|||||||
this.redis.readyMessage();
|
this.redis.readyMessage();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute a remote dashboard function (e.g. join, pause, volume).
|
|
||||||
* @async
|
|
||||||
* @param {object} params - Function call parameters.
|
|
||||||
* @param {string} params.func - The function name to execute.
|
|
||||||
* @param {object} [params.data] - Additional data for the function.
|
|
||||||
* @param {string} [params.data.user] - The Discord user ID making the request.
|
|
||||||
* @returns {Promise<object>} Result object with `message` or `error`.
|
|
||||||
*/
|
|
||||||
async runFunction(params) {
|
|
||||||
let user;
|
|
||||||
if (params.data?.user) {
|
|
||||||
try {
|
|
||||||
user = await this.remix.client.users.fetch(params.data.user);
|
|
||||||
} catch (e) {
|
|
||||||
logger.dashboard("[Dashboard] Error:", e);
|
|
||||||
return { error: "Invalid User" };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
switch (params.func) {
|
|
||||||
case "join": {
|
|
||||||
if (!user) return { error: "Invalid user" };
|
|
||||||
let voiceChannel, textChannel;
|
|
||||||
try {
|
|
||||||
const chMgr = this.remix.client.channels;
|
|
||||||
if (typeof chMgr.fetch === "function") {
|
|
||||||
voiceChannel = await chMgr.fetch(params.data.channel).catch(() => null);
|
|
||||||
if (params.data.text) textChannel = await chMgr.fetch(params.data.text).catch(() => null);
|
|
||||||
} else {
|
|
||||||
voiceChannel = chMgr.get(params.data.channel);
|
|
||||||
if (params.data.text) textChannel = chMgr.get(params.data.text);
|
|
||||||
}
|
|
||||||
if (!voiceChannel) return { error: "Voice channel not found" };
|
|
||||||
|
|
||||||
const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 ||
|
|
||||||
(typeof ch.isText === "function" && ch.isText()));
|
|
||||||
|
|
||||||
if (!isText(textChannel)) {
|
|
||||||
const guild = this.remix.client.guilds.get(voiceChannel.guildId);
|
|
||||||
if (guild?.channels) {
|
|
||||||
const channelValues = typeof guild.channels.values === "function"
|
|
||||||
? [...guild.channels.values()]
|
|
||||||
: Array.isArray(guild.channels) ? guild.channels : Object.values(guild.channels);
|
|
||||||
const sysCh = guild.systemChannelId
|
|
||||||
? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId && isText(c))
|
|
||||||
: null;
|
|
||||||
textChannel = sysCh ?? channelValues.find(c => isText(c)) ?? null;
|
|
||||||
}
|
|
||||||
if (!textChannel) {
|
|
||||||
logger.dashboard("[Dashboard] No text channel found for guild", voiceChannel.guildId, "— voice channel will be used as fallback");
|
|
||||||
textChannel = voiceChannel;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
logger.dashboard("[Dashboard] Error:", e);
|
|
||||||
return { error: "Invalid Channel" };
|
|
||||||
}
|
|
||||||
const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId);
|
|
||||||
if (authErr) return { error: authErr };
|
|
||||||
if (this.remix.players.playerMap.has(voiceChannel.id)) {
|
|
||||||
const existingPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
|
||||||
if (existingPlayer && user && !existingPlayer._dashboardUsers) {
|
|
||||||
existingPlayer._dashboardUsers = [];
|
|
||||||
}
|
|
||||||
if (existingPlayer && user && !existingPlayer._dashboardUsers.includes(String(user.id))) {
|
|
||||||
existingPlayer._dashboardUsers.push(String(user.id));
|
|
||||||
try {
|
|
||||||
const pubChannel = this.remix.redis?.publisher ?? this.remix.redis;
|
|
||||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
|
||||||
pubChannel.publish("fluxer:player_" + voiceChannel.id, JSON.stringify({
|
|
||||||
type: "join",
|
|
||||||
data: String(user.id)
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
|
|
||||||
}
|
|
||||||
return { message: "Already Connected" };
|
|
||||||
}
|
|
||||||
const fakeMsg = {
|
|
||||||
channel: textChannel,
|
|
||||||
message: { guildId: voiceChannel.guildId },
|
|
||||||
reply: async () => ({ edit: async () => {}, catch: () => {} }),
|
|
||||||
};
|
|
||||||
this.remix.players.initPlayer(fakeMsg, voiceChannel.id);
|
|
||||||
const newPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
|
||||||
if (newPlayer && user) {
|
|
||||||
if (!newPlayer._dashboardUsers) newPlayer._dashboardUsers = [];
|
|
||||||
if (!newPlayer._dashboardUsers.includes(String(user.id))) {
|
|
||||||
newPlayer._dashboardUsers.push(String(user.id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { message: "Joining" };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "pausePlayback": {
|
|
||||||
const player = this._getPlayerById(params.data.player);
|
|
||||||
if (!player) return { error: "Player not found" };
|
|
||||||
const authErr = this._authorizePlayerControl(user, player);
|
|
||||||
if (authErr) return { error: authErr };
|
|
||||||
const msg = player.pause() || "Paused successfully";
|
|
||||||
return { message: msg };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "resumePlayback": {
|
|
||||||
const player = this._getPlayerById(params.data.player);
|
|
||||||
if (!player) return { error: "Player not found" };
|
|
||||||
const authErr = this._authorizePlayerControl(user, player);
|
|
||||||
if (authErr) return { error: authErr };
|
|
||||||
const msg = player.resume() || "Resumed successfully";
|
|
||||||
return { message: msg };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "skip": {
|
|
||||||
const player = this._getPlayerById(params.data.player);
|
|
||||||
if (!player) return { error: "Player not found" };
|
|
||||||
const authErr = this._authorizePlayerControl(user, player);
|
|
||||||
if (authErr) return { error: authErr };
|
|
||||||
const msg = player.skip() || "Skipped song";
|
|
||||||
return { message: msg };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "volume": {
|
|
||||||
const player = this._getPlayerById(params.data.player);
|
|
||||||
if (!player) return { error: "Player not found" };
|
|
||||||
const authErr = this._authorizePlayerControl(user, player);
|
|
||||||
if (authErr) return { error: authErr };
|
|
||||||
const vol = Number(params.data.volume);
|
|
||||||
if (isNaN(vol) || vol < 0 || vol > 2) return {
|
|
||||||
error: "Volume must be between 0 and 2" };
|
|
||||||
const msg = player.setVolume(vol);
|
|
||||||
return { message: msg };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "addToQueue": {
|
|
||||||
const player = this._getPlayerById(params.data.player);
|
|
||||||
if (!player) return { error: "Player not found" };
|
|
||||||
if (!user) return { error: "Invalid user" };
|
|
||||||
const authErr = this._authorizePlayerControl(user, player);
|
|
||||||
if (authErr) return { error: authErr };
|
|
||||||
const type = params.data.type;
|
|
||||||
const query = params.data.query;
|
|
||||||
if (!query || typeof query !== "string") return { error: "Missing or invalid query" };
|
|
||||||
if (query.length > 500) return { error: "Query too long (max 500 characters)" };
|
|
||||||
if (type === "radio") {
|
|
||||||
const radio = this.remix.config.radio.find(e => e.name === query);
|
|
||||||
if (!radio) return { error: "Invalid radio station" };
|
|
||||||
player.playRadio(radio);
|
|
||||||
return { message: "Adding radio station" };
|
|
||||||
}
|
|
||||||
if (/^(javascript|data|vbscript):/i.test(query.trim())) {
|
|
||||||
return { error: "Invalid query protocol" };
|
|
||||||
}
|
|
||||||
player.play(query);
|
|
||||||
return { message: "Adding to queue" };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "testConnection": {
|
|
||||||
return { success: true };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "voiceState": {
|
|
||||||
if (!user) return { channel: null };
|
|
||||||
const userId = cleanId(user.id);
|
|
||||||
if (this.remix.voiceCache) {
|
|
||||||
for (const [mapUserId, info] of this.remix.voiceCache) {
|
|
||||||
if (cleanId(mapUserId) === userId && info.channelId) {
|
|
||||||
const ch = this.remix.client.channels.get(info.channelId);
|
|
||||||
return {
|
|
||||||
channelId: info.channelId,
|
|
||||||
channel: ch ? Dashboard.convertChannel(ch) : { id: info.channelId, name: "Unknown" },
|
|
||||||
guildId: info.guildId ?? ch?.guildId ?? null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const guilds = this.remix.client.guilds;
|
|
||||||
const guildValues = guilds && typeof guilds.values === "function"
|
|
||||||
? [...guilds.values()] : guilds ? Object.values(guilds) : [];
|
|
||||||
for (const guild of guildValues) {
|
|
||||||
for (const vs of iterateVoiceStates(guild)) {
|
|
||||||
const stateUserId = cleanId(vs.userId);
|
|
||||||
if (stateUserId === userId && vs.channelId) {
|
|
||||||
const ch = this.remix.client.channels.get(vs.channelId);
|
|
||||||
return {
|
|
||||||
channelId: vs.channelId,
|
|
||||||
channel: ch ? Dashboard.convertChannel(ch) : { id: vs.channelId, name: "Unknown" },
|
|
||||||
guildId: guild.id,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { channel: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
case "leave": {
|
|
||||||
if (!user) return { error: "Invalid user" };
|
|
||||||
const playerId = params.data.channel ?? params.data.player;
|
|
||||||
const player = this._getPlayerById(playerId);
|
|
||||||
if (!player) return { error: "Player not found" };
|
|
||||||
const authErr = await this._authorizeUserInGuild(user, player._guildId);
|
|
||||||
if (authErr) return { error: authErr };
|
|
||||||
if (player._dashboardUsers && user) {
|
|
||||||
const idx = player._dashboardUsers.indexOf(String(user.id));
|
|
||||||
if (idx !== -1) player._dashboardUsers.splice(idx, 1);
|
|
||||||
}
|
|
||||||
if (player._dashboardUsers && player._dashboardUsers.length > 0) {
|
|
||||||
try {
|
|
||||||
const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client;
|
|
||||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
|
||||||
pubChannel.publish("fluxer:player_" + playerId, JSON.stringify({
|
|
||||||
type: "leave",
|
|
||||||
data: String(user.id)
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
|
|
||||||
return { message: "Left channel" };
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await player.leave();
|
|
||||||
return { message: "Left channel" };
|
|
||||||
} catch (e) {
|
|
||||||
return { error: "Failed to leave: " + e.message };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
return { error: "Unknown function: " + (params.func ?? "(none)") };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verify that the given user is allowed to control the given player.
|
|
||||||
* Bot owners bypass the check; otherwise the user must be in the same voice channel.
|
|
||||||
* @private
|
|
||||||
* @param {object} user - The Discord user attempting to control the player.
|
|
||||||
* @param {object} player - The Player instance to control.
|
|
||||||
* @returns {string|null} An error message if unauthorized, or null if authorized.
|
|
||||||
*/
|
|
||||||
_authorizePlayerControl(user, player) {
|
|
||||||
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null;
|
|
||||||
if (!user) return "User not provided";
|
|
||||||
|
|
||||||
const cleanUserId = cleanId(user.id);
|
|
||||||
const cleanChanId = cleanId(player._channelId);
|
|
||||||
if (!cleanChanId) return "Player has no active channel";
|
|
||||||
|
|
||||||
const observed = this.remix.voiceCache;
|
|
||||||
if (observed) {
|
|
||||||
const guildId = cleanId(player._guildId);
|
|
||||||
const userLoc = observed.get(cleanUserId, guildId || undefined);
|
|
||||||
if (userLoc) {
|
|
||||||
const infoChannelId = cleanId(userLoc.channelId);
|
|
||||||
if (infoChannelId === cleanChanId) return null;
|
|
||||||
}
|
|
||||||
for (const [mapUserId, info] of observed) {
|
|
||||||
if (cleanId(mapUserId) === cleanUserId) {
|
|
||||||
const infoChannelId = cleanId(info.channelId);
|
|
||||||
if (infoChannelId === cleanChanId) return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return "You must be in the same voice channel as the bot to control playback";
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verify that the given user is a member of the specified guild.
|
|
||||||
* Bot owners bypass the check.
|
|
||||||
* @private
|
|
||||||
* @async
|
|
||||||
* @param {object} user - The Discord user to verify.
|
|
||||||
* @param {string} guildId - The guild ID to check membership in.
|
|
||||||
* @returns {Promise<string|null>} An error message if not a member, or null if authorized.
|
|
||||||
*/
|
|
||||||
async _authorizeUserInGuild(user, guildId) {
|
|
||||||
if (this.remix.handler?.owners?.includes?.(user.id)) return null;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const guild = this.remix.client.guilds.get(guildId);
|
|
||||||
if (!guild) return "Server not found";
|
|
||||||
const member = await guild.members.fetch(user.id).catch(() => null);
|
|
||||||
if (!member) return "You are not a member of this server";
|
|
||||||
return null;
|
|
||||||
} catch (e) {
|
|
||||||
return "Failed to verify membership: " + e.message;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Look up a player by channel ID, guild ID, or player ID.
|
|
||||||
* @private
|
|
||||||
* @param {string} id - Channel ID, guild ID, or player ID.
|
|
||||||
* @returns {object|null} The matching Player instance, or null.
|
|
||||||
*/
|
|
||||||
_getPlayerById(id) {
|
|
||||||
return this.remix.players.playerMap.get(id)
|
|
||||||
?? [...this.remix.players.playerMap.values()].find(
|
|
||||||
p => p._channelId === id || p._guildId === id
|
|
||||||
)
|
|
||||||
?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a Discord user object to a dashboard-safe plain object.
|
|
||||||
* @static
|
|
||||||
* @param {object} user - The Discord user.
|
|
||||||
* @returns {{ id: string, username: string, displayName: string, avatar: { url: string } }}
|
|
||||||
*/
|
|
||||||
static convertUser(user) {
|
|
||||||
let avatarUrl = "";
|
|
||||||
if (user.avatar) {
|
|
||||||
avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`;
|
|
||||||
} else if (typeof user.displayAvatarURL === "function") {
|
|
||||||
try { avatarUrl = user.displayAvatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] displayAvatarURL:", e?.message); }
|
|
||||||
} else if (typeof user.avatarURL === "function") {
|
|
||||||
try { avatarUrl = user.avatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] avatarURL:", e?.message); }
|
|
||||||
}
|
|
||||||
if (!avatarUrl) {
|
|
||||||
avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.id?.slice(-4) ?? "0") % 5}.png`;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
id: user.id,
|
|
||||||
username: user.username,
|
|
||||||
displayName: user.displayName ?? user.globalName ?? user.username,
|
|
||||||
avatar: {
|
|
||||||
url: avatarUrl,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a video/track object to a dashboard-safe plain object.
|
|
||||||
* @static
|
|
||||||
* @param {object} vid - The video/track object from the player queue.
|
|
||||||
* @returns {object|null} Sanitised video data, or null if input is falsy.
|
|
||||||
*/
|
|
||||||
static convertVideo(vid) {
|
|
||||||
if (!vid) return null;
|
|
||||||
const durationMs =
|
|
||||||
typeof vid.duration === "number" ? vid.duration :
|
|
||||||
typeof vid.duration === "object" && vid.duration?.seconds !== null ? vid.duration.seconds * 1000 :
|
|
||||||
0;
|
|
||||||
return {
|
|
||||||
title: vid.title,
|
|
||||||
url: vid.type === "radio" ? vid.author?.url : vid.url,
|
|
||||||
videoId: vid.videoId,
|
|
||||||
type: vid.type,
|
|
||||||
duration: vid.type === "radio" ? "--:--" : Utils.prettifyMS(durationMs),
|
|
||||||
description: vid.description,
|
|
||||||
artist: {
|
|
||||||
name: vid.author?.name ?? vid.artist,
|
|
||||||
url: vid.author?.url,
|
|
||||||
},
|
|
||||||
thumbnail: vid.thumbnail,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a Discord channel to a dashboard-safe plain object, including
|
|
||||||
* voice participant info for voice channels.
|
|
||||||
* @static
|
|
||||||
* @param {object} channel - The Discord channel.
|
|
||||||
* @returns {object} Sanitised channel data.
|
|
||||||
*/
|
|
||||||
static convertChannel(channel) {
|
|
||||||
const type = channel.type ?? 0;
|
|
||||||
const isVoice = channel.isVoice?.() || type === 2;
|
|
||||||
const isCategory = type === 4;
|
|
||||||
const isText = !isVoice && !isCategory && (
|
|
||||||
type === 0 || type === 5 || type === 13 ||
|
|
||||||
(typeof channel.isText === "function" && channel.isText())
|
|
||||||
);
|
|
||||||
let voiceParticipants = [];
|
|
||||||
if (isVoice) {
|
|
||||||
const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
|
||||||
for (const vs of iterateVoiceStates(guild)) {
|
|
||||||
const scId = cleanId(vs.channelId);
|
|
||||||
const chId = cleanId(channel?.id);
|
|
||||||
if (scId === chId) {
|
|
||||||
const user = guild?.members?.get?.(vs.userId)?.user;
|
|
||||||
if (user && !user.bot) voiceParticipants.push(Dashboard.convertUser(user));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: channel.name,
|
|
||||||
displayName: channel.name,
|
|
||||||
id: channel.id,
|
|
||||||
icon: null,
|
|
||||||
description: channel.topic ?? null,
|
|
||||||
type,
|
|
||||||
isVoice,
|
|
||||||
isCategory,
|
|
||||||
isText,
|
|
||||||
parentId: channel.parentId ?? channel.parent_id ?? null,
|
|
||||||
voiceParticipants,
|
|
||||||
mature: channel.nsfw ?? false,
|
|
||||||
serverId: channel.guildId,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a Discord guild (server) to a dashboard-safe plain object with channels.
|
|
||||||
* @static
|
|
||||||
* @param {object} guild - The Discord guild.
|
|
||||||
* @returns {object} Sanitised server data including channels and voice channels.
|
|
||||||
*/
|
|
||||||
static convertServer(guild) {
|
|
||||||
const channelStore = guild.channels;
|
|
||||||
const channelIds = channelStore && typeof channelStore.keys === "function"
|
|
||||||
? [...channelStore.keys()]
|
|
||||||
: [];
|
|
||||||
const channelValues = channelStore && typeof channelStore.values === "function"
|
|
||||||
? [...channelStore.values()]
|
|
||||||
: [];
|
|
||||||
const allChannels = channelValues
|
|
||||||
.map(Dashboard.convertChannel)
|
|
||||||
.filter(c => !c.isCategory);
|
|
||||||
|
|
||||||
let iconUrl = null;
|
|
||||||
if (guild.icon) {
|
|
||||||
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
|
||||||
} else if (typeof guild.iconURL === "function") {
|
|
||||||
try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; }
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
name: guild.name,
|
|
||||||
id: guild.id,
|
|
||||||
icon: iconUrl,
|
|
||||||
channelIds,
|
|
||||||
description: guild.description ?? null,
|
|
||||||
ownerId: guild.ownerId,
|
|
||||||
channels: allChannels,
|
|
||||||
voiceChannels: allChannels.filter(c => c.isVoice),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a Discord guild to a lightweight summary object (no channels).
|
|
||||||
* @static
|
|
||||||
* @param {object} guild - The Discord guild.
|
|
||||||
* @returns {{ name: string, id: string, icon: string|null, description: string|null, ownerId: string|null }}
|
|
||||||
*/
|
|
||||||
static convertServerSummary(guild) {
|
|
||||||
let iconUrl = null;
|
|
||||||
if (guild.icon) {
|
|
||||||
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
|
||||||
} else if (typeof guild.iconURL === "function") {
|
|
||||||
try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; }
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
name: guild.name,
|
|
||||||
id: guild.id,
|
|
||||||
icon: iconUrl,
|
|
||||||
description: guild.description ?? null,
|
|
||||||
ownerId: guild.ownerId,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a Player instance to a dashboard-safe serialisable object.
|
|
||||||
* Includes queue, users, channel, and server info.
|
|
||||||
* @static
|
|
||||||
* @param {object} player - The Player instance.
|
|
||||||
* @returns {object} Sanitised player data.
|
|
||||||
*/
|
|
||||||
static convertPlayer(player) {
|
|
||||||
const channelId = player._channelId;
|
|
||||||
const channel = channelId ? player.client?.channels?.get(channelId) : null;
|
|
||||||
const guild = channel?.guild ?? (player._guildId ? player.client?.guilds?.get(player._guildId) : null);
|
|
||||||
const cleanChannelId = channelId ? cleanId(channelId) : "";
|
|
||||||
const cleanGuildId = player._guildId ? cleanId(player._guildId) : "";
|
|
||||||
|
|
||||||
const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] };
|
|
||||||
|
|
||||||
return {
|
|
||||||
loop: (queue.loop ? 1 : 0) + (queue.songLoop ? 2 : 0),
|
|
||||||
paused: !!player._paused,
|
|
||||||
volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume * 100 : 100,
|
|
||||||
queue: {
|
|
||||||
current: Dashboard.convertVideo(queue.current),
|
|
||||||
data: Array.isArray(queue.data) ? queue.data.slice(0, 500).map(v => Dashboard.convertVideo(v)) : [],
|
|
||||||
},
|
|
||||||
users: (() => {
|
|
||||||
if (!channel) return player._dashboardUsers ?? [];
|
|
||||||
const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
|
||||||
const ids = [];
|
|
||||||
const seen = new Set();
|
|
||||||
for (const vs of iterateVoiceStates(g)) {
|
|
||||||
const scId = cleanId(vs.channelId);
|
|
||||||
const chId = cleanId(channel?.id);
|
|
||||||
if (scId === chId) {
|
|
||||||
const memberId = vs.userId;
|
|
||||||
if (memberId) { ids.push(memberId); seen.add(memberId); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const vc = player._voiceCache ?? player._observedVoiceUsers;
|
|
||||||
if (vc && cleanChannelId && cleanGuildId) {
|
|
||||||
if (typeof vc.getHumansInChannel === "function") {
|
|
||||||
const channelHumans = vc.getHumansInChannel(cleanGuildId, cleanChannelId);
|
|
||||||
for (const hid of channelHumans) {
|
|
||||||
if (seen.has(hid)) continue;
|
|
||||||
const botId = player.client?.user?.id;
|
|
||||||
if (botId && String(hid) === String(botId)) continue;
|
|
||||||
ids.push(String(hid));
|
|
||||||
seen.add(hid);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for (const [mapUserId, info] of vc) {
|
|
||||||
if (seen.has(mapUserId)) continue;
|
|
||||||
const infoCh = cleanId(info.channelId);
|
|
||||||
const infoG = cleanId(info.guildId);
|
|
||||||
if (infoCh === cleanChannelId && infoG === cleanGuildId) {
|
|
||||||
const botId = player.client?.user?.id;
|
|
||||||
if (botId && String(mapUserId) === String(botId)) continue;
|
|
||||||
ids.push(String(mapUserId));
|
|
||||||
seen.add(mapUserId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (player._dashboardUsers) {
|
|
||||||
for (const du of player._dashboardUsers) {
|
|
||||||
if (!seen.has(du)) { ids.push(du); seen.add(du); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ids;
|
|
||||||
})(),
|
|
||||||
channel: channel ? Dashboard.convertChannel(channel) : null,
|
|
||||||
server: guild ? Dashboard.convertServerSummary(guild) : null,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a command option to a dashboard-safe plain object.
|
|
||||||
* @static
|
|
||||||
* @param {object} opt - The command option.
|
|
||||||
* @returns {object} Sanitised option data.
|
|
||||||
*/
|
|
||||||
static convertOption(opt) {
|
|
||||||
return {
|
|
||||||
type: opt.type,
|
|
||||||
name: opt.name,
|
|
||||||
choices: opt.choices,
|
|
||||||
description: opt.description,
|
|
||||||
required: opt.required,
|
|
||||||
uid: opt.uid,
|
|
||||||
defaultValue: opt.defaultValue,
|
|
||||||
dynamicDefaultPresent: !!opt.dynamicDefault,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert a command (and its subcommands/options) to a dashboard-safe plain object.
|
|
||||||
* @static
|
|
||||||
* @param {object} com - The command object.
|
|
||||||
* @param {object} commands - The CommandHandler instance (for usage generation).
|
|
||||||
* @returns {object} Sanitised command data.
|
|
||||||
*/
|
|
||||||
static convertCommand(com, commands) {
|
|
||||||
return {
|
|
||||||
name: com.name,
|
|
||||||
description: com.description,
|
|
||||||
uid: com.uid,
|
|
||||||
aliases: com.aliases,
|
|
||||||
subcommands: com.subcommands.map(c => Dashboard.convertCommand(c, commands)),
|
|
||||||
category: com.category,
|
|
||||||
examples: com.examples,
|
|
||||||
usage: commands.helpHandler?.commandUsage?.(com, {
|
|
||||||
message: { guildId: null },
|
|
||||||
}) ?? null,
|
|
||||||
options: com.options.map(o => Dashboard.convertOption(o)),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/** @private */
|
|
||||||
_playerUpdateTimers = new Map();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Broadcast a player state update to the dashboard via Redis.
|
* Broadcast a player state update to the dashboard via Redis.
|
||||||
* Debounces non-init/close updates by 500ms.
|
* Debounces non-init/close updates by 500ms.
|
||||||
@@ -784,7 +211,7 @@ export class Dashboard {
|
|||||||
/**
|
/**
|
||||||
* Broadcast a user update to the global users Redis channel.
|
* Broadcast a user update to the global users Redis channel.
|
||||||
* @param {object} details - The update payload.
|
* @param {object} details - The update payload.
|
||||||
* @param {object} user - The Discord user.
|
* @param {object} user - The user.
|
||||||
*/
|
*/
|
||||||
userUpdate(details, user) {
|
userUpdate(details, user) {
|
||||||
if (!this.enabled) return;
|
if (!this.enabled) return;
|
||||||
@@ -798,48 +225,21 @@ export class Dashboard {
|
|||||||
/**
|
/**
|
||||||
* Send a lightweight update to the user-specific Redis channel.
|
* Send a lightweight update to the user-specific Redis channel.
|
||||||
* @param {object} details - The update payload.
|
* @param {object} details - The update payload.
|
||||||
* @param {object} user - The Discord user.
|
* @param {object} user - The user.
|
||||||
*/
|
*/
|
||||||
updateUser(details, user) {
|
updateUser(details, user) {
|
||||||
if (!this.enabled) return;
|
if (!this.enabled) return;
|
||||||
const channel = this.redis.platform + ":user_" + user.id;
|
const channel = this.redis.platform + ":user_" + user.id;
|
||||||
this.redis.send(channel, JSON.stringify(details));
|
this.redis.send(channel, JSON.stringify(details));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Verify a dashboard login code for a user.
|
|
||||||
* @async
|
|
||||||
* @param {string} user - The Discord user ID.
|
|
||||||
* @param {string} code - The login code to verify.
|
|
||||||
* @returns {Promise<string|null>} An error message if verification fails, or null on success.
|
|
||||||
*/
|
|
||||||
async confirmLogin(user, code) {
|
|
||||||
if (!this.enabled) return "Dashboard not enabled.";
|
|
||||||
if (!this.db) return "Dashboard database not configured.";
|
|
||||||
|
|
||||||
let res;
|
|
||||||
try {
|
|
||||||
res = await this.db.execute("SELECT * FROM login_codes WHERE user=? AND (verified IS NULL OR verified !== true)", [user]);
|
|
||||||
} catch (e) {
|
|
||||||
const id = Utils.uid();
|
|
||||||
logger.dashboard("[Dashboard] MySQL error, id:", id, e);
|
|
||||||
return "An error occurred, please contact an administrator if this happens again. Error id: `" + id + "`";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (res.length === 0) return "If this is a valid code, it was not created for your account.";
|
|
||||||
|
|
||||||
for (let i = 0; i < res.length; i++) {
|
|
||||||
if (res[i].verified) continue;
|
|
||||||
if (await this.db.compareHash(code, res[i].token)) {
|
|
||||||
if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) {
|
|
||||||
return "Login token expired";
|
|
||||||
}
|
|
||||||
await this.db.execute("UPDATE login_codes SET verified=true WHERE id=?", [res[i].id]);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return "Invalid code.";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Attach the split-out concerns: the remote RPC handler methods (runFunction,
|
||||||
|
// confirmLogin and the authorization helpers) from RpcHandlersMixin.
|
||||||
|
applyMixins(Dashboard, RpcHandlersMixin);
|
||||||
|
|
||||||
|
// Re-attach the static conversion helpers (convertUser, convertChannel,
|
||||||
|
// convertPlayer, …) so external `Dashboard.convertX(...)` call sites keep working.
|
||||||
|
Object.assign(Dashboard, Serializers);
|
||||||
|
|
||||||
|
export { Dashboard };
|
||||||
@@ -6,20 +6,23 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { createClient } from "redis";
|
import { createClient } from "redis";
|
||||||
import { logger } from "../constants/Logger.mjs";
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Default reconnection strategy for Redis sockets.
|
* Default reconnection strategy for Redis sockets.
|
||||||
* @param {object} options - Reconnection options from the Redis client.
|
* redis@5 calls the strategy as `strategy(retries, cause)` where `retries` is a
|
||||||
* @param {number} options.totalRetryTime - Cumulative retry time so far.
|
* plain NUMBER of reconnect attempts made so far — NOT an options object.
|
||||||
* @param {number} options.attempt - Current retry attempt number.
|
* The previous version read cumulative-time / attempt-count properties off
|
||||||
* @returns {number|Error} Delay in ms before next retry, or an Error to stop retrying.
|
* that number, which produced NaN; NaN passes redis@5's `typeof !== "number"`
|
||||||
|
* gate and collapses `setTimeout(NaN)` to a ~1ms hot-retry loop (log storm).
|
||||||
|
* Strategy now: linear ramp 0.5s -> 5s, then a steady 15s retry pulse. It
|
||||||
|
* never exhausts, so the dashboard auto-recovers whenever Redis returns.
|
||||||
|
* @param {number} retries - Reconnect attempts made so far (redis@5 argument).
|
||||||
|
* @returns {number} Delay in ms before the next reconnect attempt.
|
||||||
*/
|
*/
|
||||||
const DEFAULT_RETRY_STRATEGY = (options) => {
|
const DEFAULT_RETRY_STRATEGY = (retries) => {
|
||||||
if (options.totalRetryTime > 60_000) {
|
if (!Number.isFinite(retries)) return 15_000; // defensive: wrong-shape argument
|
||||||
return new Error("Redis reconnection exhausted after 60s");
|
return retries < 10 ? Math.min(retries * 500, 5_000) : 15_000;
|
||||||
}
|
|
||||||
return Math.min(options.attempt * 500, 5_000);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,12 +49,12 @@ export class RedisHandler {
|
|||||||
constructor(opts = {}) {
|
constructor(opts = {}) {
|
||||||
this.platform = opts.platform ?? "fluxer";
|
this.platform = opts.platform ?? "fluxer";
|
||||||
|
|
||||||
const clientOpts = {
|
// `url` (and any explicit socket options) come from config; the retry
|
||||||
...opts,
|
// strategy is always pinned so misconfig can never cause a hot retry loop.
|
||||||
socket: {
|
const { platform: _platform, ...clientOpts } = { ...opts };
|
||||||
...(opts.socket ?? {}),
|
clientOpts.socket = {
|
||||||
|
...(clientOpts.socket ?? {}),
|
||||||
reconnectStrategy: DEFAULT_RETRY_STRATEGY,
|
reconnectStrategy: DEFAULT_RETRY_STRATEGY,
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
this.client = createClient(clientOpts);
|
this.client = createClient(clientOpts);
|
||||||
@@ -74,16 +77,22 @@ export class RedisHandler {
|
|||||||
* @async
|
* @async
|
||||||
*/
|
*/
|
||||||
async _connect() {
|
async _connect() {
|
||||||
try {
|
// Connect both clients CONCURRENTLY. The previous sequential awaits made
|
||||||
await this.client.connect();
|
// the subscriber wait behind the main client's retry loop: while Redis was
|
||||||
|
// down, the subscriber never even attempted to connect.
|
||||||
|
this.client.connect()
|
||||||
|
.then(() => {
|
||||||
|
if (this._destroyed) return;
|
||||||
logger.redis("[Redis/Main] Connected");
|
logger.redis("[Redis/Main] Connected");
|
||||||
this.readyMessage();
|
this.readyMessage();
|
||||||
} catch (e) {
|
})
|
||||||
|
.catch((e) => {
|
||||||
logger.error("[Redis/Main] Initial connection failed:", e.message);
|
logger.error("[Redis/Main] Initial connection failed:", e.message);
|
||||||
}
|
});
|
||||||
|
|
||||||
try {
|
this.subscriber.connect()
|
||||||
await this.subscriber.connect();
|
.then(() => {
|
||||||
|
if (this._destroyed) return;
|
||||||
logger.redis("[Redis/Subscriber] Connected");
|
logger.redis("[Redis/Subscriber] Connected");
|
||||||
|
|
||||||
this.subscriber.subscribe("request", async (m) => {
|
this.subscriber.subscribe("request", async (m) => {
|
||||||
@@ -116,9 +125,10 @@ export class RedisHandler {
|
|||||||
this._pingInterval = setInterval(() => {
|
this._pingInterval = setInterval(() => {
|
||||||
this.send(this.platform + ":ping", "" + Date.now());
|
this.send(this.platform + ":ping", "" + Date.now());
|
||||||
}, 10000);
|
}, 10000);
|
||||||
} catch (e) {
|
})
|
||||||
|
.catch((e) => {
|
||||||
logger.error("[Redis/Subscriber] Initial connection failed:", e.message);
|
logger.error("[Redis/Subscriber] Initial connection failed:", e.message);
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -173,8 +183,16 @@ export class RedisHandler {
|
|||||||
this._destroyed = true;
|
this._destroyed = true;
|
||||||
if (this._pingInterval) { clearInterval(this._pingInterval); this._pingInterval = null; }
|
if (this._pingInterval) { clearInterval(this._pingInterval); this._pingInterval = null; }
|
||||||
if (this._readyTimer) { clearTimeout(this._readyTimer); this._readyTimer = null; }
|
if (this._readyTimer) { clearTimeout(this._readyTimer); this._readyTimer = null; }
|
||||||
try { await this.subscriber?.quit(); } catch(e) { logger.warn("[Redis/Subscriber] Quit error:", e?.message); }
|
// quit() waits for a live connection; on a still-connecting/down client it
|
||||||
try { await this.client?.quit(); } catch(e) { logger.warn("[Redis/Main] Quit error:", e?.message); }
|
// would pend forever (bot shutdown hang). Hard-disconnect instead.
|
||||||
|
try {
|
||||||
|
if (this.subscriber?.isReady) await this.subscriber.quit();
|
||||||
|
else this.subscriber?.disconnect();
|
||||||
|
} catch(e) { logger.warn("[Redis/Subscriber] Quit error:", e?.message); }
|
||||||
|
try {
|
||||||
|
if (this.client?.isReady) await this.client.quit();
|
||||||
|
else this.client?.disconnect();
|
||||||
|
} catch(e) { logger.warn("[Redis/Main] Quit error:", e?.message); }
|
||||||
logger.redis("[Redis] Connections closed gracefully");
|
logger.redis("[Redis] Connections closed gracefully");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,362 @@
|
|||||||
|
/**
|
||||||
|
* @module dashboard/RpcHandlersMixin
|
||||||
|
* @description Remote-control concern for {@link Dashboard}: the dashboard RPC
|
||||||
|
* "function" dispatch (runFunction — join / pausePlayback / resumePlayback / skip /
|
||||||
|
* volume / addToQueue / testConnection / voiceState / leave), the login-code
|
||||||
|
* verification (confirmLogin) and the authorization / player-lookup helpers.
|
||||||
|
*
|
||||||
|
* These methods are applied onto the Dashboard class prototype via
|
||||||
|
* {@link applyMixins} — `this` is a Dashboard instance.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Dashboard } from "./Dashboard.mjs";
|
||||||
|
import { Utils, cleanId } from "../utils/Utils.mjs";
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
import { iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @type {object}
|
||||||
|
* @description RPC handlers mixin — applied to Dashboard.
|
||||||
|
*/
|
||||||
|
const RpcHandlersMixin = {
|
||||||
|
/**
|
||||||
|
* Execute a remote dashboard function (e.g. join, pause, volume).
|
||||||
|
* @async
|
||||||
|
* @param {object} params - Function call parameters.
|
||||||
|
* @param {string} params.func - The function name to execute.
|
||||||
|
* @param {object} [params.data] - Additional data for the function.
|
||||||
|
* @param {string} [params.data.user] - The user ID making the request.
|
||||||
|
* @returns {Promise<object>} Result object with `message` or `error`.
|
||||||
|
*/
|
||||||
|
async runFunction(params) {
|
||||||
|
let user;
|
||||||
|
if (params.data?.user) {
|
||||||
|
try {
|
||||||
|
user = await this.remix.client.users.fetch(params.data.user);
|
||||||
|
} catch (e) {
|
||||||
|
logger.dashboard("[Dashboard] Error:", e);
|
||||||
|
return { error: "Invalid User" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch (params.func) {
|
||||||
|
case "join": {
|
||||||
|
if (!user) return { error: "Invalid user" };
|
||||||
|
let voiceChannel, textChannel;
|
||||||
|
try {
|
||||||
|
const chMgr = this.remix.client.channels;
|
||||||
|
if (typeof chMgr.fetch === "function") {
|
||||||
|
voiceChannel = await chMgr.fetch(params.data.channel).catch(() => null);
|
||||||
|
if (params.data.text) textChannel = await chMgr.fetch(params.data.text).catch(() => null);
|
||||||
|
} else {
|
||||||
|
voiceChannel = chMgr.get(params.data.channel);
|
||||||
|
if (params.data.text) textChannel = chMgr.get(params.data.text);
|
||||||
|
}
|
||||||
|
if (!voiceChannel) return { error: "Voice channel not found" };
|
||||||
|
|
||||||
|
const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 ||
|
||||||
|
(typeof ch.isText === "function" && ch.isText()));
|
||||||
|
|
||||||
|
if (!isText(textChannel)) {
|
||||||
|
const guild = this.remix.client.guilds.get(voiceChannel.guildId);
|
||||||
|
if (guild?.channels) {
|
||||||
|
const channelValues = typeof guild.channels.values === "function"
|
||||||
|
? [...guild.channels.values()]
|
||||||
|
: Array.isArray(guild.channels) ? guild.channels : Object.values(guild.channels);
|
||||||
|
const sysCh = guild.systemChannelId
|
||||||
|
? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId && isText(c))
|
||||||
|
: null;
|
||||||
|
textChannel = sysCh ?? channelValues.find(c => isText(c)) ?? null;
|
||||||
|
}
|
||||||
|
if (!textChannel) {
|
||||||
|
logger.dashboard("[Dashboard] No text channel found for guild", voiceChannel.guildId, "— voice channel will be used as fallback");
|
||||||
|
textChannel = voiceChannel;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.dashboard("[Dashboard] Error:", e);
|
||||||
|
return { error: "Invalid Channel" };
|
||||||
|
}
|
||||||
|
const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId);
|
||||||
|
if (authErr) return { error: authErr };
|
||||||
|
if (this.remix.players.playerMap.has(voiceChannel.id)) {
|
||||||
|
const existingPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||||
|
if (existingPlayer && user && !existingPlayer._dashboardUsers) {
|
||||||
|
existingPlayer._dashboardUsers = [];
|
||||||
|
}
|
||||||
|
if (existingPlayer && user && !existingPlayer._dashboardUsers.includes(String(user.id))) {
|
||||||
|
existingPlayer._dashboardUsers.push(String(user.id));
|
||||||
|
try {
|
||||||
|
const pubChannel = this.remix.redis?.publisher ?? this.remix.redis;
|
||||||
|
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||||
|
pubChannel.publish("fluxer:player_" + voiceChannel.id, JSON.stringify({
|
||||||
|
type: "join",
|
||||||
|
data: String(user.id)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
|
||||||
|
}
|
||||||
|
return { message: "Already Connected" };
|
||||||
|
}
|
||||||
|
const fakeMsg = {
|
||||||
|
channel: textChannel,
|
||||||
|
message: { guildId: voiceChannel.guildId },
|
||||||
|
reply: async () => ({ edit: async () => {}, catch: () => {} }),
|
||||||
|
};
|
||||||
|
this.remix.players.initPlayer(fakeMsg, voiceChannel.id);
|
||||||
|
const newPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||||
|
if (newPlayer && user) {
|
||||||
|
if (!newPlayer._dashboardUsers) newPlayer._dashboardUsers = [];
|
||||||
|
if (!newPlayer._dashboardUsers.includes(String(user.id))) {
|
||||||
|
newPlayer._dashboardUsers.push(String(user.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { message: "Joining" };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "pausePlayback": {
|
||||||
|
const player = this._getPlayerById(params.data.player);
|
||||||
|
if (!player) return { error: "Player not found" };
|
||||||
|
const authErr = this._authorizePlayerControl(user, player);
|
||||||
|
if (authErr) return { error: authErr };
|
||||||
|
const msg = player.pause() || "Paused successfully";
|
||||||
|
return { message: msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "resumePlayback": {
|
||||||
|
const player = this._getPlayerById(params.data.player);
|
||||||
|
if (!player) return { error: "Player not found" };
|
||||||
|
const authErr = this._authorizePlayerControl(user, player);
|
||||||
|
if (authErr) return { error: authErr };
|
||||||
|
const msg = player.resume() || "Resumed successfully";
|
||||||
|
return { message: msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "skip": {
|
||||||
|
const player = this._getPlayerById(params.data.player);
|
||||||
|
if (!player) return { error: "Player not found" };
|
||||||
|
const authErr = this._authorizePlayerControl(user, player);
|
||||||
|
if (authErr) return { error: authErr };
|
||||||
|
const msg = player.skip() || "Skipped song";
|
||||||
|
return { message: msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "volume": {
|
||||||
|
const player = this._getPlayerById(params.data.player);
|
||||||
|
if (!player) return { error: "Player not found" };
|
||||||
|
const authErr = this._authorizePlayerControl(user, player);
|
||||||
|
if (authErr) return { error: authErr };
|
||||||
|
const vol = Number(params.data.volume);
|
||||||
|
if (isNaN(vol) || vol < 0 || vol > 2) return {
|
||||||
|
error: "Volume must be between 0 and 2" };
|
||||||
|
const msg = player.setVolume(vol);
|
||||||
|
return { message: msg };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "addToQueue": {
|
||||||
|
const player = this._getPlayerById(params.data.player);
|
||||||
|
if (!player) return { error: "Player not found" };
|
||||||
|
if (!user) return { error: "Invalid user" };
|
||||||
|
const authErr = this._authorizePlayerControl(user, player);
|
||||||
|
if (authErr) return { error: authErr };
|
||||||
|
const type = params.data.type;
|
||||||
|
const query = params.data.query;
|
||||||
|
if (!query || typeof query !== "string") return { error: "Missing or invalid query" };
|
||||||
|
if (query.length > 500) return { error: "Query too long (max 500 characters)" };
|
||||||
|
if (type === "radio") {
|
||||||
|
const radio = this.remix.config.radio.find(e => e.name === query);
|
||||||
|
if (!radio) return { error: "Invalid radio station" };
|
||||||
|
player.playRadio(radio);
|
||||||
|
return { message: "Adding radio station" };
|
||||||
|
}
|
||||||
|
if (/^(javascript|data|vbscript):/i.test(query.trim())) {
|
||||||
|
return { error: "Invalid query protocol" };
|
||||||
|
}
|
||||||
|
player.play(query);
|
||||||
|
return { message: "Adding to queue" };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "testConnection": {
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "voiceState": {
|
||||||
|
if (!user) return { channel: null };
|
||||||
|
const userId = cleanId(user.id);
|
||||||
|
if (this.remix.voiceCache) {
|
||||||
|
for (const [mapUserId, info] of this.remix.voiceCache) {
|
||||||
|
if (cleanId(mapUserId) === userId && info.channelId) {
|
||||||
|
const ch = this.remix.client.channels.get(info.channelId);
|
||||||
|
return {
|
||||||
|
channelId: info.channelId,
|
||||||
|
channel: ch ? Dashboard.convertChannel(ch) : { id: info.channelId, name: "Unknown" },
|
||||||
|
guildId: info.guildId ?? ch?.guildId ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const guilds = this.remix.client.guilds;
|
||||||
|
const guildValues = guilds && typeof guilds.values === "function"
|
||||||
|
? [...guilds.values()] : guilds ? Object.values(guilds) : [];
|
||||||
|
for (const guild of guildValues) {
|
||||||
|
for (const vs of iterateVoiceStates(guild)) {
|
||||||
|
const stateUserId = cleanId(vs.userId);
|
||||||
|
if (stateUserId === userId && vs.channelId) {
|
||||||
|
const ch = this.remix.client.channels.get(vs.channelId);
|
||||||
|
return {
|
||||||
|
channelId: vs.channelId,
|
||||||
|
channel: ch ? Dashboard.convertChannel(ch) : { id: vs.channelId, name: "Unknown" },
|
||||||
|
guildId: guild.id,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { channel: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
case "leave": {
|
||||||
|
if (!user) return { error: "Invalid user" };
|
||||||
|
const playerId = params.data.channel ?? params.data.player;
|
||||||
|
const player = this._getPlayerById(playerId);
|
||||||
|
if (!player) return { error: "Player not found" };
|
||||||
|
const authErr = await this._authorizeUserInGuild(user, player._guildId);
|
||||||
|
if (authErr) return { error: authErr };
|
||||||
|
if (player._dashboardUsers && user) {
|
||||||
|
const idx = player._dashboardUsers.indexOf(String(user.id));
|
||||||
|
if (idx !== -1) player._dashboardUsers.splice(idx, 1);
|
||||||
|
}
|
||||||
|
if (player._dashboardUsers && player._dashboardUsers.length > 0) {
|
||||||
|
try {
|
||||||
|
const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client;
|
||||||
|
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||||
|
pubChannel.publish("fluxer:player_" + playerId, JSON.stringify({
|
||||||
|
type: "leave",
|
||||||
|
data: String(user.id)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
|
||||||
|
return { message: "Left channel" };
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await player.leave();
|
||||||
|
return { message: "Left channel" };
|
||||||
|
} catch (e) {
|
||||||
|
return { error: "Failed to leave: " + e.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
return { error: "Unknown function: " + (params.func ?? "(none)") };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that the given user is allowed to control the given player.
|
||||||
|
* Bot owners bypass the check; otherwise the user must be in the same voice channel.
|
||||||
|
* @private
|
||||||
|
* @param {object} user - The user attempting to control the player.
|
||||||
|
* @param {object} player - The Player instance to control.
|
||||||
|
* @returns {string|null} An error message if unauthorized, or null if authorized.
|
||||||
|
*/
|
||||||
|
_authorizePlayerControl(user, player) {
|
||||||
|
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null;
|
||||||
|
if (!user) return "User not provided";
|
||||||
|
|
||||||
|
const cleanUserId = cleanId(user.id);
|
||||||
|
const cleanChanId = cleanId(player._channelId);
|
||||||
|
if (!cleanChanId) return "Player has no active channel";
|
||||||
|
|
||||||
|
const observed = this.remix.voiceCache;
|
||||||
|
if (observed) {
|
||||||
|
const guildId = cleanId(player._guildId);
|
||||||
|
const userLoc = observed.get(cleanUserId, guildId || undefined);
|
||||||
|
if (userLoc) {
|
||||||
|
const infoChannelId = cleanId(userLoc.channelId);
|
||||||
|
if (infoChannelId === cleanChanId) return null;
|
||||||
|
}
|
||||||
|
for (const [mapUserId, info] of observed) {
|
||||||
|
if (cleanId(mapUserId) === cleanUserId) {
|
||||||
|
const infoChannelId = cleanId(info.channelId);
|
||||||
|
if (infoChannelId === cleanChanId) return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "You must be in the same voice channel as the bot to control playback";
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify that the given user is a member of the specified guild.
|
||||||
|
* Bot owners bypass the check.
|
||||||
|
* @private
|
||||||
|
* @async
|
||||||
|
* @param {object} user - The user to verify.
|
||||||
|
* @param {string} guildId - The guild ID to check membership in.
|
||||||
|
* @returns {Promise<string|null>} An error message if not a member, or null if authorized.
|
||||||
|
*/
|
||||||
|
async _authorizeUserInGuild(user, guildId) {
|
||||||
|
if (this.remix.handler?.owners?.includes?.(user.id)) return null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const guild = this.remix.client.guilds.get(guildId);
|
||||||
|
if (!guild) return "Server not found";
|
||||||
|
const member = await guild.members.fetch(user.id).catch(() => null);
|
||||||
|
if (!member) return "You are not a member of this server";
|
||||||
|
return null;
|
||||||
|
} catch (e) {
|
||||||
|
return "Failed to verify membership: " + e.message;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Look up a player by channel ID, guild ID, or player ID.
|
||||||
|
* @private
|
||||||
|
* @param {string} id - Channel ID, guild ID, or player ID.
|
||||||
|
* @returns {object|null} The matching Player instance, or null.
|
||||||
|
*/
|
||||||
|
_getPlayerById(id) {
|
||||||
|
return this.remix.players.playerMap.get(id)
|
||||||
|
?? [...this.remix.players.playerMap.values()].find(
|
||||||
|
p => p._channelId === id || p._guildId === id
|
||||||
|
)
|
||||||
|
?? null;
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify a dashboard login code for a user.
|
||||||
|
* @async
|
||||||
|
* @param {string} user - The user ID.
|
||||||
|
* @param {string} code - The login code to verify.
|
||||||
|
* @returns {Promise<string|null>} An error message if verification fails, or null on success.
|
||||||
|
*/
|
||||||
|
async confirmLogin(user, code) {
|
||||||
|
if (!this.enabled) return "Dashboard not enabled.";
|
||||||
|
if (!this.db) return "Dashboard database not configured.";
|
||||||
|
|
||||||
|
let res;
|
||||||
|
try {
|
||||||
|
res = await this.db.execute("SELECT * FROM login_codes WHERE user=? AND (verified IS NULL OR verified !== true)", [user]);
|
||||||
|
} catch (e) {
|
||||||
|
const id = Utils.uid();
|
||||||
|
logger.dashboard("[Dashboard] MySQL error, id:", id, e);
|
||||||
|
return "An error occurred, please contact an administrator if this happens again. Error id: `" + id + "`";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (res.length === 0) return "If this is a valid code, it was not created for your account.";
|
||||||
|
|
||||||
|
for (let i = 0; i < res.length; i++) {
|
||||||
|
if (res[i].verified) continue;
|
||||||
|
if (await this.db.compareHash(code, res[i].token)) {
|
||||||
|
if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) {
|
||||||
|
return "Login token expired";
|
||||||
|
}
|
||||||
|
await this.db.execute("UPDATE login_codes SET verified=true WHERE id=?", [res[i].id]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Invalid code.";
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default RpcHandlersMixin;
|
||||||
|
export { RpcHandlersMixin };
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
/**
|
||||||
|
* @module dashboard/Serializers
|
||||||
|
* @description Static data-conversion helpers for {@link Dashboard}: turn
|
||||||
|
* users, videos/tracks, channels, guilds, players and commands into
|
||||||
|
* dashboard-safe plain objects.
|
||||||
|
*
|
||||||
|
* This plain object is attached to the Dashboard class as static methods via
|
||||||
|
* `Object.assign(Dashboard, Serializers)` at the bottom of Dashboard.mjs, so
|
||||||
|
* `Dashboard.convertChannel(...)`, `Dashboard.convertPlayer(...)`, etc. keep
|
||||||
|
* working for external callers.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Dashboard } from "./Dashboard.mjs";
|
||||||
|
import { Utils, cleanId } from "../utils/Utils.mjs";
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
import { iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @type {object}
|
||||||
|
* @description Serializers — attached to Dashboard as static methods.
|
||||||
|
*/
|
||||||
|
const Serializers = {
|
||||||
|
/**
|
||||||
|
* Convert a user object to a dashboard-safe plain object.
|
||||||
|
* @static
|
||||||
|
* @param {object} user - The user.
|
||||||
|
* @returns {{ id: string, username: string, displayName: string, avatar: { url: string } }}
|
||||||
|
*/
|
||||||
|
convertUser(user) {
|
||||||
|
let avatarUrl = "";
|
||||||
|
if (user.avatar) {
|
||||||
|
avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`;
|
||||||
|
} else if (typeof user.displayAvatarURL === "function") {
|
||||||
|
try { avatarUrl = user.displayAvatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] displayAvatarURL:", e?.message); }
|
||||||
|
} else if (typeof user.avatarURL === "function") {
|
||||||
|
try { avatarUrl = user.avatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] avatarURL:", e?.message); }
|
||||||
|
}
|
||||||
|
if (!avatarUrl) {
|
||||||
|
avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.id?.slice(-4) ?? "0") % 5}.png`;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
displayName: user.displayName ?? user.globalName ?? user.username,
|
||||||
|
avatar: {
|
||||||
|
url: avatarUrl,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a video/track object to a dashboard-safe plain object.
|
||||||
|
* @static
|
||||||
|
* @param {object} vid - The video/track object from the player queue.
|
||||||
|
* @returns {object|null} Sanitised video data, or null if input is falsy.
|
||||||
|
*/
|
||||||
|
convertVideo(vid) {
|
||||||
|
if (!vid) return null;
|
||||||
|
const durationMs =
|
||||||
|
typeof vid.duration === "number" ? vid.duration :
|
||||||
|
typeof vid.duration === "object" && vid.duration?.seconds !== null ? vid.duration.seconds * 1000 :
|
||||||
|
0;
|
||||||
|
return {
|
||||||
|
title: vid.title,
|
||||||
|
url: vid.type === "radio" ? vid.author?.url : vid.url,
|
||||||
|
videoId: vid.videoId,
|
||||||
|
type: vid.type,
|
||||||
|
duration: vid.type === "radio" ? "--:--" : Utils.prettifyMS(durationMs),
|
||||||
|
description: vid.description,
|
||||||
|
artist: {
|
||||||
|
name: vid.author?.name ?? vid.artist,
|
||||||
|
url: vid.author?.url,
|
||||||
|
},
|
||||||
|
thumbnail: vid.thumbnail,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a channel to a dashboard-safe plain object, including
|
||||||
|
* voice participant info for voice channels.
|
||||||
|
* @static
|
||||||
|
* @param {object} channel - The channel.
|
||||||
|
* @returns {object} Sanitised channel data.
|
||||||
|
*/
|
||||||
|
convertChannel(channel) {
|
||||||
|
const type = channel.type ?? 0;
|
||||||
|
const isVoice = channel.isVoice?.() || type === 2;
|
||||||
|
const isCategory = type === 4;
|
||||||
|
const isText = !isVoice && !isCategory && (
|
||||||
|
type === 0 || type === 5 || type === 13 ||
|
||||||
|
(typeof channel.isText === "function" && channel.isText())
|
||||||
|
);
|
||||||
|
let voiceParticipants = [];
|
||||||
|
if (isVoice) {
|
||||||
|
const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||||
|
for (const vs of iterateVoiceStates(guild)) {
|
||||||
|
const scId = cleanId(vs.channelId);
|
||||||
|
const chId = cleanId(channel?.id);
|
||||||
|
if (scId === chId) {
|
||||||
|
const user = guild?.members?.get?.(vs.userId)?.user;
|
||||||
|
if (user && !user.bot) voiceParticipants.push(Dashboard.convertUser(user));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: channel.name,
|
||||||
|
displayName: channel.name,
|
||||||
|
id: channel.id,
|
||||||
|
icon: null,
|
||||||
|
description: channel.topic ?? null,
|
||||||
|
type,
|
||||||
|
isVoice,
|
||||||
|
isCategory,
|
||||||
|
isText,
|
||||||
|
parentId: channel.parentId ?? channel.parent_id ?? null,
|
||||||
|
voiceParticipants,
|
||||||
|
mature: channel.nsfw ?? false,
|
||||||
|
serverId: channel.guildId,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a guild (server) to a dashboard-safe plain object with channels.
|
||||||
|
* @static
|
||||||
|
* @param {object} guild - The guild.
|
||||||
|
* @returns {object} Sanitised server data including channels and voice channels.
|
||||||
|
*/
|
||||||
|
convertServer(guild) {
|
||||||
|
const channelStore = guild.channels;
|
||||||
|
const channelIds = channelStore && typeof channelStore.keys === "function"
|
||||||
|
? [...channelStore.keys()]
|
||||||
|
: [];
|
||||||
|
const channelValues = channelStore && typeof channelStore.values === "function"
|
||||||
|
? [...channelStore.values()]
|
||||||
|
: [];
|
||||||
|
const allChannels = channelValues
|
||||||
|
.map(Dashboard.convertChannel)
|
||||||
|
.filter(c => !c.isCategory);
|
||||||
|
|
||||||
|
let iconUrl = null;
|
||||||
|
if (guild.icon) {
|
||||||
|
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
||||||
|
} else if (typeof guild.iconURL === "function") {
|
||||||
|
try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
name: guild.name,
|
||||||
|
id: guild.id,
|
||||||
|
icon: iconUrl,
|
||||||
|
channelIds,
|
||||||
|
description: guild.description ?? null,
|
||||||
|
ownerId: guild.ownerId,
|
||||||
|
channels: allChannels,
|
||||||
|
voiceChannels: allChannels.filter(c => c.isVoice),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a guild to a lightweight summary object (no channels).
|
||||||
|
* @static
|
||||||
|
* @param {object} guild - The guild.
|
||||||
|
* @returns {{ name: string, id: string, icon: string|null, description: string|null, ownerId: string|null }}
|
||||||
|
*/
|
||||||
|
convertServerSummary(guild) {
|
||||||
|
let iconUrl = null;
|
||||||
|
if (guild.icon) {
|
||||||
|
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
||||||
|
} else if (typeof guild.iconURL === "function") {
|
||||||
|
try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; }
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
name: guild.name,
|
||||||
|
id: guild.id,
|
||||||
|
icon: iconUrl,
|
||||||
|
description: guild.description ?? null,
|
||||||
|
ownerId: guild.ownerId,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a Player instance to a dashboard-safe serialisable object.
|
||||||
|
* Includes queue, users, channel, and server info.
|
||||||
|
* @static
|
||||||
|
* @param {object} player - The Player instance.
|
||||||
|
* @returns {object} Sanitised player data.
|
||||||
|
*/
|
||||||
|
convertPlayer(player) {
|
||||||
|
const channelId = player._channelId;
|
||||||
|
const channel = channelId ? player.client?.channels?.get(channelId) : null;
|
||||||
|
const guild = channel?.guild ?? (player._guildId ? player.client?.guilds?.get(player._guildId) : null);
|
||||||
|
const cleanChannelId = channelId ? cleanId(channelId) : "";
|
||||||
|
const cleanGuildId = player._guildId ? cleanId(player._guildId) : "";
|
||||||
|
|
||||||
|
const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] };
|
||||||
|
|
||||||
|
return {
|
||||||
|
loop: (queue.loop ? 1 : 0) + (queue.songLoop ? 2 : 0),
|
||||||
|
paused: !!player._paused,
|
||||||
|
volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume * 100 : 100,
|
||||||
|
queue: {
|
||||||
|
current: Dashboard.convertVideo(queue.current),
|
||||||
|
data: Array.isArray(queue.data) ? queue.data.slice(0, 500).map(v => Dashboard.convertVideo(v)) : [],
|
||||||
|
},
|
||||||
|
users: (() => {
|
||||||
|
if (!channel) return player._dashboardUsers ?? [];
|
||||||
|
const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||||
|
const ids = [];
|
||||||
|
const seen = new Set();
|
||||||
|
for (const vs of iterateVoiceStates(g)) {
|
||||||
|
const scId = cleanId(vs.channelId);
|
||||||
|
const chId = cleanId(channel?.id);
|
||||||
|
if (scId === chId) {
|
||||||
|
const memberId = vs.userId;
|
||||||
|
if (memberId) { ids.push(memberId); seen.add(memberId); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const vc = player._voiceCache ?? player._observedVoiceUsers;
|
||||||
|
if (vc && cleanChannelId && cleanGuildId) {
|
||||||
|
if (typeof vc.getHumansInChannel === "function") {
|
||||||
|
const channelHumans = vc.getHumansInChannel(cleanGuildId, cleanChannelId);
|
||||||
|
for (const hid of channelHumans) {
|
||||||
|
if (seen.has(hid)) continue;
|
||||||
|
const botId = player.client?.user?.id;
|
||||||
|
if (botId && String(hid) === String(botId)) continue;
|
||||||
|
ids.push(String(hid));
|
||||||
|
seen.add(hid);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const [mapUserId, info] of vc) {
|
||||||
|
if (seen.has(mapUserId)) continue;
|
||||||
|
const infoCh = cleanId(info.channelId);
|
||||||
|
const infoG = cleanId(info.guildId);
|
||||||
|
if (infoCh === cleanChannelId && infoG === cleanGuildId) {
|
||||||
|
const botId = player.client?.user?.id;
|
||||||
|
if (botId && String(mapUserId) === String(botId)) continue;
|
||||||
|
ids.push(String(mapUserId));
|
||||||
|
seen.add(mapUserId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (player._dashboardUsers) {
|
||||||
|
for (const du of player._dashboardUsers) {
|
||||||
|
if (!seen.has(du)) { ids.push(du); seen.add(du); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
})(),
|
||||||
|
channel: channel ? Dashboard.convertChannel(channel) : null,
|
||||||
|
server: guild ? Dashboard.convertServerSummary(guild) : null,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a command option to a dashboard-safe plain object.
|
||||||
|
* @static
|
||||||
|
* @param {object} opt - The command option.
|
||||||
|
* @returns {object} Sanitised option data.
|
||||||
|
*/
|
||||||
|
convertOption(opt) {
|
||||||
|
return {
|
||||||
|
type: opt.type,
|
||||||
|
name: opt.name,
|
||||||
|
choices: opt.choices,
|
||||||
|
description: opt.description,
|
||||||
|
required: opt.required,
|
||||||
|
uid: opt.uid,
|
||||||
|
defaultValue: opt.defaultValue,
|
||||||
|
dynamicDefaultPresent: !!opt.dynamicDefault,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a command (and its subcommands/options) to a dashboard-safe plain object.
|
||||||
|
* @static
|
||||||
|
* @param {object} com - The command object.
|
||||||
|
* @param {object} commands - The CommandHandler instance (for usage generation).
|
||||||
|
* @returns {object} Sanitised command data.
|
||||||
|
*/
|
||||||
|
convertCommand(com, commands) {
|
||||||
|
return {
|
||||||
|
name: com.name,
|
||||||
|
description: com.description,
|
||||||
|
uid: com.uid,
|
||||||
|
aliases: com.aliases,
|
||||||
|
subcommands: com.subcommands.map(c => Dashboard.convertCommand(c, commands)),
|
||||||
|
category: com.category,
|
||||||
|
examples: com.examples,
|
||||||
|
usage: commands.helpHandler?.commandUsage?.(com, {
|
||||||
|
message: { guildId: null },
|
||||||
|
}) ?? null,
|
||||||
|
options: com.options.map(o => Dashboard.convertOption(o)),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Serializers;
|
||||||
|
export { Serializers };
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
/**
|
||||||
|
* @module dashboard
|
||||||
|
* @description Barrel for the dashboard layer — re-exports the Dashboard class.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export { Dashboard } from "./Dashboard.mjs";
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
/**
|
||||||
|
* @module src/db/DatabaseManager
|
||||||
|
* @description MySQL connection pool wrapper for the dashboard. Provides parameterised
|
||||||
|
* query execution and bcrypt hashing utilities for login code management.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { compare, genSalt, hash } from "bcryptjs";
|
||||||
|
import { createPool } from "mysql2/promise";
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @class
|
||||||
|
* @description Wraps a mysql2 connection pool with convenience methods for
|
||||||
|
* parameterised queries and bcrypt hash operations.
|
||||||
|
*/
|
||||||
|
export class DatabaseManager {
|
||||||
|
/**
|
||||||
|
* Create a new DatabaseManager.
|
||||||
|
* @param {object} config - mysql2 pool configuration (host, user, password, database, etc.).
|
||||||
|
*/
|
||||||
|
constructor(config) {
|
||||||
|
this.db = createPool({
|
||||||
|
connectionLimit: 15,
|
||||||
|
...config,
|
||||||
|
});
|
||||||
|
this.db.on("error", (err) => {
|
||||||
|
logger.error("[DashboardDB] MySQL pool error:", err.code ?? err.message);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a raw SQL query (no parameter binding).
|
||||||
|
* @async
|
||||||
|
* @param {string} query - The SQL query string.
|
||||||
|
* @returns {Promise<Array>} The query result rows and fields.
|
||||||
|
*/
|
||||||
|
async query(query) {
|
||||||
|
return this.db.query(query);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a parameterised SQL query.
|
||||||
|
* @async
|
||||||
|
* @param {string} query - The SQL query with `?` placeholders.
|
||||||
|
* @param {Array} data - The values to bind.
|
||||||
|
* @returns {Promise<Array>} The result rows.
|
||||||
|
*/
|
||||||
|
async execute(query, data) {
|
||||||
|
const [res, _fields] = await this.db.execute(query, data);
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a bcrypt hash of the given plaintext.
|
||||||
|
* @async
|
||||||
|
* @param {string} plain - The plaintext string.
|
||||||
|
* @returns {Promise<string>} The hashed string.
|
||||||
|
*/
|
||||||
|
async hash(plain) {
|
||||||
|
const salt = await genSalt(10);
|
||||||
|
return hash(plain, salt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compare a plaintext string against a bcrypt hash.
|
||||||
|
* @async
|
||||||
|
* @param {string} plain - The plaintext string.
|
||||||
|
* @param {string} hashed - The bcrypt hash.
|
||||||
|
* @returns {Promise<boolean>} True if the plaintext matches the hash.
|
||||||
|
*/
|
||||||
|
async compareHash(plain, hashed) {
|
||||||
|
return await compare(plain, hashed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close the underlying MySQL connection pool.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
close() {
|
||||||
|
return this.db.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* @module src/Settings
|
* @module src/db/Settings
|
||||||
* @description MySQL-backed settings system for per-guild bot configuration.
|
* @description MySQL-backed settings system for per-guild bot configuration.
|
||||||
* Supports debounced writes (80ms), multi-bot via bot_id column, and
|
* Supports debounced writes (80ms), multi-bot via bot_id column, and
|
||||||
* automatic schema migration for legacy tables.
|
* automatic schema migration for legacy tables.
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
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 { logger } from "./constants/Logger.mjs";
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Base settings manager providing defaults, descriptions, and key utilities.
|
* Base settings manager providing defaults, descriptions, and key utilities.
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
/** @module src/LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. */
|
/** @module src/music/LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. */
|
||||||
|
|
||||||
import { LavalinkManager as LavalinkClientManager, NodeType } from "lavalink-client";
|
import { LavalinkManager as LavalinkClientManager, NodeType } from "lavalink-client";
|
||||||
import { logger, _wsErrorCooldown } from "./constants/Logger.mjs";
|
import { logger, _wsErrorCooldown } from "../core/Logger.mjs";
|
||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
import { Events } from "@fluxerjs/core";
|
import { Events } from "@fluxerjs/core";
|
||||||
import { getVoiceManager } from "@fluxerjs/voice";
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
|
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
|
||||||
|
|
||||||
/** @class LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. Wraps the lavalink-client library and provides node lifecycle management, search, player creation, and WebSocket payload interception. @extends {EventEmitter} */
|
/** @class LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. Wraps the lavalink-client library and provides node lifecycle management, search, player creation, and WebSocket payload interception. @extends {EventEmitter} */
|
||||||
export class LavalinkManager extends EventEmitter {
|
export class LavalinkManager extends EventEmitter {
|
||||||
@@ -23,7 +24,7 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
/** @private @type {Map<string, object>} @description Cached VOICE_SERVER_UPDATE payloads keyed by guild ID. */
|
/** @private @type {Map<string, object>} @description Cached VOICE_SERVER_UPDATE payloads keyed by guild ID. */
|
||||||
_cachedVoiceServerUpdates = new Map();
|
_cachedVoiceServerUpdates = new Map();
|
||||||
|
|
||||||
/** Create a new LavalinkManager and initialize the underlying lavalink-client connection. @param {object} nodeCfg - Node configuration (id, host, port, password, secure). @param {object} client - Discord bot client instance. @param {object} user - Bot user object with id and username. */
|
/** Create a new LavalinkManager and initialize the underlying lavalink-client connection. @param {object} nodeCfg - Node configuration (id, host, port, password, secure). @param {object} client - bot client instance. @param {object} user - Bot user object with id and username. */
|
||||||
constructor(nodeCfg, client, user) {
|
constructor(nodeCfg, client, user) {
|
||||||
super();
|
super();
|
||||||
this.setMaxListeners(50);
|
this.setMaxListeners(50);
|
||||||
@@ -178,12 +179,16 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Fluxer 3.0 sharding: gateway payloads are guild-scoped — route to the
|
||||||
|
// shard that owns this guild (single process: always shard 0, as before).
|
||||||
|
const targetShardId = ShardingUtils.shardIdForGuild(this._client, guildId);
|
||||||
|
|
||||||
if (typeof this._client?.ws?.send === "function") {
|
if (typeof this._client?.ws?.send === "function") {
|
||||||
this._client.ws.send(0, payload);
|
this._client.ws.send(targetShardId, payload);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const shard = this._client?.ws?.shards?.get?.(0);
|
const shard = ShardingUtils.getShard(this._client, targetShardId);
|
||||||
if (!shard) {
|
if (!shard) {
|
||||||
logger.warn("[LavalinkManager] No WebSocket shard available");
|
logger.warn("[LavalinkManager] No WebSocket shard available");
|
||||||
return;
|
return;
|
||||||
@@ -206,24 +211,31 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
|
|
||||||
const attachRawWs = () => {
|
const attachRawWs = () => {
|
||||||
try {
|
try {
|
||||||
const shard0 = client.ws?.shards?.get?.(0);
|
// Fluxer 3.0 + sharding: getShards() replaces the 2.2 `shards` Map
|
||||||
const wsObj = shard0?.ws ?? null;
|
// property, and a sharded child owns several shards — track the raw
|
||||||
if (!wsObj) return;
|
// socket of EVERY local shard, not just shard 0.
|
||||||
|
const wsObjs = ShardingUtils.localShardSockets(client);
|
||||||
|
if (wsObjs.length === 0) return;
|
||||||
|
|
||||||
if (this._rawWsHandler && this._rawWsObj && this._rawWsObj !== wsObj) {
|
if (!this._rawWsObjs) this._rawWsObjs = new Set();
|
||||||
|
const attached = this._rawWsObjs;
|
||||||
|
|
||||||
|
// Detach listeners from sockets that went away (reconnects).
|
||||||
|
for (const old of attached) {
|
||||||
|
if (wsObjs.includes(old)) continue;
|
||||||
try {
|
try {
|
||||||
if (typeof this._rawWsObj.removeEventListener === "function") {
|
if (typeof old.removeEventListener === "function") {
|
||||||
this._rawWsObj.removeEventListener(
|
old.removeEventListener(
|
||||||
"message",
|
"message",
|
||||||
this._rawWsMessageListener ?? this._rawWsHandler
|
this._rawWsMessageListener ?? this._rawWsHandler
|
||||||
);
|
);
|
||||||
this._rawWsObj.removeEventListener("error", this._rawWsErrorHandler);
|
old.removeEventListener("error", this._rawWsErrorHandler);
|
||||||
} else if (typeof this._rawWsObj.off === "function") {
|
} else if (typeof old.off === "function") {
|
||||||
this._rawWsObj.off(
|
old.off(
|
||||||
"message",
|
"message",
|
||||||
this._rawWsMessageListener ?? this._rawWsHandler
|
this._rawWsMessageListener ?? this._rawWsHandler
|
||||||
);
|
);
|
||||||
this._rawWsObj.off("error", this._rawWsErrorHandler);
|
old.off("error", this._rawWsErrorHandler);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
@@ -231,10 +243,11 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
e?.message
|
e?.message
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
attached.delete(old);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (wsObj === this._rawWsObj) return;
|
// Create the shared handlers once (stateless parsers).
|
||||||
|
if (!this._rawWsHandler) {
|
||||||
const botId = this._client?.user?.id;
|
const botId = this._client?.user?.id;
|
||||||
let _vsuLogCooldown = 0;
|
let _vsuLogCooldown = 0;
|
||||||
let _vsuBotLogCooldown = 0;
|
let _vsuBotLogCooldown = 0;
|
||||||
@@ -290,6 +303,10 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
|
|
||||||
this._rawWsMessageListener = (event) =>
|
this._rawWsMessageListener = (event) =>
|
||||||
this._rawWsHandler(event?.data ?? event);
|
this._rawWsHandler(event?.data ?? event);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const wsObj of wsObjs) {
|
||||||
|
if (attached.has(wsObj)) continue;
|
||||||
|
|
||||||
if (typeof wsObj.addEventListener === "function") {
|
if (typeof wsObj.addEventListener === "function") {
|
||||||
wsObj.addEventListener("message", this._rawWsMessageListener);
|
wsObj.addEventListener("message", this._rawWsMessageListener);
|
||||||
@@ -299,7 +316,11 @@ export class LavalinkManager extends EventEmitter {
|
|||||||
wsObj.on("error", this._rawWsErrorHandler);
|
wsObj.on("error", this._rawWsErrorHandler);
|
||||||
}
|
}
|
||||||
|
|
||||||
this._rawWsObj = wsObj;
|
attached.add(wsObj);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Legacy singular field kept in sync (first socket).
|
||||||
|
this._rawWsObj = wsObjs[0] ?? null;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[LavalinkManager] Raw WS setup error:", e.message);
|
logger.warn("[LavalinkManager] Raw WS setup error:", e.message);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
/**
|
||||||
|
* @module src/music/PlayerEventsMixin
|
||||||
|
* @description Dashboard event wiring concern for {@link PlayerManager}:
|
||||||
|
* binds dashboard update/queue/message events onto spawned players,
|
||||||
|
* forwards now-playing updates to Last.fm with scrobble scheduling, and
|
||||||
|
* translates locale keys for message contexts.
|
||||||
|
*
|
||||||
|
* These methods are applied onto the PlayerManager class prototype via
|
||||||
|
* {@link applyMixins} (see src/music/PlayerManager.mjs) — `this` is a
|
||||||
|
* PlayerManager instance.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { cleanId } from "../utils/Utils.mjs";
|
||||||
|
import { getMessageGuildId } from "../ui/index.mjs";
|
||||||
|
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||||
|
|
||||||
|
// Module-level ID helpers from the original PlayerManager.mjs. They live in
|
||||||
|
// this module (not the base file) because it is the shared leaf of the three
|
||||||
|
// PlayerManager modules, which keeps the import graph acyclic:
|
||||||
|
// PlayerManager.mjs → PlayerEventsMixin.mjs ← PlayerLifecycleMixin.mjs.
|
||||||
|
/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */
|
||||||
|
function getPlayerGuildId(player, fallbackChannel = null) {
|
||||||
|
return cleanId(
|
||||||
|
player?._guildId ??
|
||||||
|
fallbackChannel?.guildId ??
|
||||||
|
fallbackChannel?.guild?.id ??
|
||||||
|
fallbackChannel?.server_id ??
|
||||||
|
fallbackChannel?.serverId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @private @param {Player} player @param {string|null} [fallbackChannelId=null] @returns {string} Cleaned channel ID. */
|
||||||
|
function getPlayerChannelId(player, fallbackChannelId = null) {
|
||||||
|
return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId);
|
||||||
|
}
|
||||||
|
export { getPlayerGuildId, getPlayerChannelId };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @type {object}
|
||||||
|
* @description Player events mixin — applied to PlayerManager.
|
||||||
|
*/
|
||||||
|
const PlayerEventsMixin = {
|
||||||
|
/** Bind dashboard update and message-sending events on a player. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {object} [context={}] @returns {Player} The same player, with events bound. */
|
||||||
|
setupEvents(player, context = {}) {
|
||||||
|
if (!player || player._dashboardEventsBound) return player;
|
||||||
|
|
||||||
|
Object.defineProperty(player, "_dashboardEventsBound", {
|
||||||
|
value: true,
|
||||||
|
configurable: true,
|
||||||
|
enumerable: false,
|
||||||
|
writable: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const emit = (type, data) => {
|
||||||
|
if (!this.dashboard?.enabled) return;
|
||||||
|
this.dashboard.updatePlayer({ type, data }, player);
|
||||||
|
};
|
||||||
|
|
||||||
|
const emitGlobal = (type) => {
|
||||||
|
if (!this.dashboard?.enabled) return;
|
||||||
|
this.dashboard.playerUpdate({ type }, player);
|
||||||
|
};
|
||||||
|
|
||||||
|
const sendUserUpdates = (eventType) => {
|
||||||
|
if (!this.dashboard?.enabled) return;
|
||||||
|
const channelId = getPlayerChannelId(player, context.channelId);
|
||||||
|
const channel = player.client?.channels?.get(channelId);
|
||||||
|
const guild = player.client?.guilds?.get(cleanId(player._guildId ?? context.guildId));
|
||||||
|
if (!guild) return;
|
||||||
|
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
||||||
|
if (!voiceStates) return;
|
||||||
|
const entries = Array.isArray(voiceStates)
|
||||||
|
? voiceStates
|
||||||
|
: typeof voiceStates.values === "function"
|
||||||
|
? [...voiceStates.values()]
|
||||||
|
: Object.values(voiceStates);
|
||||||
|
for (const state of entries) {
|
||||||
|
if (!state?.channelId && !state?.channel_id) continue;
|
||||||
|
const stateChannelId = cleanId(state.channelId ?? state.channel_id);
|
||||||
|
if (stateChannelId !== channelId) continue;
|
||||||
|
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
||||||
|
if (!member?.user || member.user?.bot) continue;
|
||||||
|
emit(eventType, member.user.id);
|
||||||
|
this.dashboard.userUpdate({
|
||||||
|
type: eventType,
|
||||||
|
guildId: cleanId(player._guildId ?? context.guildId),
|
||||||
|
channelId,
|
||||||
|
}, member.user);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
player.on("roomfetched", () => {
|
||||||
|
emitGlobal("init");
|
||||||
|
sendUserUpdates("join");
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("startplay", (song) => {
|
||||||
|
emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current));
|
||||||
|
emit("streamStartPlay", Date.now());
|
||||||
|
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
||||||
|
|
||||||
|
if (this._lastfm?.enabled && song) {
|
||||||
|
this._handleLastFmStartPlay(player, song);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("stopplay", () => {
|
||||||
|
emit("stopplay", null);
|
||||||
|
this.dashboard.playerUpdate({ type: "stopplay" }, player);
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("playback", (playing) => {
|
||||||
|
const elapsedMs = player._pausedAt
|
||||||
|
? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) -
|
||||||
|
(player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0))
|
||||||
|
: Date.now() - (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0));
|
||||||
|
const type = playing ? "resume" : "pause";
|
||||||
|
emit(type, { elapsedTime: Math.max(0, elapsedMs) });
|
||||||
|
this.dashboard.playerUpdate({ type }, player);
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("volume", (volume) => {
|
||||||
|
emit("volume", volume);
|
||||||
|
this.dashboard.playerUpdate({ type: "volume" }, player);
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("filter", (filter) => {
|
||||||
|
emit("filter", filter);
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("update", (scope) => {
|
||||||
|
this.dashboard.playerUpdate({ type: "update" }, player);
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("autoleave", () => {
|
||||||
|
sendUserUpdates("leave");
|
||||||
|
emitGlobal("close");
|
||||||
|
emit("stopplay", null);
|
||||||
|
});
|
||||||
|
|
||||||
|
player.on("leave", () => {
|
||||||
|
sendUserUpdates("leave");
|
||||||
|
emitGlobal("close");
|
||||||
|
emit("stopplay", null);
|
||||||
|
});
|
||||||
|
|
||||||
|
player.queue?.on("queue", (queueEvent) => {
|
||||||
|
const serialised = { type: queueEvent.type };
|
||||||
|
switch (queueEvent.type) {
|
||||||
|
case "add":
|
||||||
|
serialised.data = {
|
||||||
|
append: queueEvent.data?.append,
|
||||||
|
data: Dashboard.convertVideo(queueEvent.data?.data),
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case "addMany":
|
||||||
|
serialised.data = {
|
||||||
|
append: queueEvent.data?.append,
|
||||||
|
tracks: (queueEvent.data?.tracks ?? []).map(v => Dashboard.convertVideo(v)),
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case "remove":
|
||||||
|
serialised.data = {
|
||||||
|
index: queueEvent.data?.index,
|
||||||
|
removed: Dashboard.convertVideo(queueEvent.data?.removed),
|
||||||
|
old: (queueEvent.data?.old ?? []).map(v => Dashboard.convertVideo(v)),
|
||||||
|
new: (queueEvent.data?.new ?? []).map(v => Dashboard.convertVideo(v)),
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case "move":
|
||||||
|
serialised.data = {
|
||||||
|
from: queueEvent.data?.from,
|
||||||
|
to: queueEvent.data?.to,
|
||||||
|
track: Dashboard.convertVideo(queueEvent.data?.track),
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case "shuffle":
|
||||||
|
serialised.data = (queueEvent.data ?? []).map(v => Dashboard.convertVideo(v));
|
||||||
|
break;
|
||||||
|
case "update":
|
||||||
|
serialised.data = {
|
||||||
|
current: Dashboard.convertVideo(queueEvent.data?.current),
|
||||||
|
old: Dashboard.convertVideo(queueEvent.data?.old),
|
||||||
|
loop: queueEvent.data?.loop,
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
serialised.data = queueEvent.data;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
emit("queue", serialised);
|
||||||
|
this.dashboard.playerUpdate({ type: "queue" }, player);
|
||||||
|
});
|
||||||
|
|
||||||
|
return player;
|
||||||
|
},
|
||||||
|
|
||||||
|
/** @private Translate a locale key for a message context. @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {string} key @param {object} [replacements={}] @returns {string} */
|
||||||
|
_t(message, key, replacements = {}) {
|
||||||
|
if (!this.locale) return key;
|
||||||
|
const guildId = getMessageGuildId(message);
|
||||||
|
return this.locale.translate(guildId, key, replacements);
|
||||||
|
},
|
||||||
|
|
||||||
|
/** @private Handle Last.fm now-playing update and schedule scrobble timer. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {object} song */
|
||||||
|
_handleLastFmStartPlay(player, song) {
|
||||||
|
const lastfm = this._lastfm;
|
||||||
|
if (!lastfm?.enabled) return;
|
||||||
|
|
||||||
|
const guildId = cleanId(player._guildId);
|
||||||
|
if (!guildId) return;
|
||||||
|
|
||||||
|
const channelId = getPlayerChannelId(player);
|
||||||
|
const humanUserIds = [];
|
||||||
|
|
||||||
|
if (this.voiceCache) {
|
||||||
|
const users = this.voiceCache.getHumansInChannel(guildId, channelId);
|
||||||
|
humanUserIds.push(...users);
|
||||||
|
} else if (this.observedVoiceUsers) {
|
||||||
|
for (const [uid, info] of this.observedVoiceUsers) {
|
||||||
|
if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) {
|
||||||
|
humanUserIds.push(uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const guild = player.client?.guilds?.get(guildId);
|
||||||
|
if (guild) {
|
||||||
|
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
||||||
|
if (voiceStates) {
|
||||||
|
const entries = Array.isArray(voiceStates)
|
||||||
|
? voiceStates
|
||||||
|
: typeof voiceStates.values === "function"
|
||||||
|
? [...voiceStates.values()]
|
||||||
|
: Object.values(voiceStates ?? {});
|
||||||
|
for (const state of entries) {
|
||||||
|
const uid = state?.userId ?? state?.user_id;
|
||||||
|
const chId = cleanId(state?.channelId ?? state?.channel_id);
|
||||||
|
if (uid && chId === channelId) {
|
||||||
|
const member = guild.members?.get?.(uid);
|
||||||
|
if (member?.user?.bot) continue;
|
||||||
|
if (!humanUserIds.includes(uid)) humanUserIds.push(uid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const startedAtMs = player.startedPlaying;
|
||||||
|
|
||||||
|
const pendingKey = channelId;
|
||||||
|
const existing = this._pendingScrobbleTimers.get(pendingKey);
|
||||||
|
if (existing) {
|
||||||
|
clearTimeout(existing.timer);
|
||||||
|
this._pendingScrobbleTimers.delete(pendingKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const userId of humanUserIds) {
|
||||||
|
lastfm.updateNowPlaying(userId, song).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
const durationMs = (() => {
|
||||||
|
const d = song.duration;
|
||||||
|
if (!d) return null;
|
||||||
|
if (typeof d === "object" && d.seconds) return d.seconds * 1000;
|
||||||
|
if (typeof d === "number") return d;
|
||||||
|
return null;
|
||||||
|
})();
|
||||||
|
|
||||||
|
if (durationMs && durationMs >= 30_000) {
|
||||||
|
const thresholdMs = Math.min(
|
||||||
|
durationMs * lastfm.scrobbleThreshold,
|
||||||
|
lastfm.scrobbleMinMs
|
||||||
|
);
|
||||||
|
if (thresholdMs <= 600_000) {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
this._pendingScrobbleTimers.delete(pendingKey);
|
||||||
|
const current = player.queue?.getCurrent();
|
||||||
|
if (!current || player._destroyed || player.leaving) return;
|
||||||
|
if (current.title !== song.title || current.url !== song.url) return;
|
||||||
|
if (player._paused) return;
|
||||||
|
|
||||||
|
const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now());
|
||||||
|
if (lastfm.shouldScrobble(song, playedMs)) {
|
||||||
|
for (const userId of humanUserIds) {
|
||||||
|
lastfm.scrobble(userId, song, startedAtMs).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, thresholdMs);
|
||||||
|
|
||||||
|
this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default PlayerEventsMixin;
|
||||||
|
export { PlayerEventsMixin };
|
||||||
@@ -1,32 +1,28 @@
|
|||||||
/** @module src/PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */
|
/**
|
||||||
|
* @module src/music/PlayerLifecycleMixin
|
||||||
|
* @description Voice-channel resolution & player lifecycle concern for
|
||||||
|
* {@link PlayerManager}: author voice-channel detection, interactive
|
||||||
|
* voice-channel selection prompt, leave, saved-volume restore, and
|
||||||
|
* spawn/join of Player instances (including join retries and the autoleave
|
||||||
|
* / now-playing announcement handlers wired inside initPlayer).
|
||||||
|
*
|
||||||
|
* These methods are applied onto the PlayerManager class prototype via
|
||||||
|
* {@link applyMixins} (see src/music/PlayerManager.mjs) — `this` is a
|
||||||
|
* PlayerManager instance.
|
||||||
|
*/
|
||||||
|
|
||||||
import Player from "./Player.mjs";
|
import Player from "./player/index.mjs";
|
||||||
import { Utils, cleanId } from "./Utils.mjs";
|
import { cleanId } from "../utils/Utils.mjs";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "../core/Logger.mjs";
|
||||||
import { get247ChannelMode } from "./constants/Helpers247.mjs";
|
import { get247ChannelMode } from "../utils/Helpers247.mjs";
|
||||||
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 "./MessageHandler.mjs";
|
import { getGlobalColor, getMessageGuildId } from "../ui/index.mjs";
|
||||||
import { Dashboard } from "./dashboard/Dashboard.mjs";
|
import { hasHumansInChannel, iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
||||||
import { hasHumansInChannel, iterateVoiceStates } from "./constants/VoiceStateResolver.mjs";
|
import { getPlayerChannelId } from "./PlayerEventsMixin.mjs";
|
||||||
|
|
||||||
|
|
||||||
/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */
|
|
||||||
function getPlayerGuildId(player, fallbackChannel = null) {
|
|
||||||
return cleanId(
|
|
||||||
player?._guildId ??
|
|
||||||
fallbackChannel?.guildId ??
|
|
||||||
fallbackChannel?.guild?.id ??
|
|
||||||
fallbackChannel?.server_id ??
|
|
||||||
fallbackChannel?.serverId
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @private @param {Player} player @param {string|null} [fallbackChannelId=null] @returns {string} Cleaned channel ID. */
|
|
||||||
function getPlayerChannelId(player, fallbackChannelId = null) {
|
|
||||||
return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
// Module-level join/permission helpers from the original PlayerManager.mjs
|
||||||
|
// (only initPlayer below uses them, so they stay private to this module).
|
||||||
/** @private Check whether the bot has required voice permissions in a channel. @param {object} client @param {string} channelId @returns {boolean} True if the bot can connect, speak, and use VAD. */
|
/** @private Check whether the bot has required voice permissions in a channel. @param {object} client @param {string} channelId @returns {boolean} True if the bot can connect, speak, and use VAD. */
|
||||||
function botHasVoicePermissions(client, channelId) {
|
function botHasVoicePermissions(client, channelId) {
|
||||||
try {
|
try {
|
||||||
@@ -70,287 +66,12 @@ function sanitizeJoinError(err, client = null, channelId = null) {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @class PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */
|
/**
|
||||||
export class PlayerManager {
|
* @type {object}
|
||||||
/** @type {RemoteSettingsManager} */
|
* @description Player lifecycle mixin — applied to PlayerManager.
|
||||||
settings;
|
|
||||||
|
|
||||||
/** @type {CommandHandler} */
|
|
||||||
commands;
|
|
||||||
|
|
||||||
/** @type {Map<string, Player>} Player instances keyed by channel ID. */
|
|
||||||
playerMap = new Map();
|
|
||||||
|
|
||||||
/** @private @type {Map<string, Set<string>>} Guild ID → Set of channel IDs (for fast guild-player lookup). */
|
|
||||||
_guildPlayerIndex = new Map();
|
|
||||||
|
|
||||||
/** @private @type {Set<string>} Channel IDs currently being joined. */
|
|
||||||
_pendingJoins = new Set();
|
|
||||||
|
|
||||||
/** @private @type {Map<string, {timer: setTimeout, songUrl: string, startedAtMs: number}>} */
|
|
||||||
_pendingScrobbleTimers = new Map();
|
|
||||||
|
|
||||||
/** @type {object} Full bot config. */
|
|
||||||
config;
|
|
||||||
|
|
||||||
/** @type {object} Player-specific config (lavalink reference). */
|
|
||||||
playerConfig;
|
|
||||||
|
|
||||||
/** @type {Locale|null} */
|
|
||||||
locale = null;
|
|
||||||
|
|
||||||
/** @type {Dashboard|null} */
|
|
||||||
dashboard = null;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create a new PlayerManager.
|
|
||||||
* @param {RemoteSettingsManager} settings - The settings manager.
|
|
||||||
* @param {CommandHandler} commands - The command handler.
|
|
||||||
* @param {object} config - Configuration object.
|
|
||||||
* @param {object} config.config - Full bot config.
|
|
||||||
* @param {object} config.player - Player-specific config (lavalink, etc.).
|
|
||||||
* @param {Dashboard} [config.dashboard] - Dashboard instance.
|
|
||||||
* @param {Locale} [config.locale] - Locale manager.
|
|
||||||
* @param {object} [config.timers] - Timer configuration.
|
|
||||||
* @param {TrackOptionsManager} [config.trackOptions] - Track options manager.
|
|
||||||
*/
|
*/
|
||||||
constructor(settings, commands, config) {
|
const PlayerLifecycleMixin = {
|
||||||
this.commands = commands;
|
/** Detect which voice channel the message author is in. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {object} settings @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} */
|
||||||
this.settings = settings;
|
|
||||||
this.config = config.config;
|
|
||||||
this.playerConfig = config.player;
|
|
||||||
this.dashboard = config.dashboard ?? null;
|
|
||||||
this.locale = config.locale ?? null;
|
|
||||||
this.timers = config.timers ?? {};
|
|
||||||
this._lastfm = null;
|
|
||||||
this.trackOptions = config.trackOptions ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @private Index a player by guild and channel ID for fast lookups. @param {string} guildId @param {string} channelId */
|
|
||||||
_indexPlayer(guildId, channelId) {
|
|
||||||
const gId = cleanId(guildId);
|
|
||||||
const cId = cleanId(channelId);
|
|
||||||
if (!gId || !cId) return;
|
|
||||||
let set = this._guildPlayerIndex.get(gId);
|
|
||||||
if (!set) { set = new Set(); this._guildPlayerIndex.set(gId, set); }
|
|
||||||
set.add(cId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @private Remove a player from the guild-player index. @param {string} guildId @param {string} channelId */
|
|
||||||
_unindexPlayer(guildId, channelId) {
|
|
||||||
const gId = cleanId(guildId);
|
|
||||||
const cId = cleanId(channelId);
|
|
||||||
if (!gId) return;
|
|
||||||
const set = this._guildPlayerIndex.get(gId);
|
|
||||||
if (set) {
|
|
||||||
set.delete(cId);
|
|
||||||
if (set.size === 0) this._guildPlayerIndex.delete(gId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Get all active (non-destroyed) players for a guild. @param {string} guildId @returns {Array<[string, Player]>} Array of [channelId, Player] pairs. */
|
|
||||||
getGuildPlayers(guildId) {
|
|
||||||
const gId = cleanId(guildId);
|
|
||||||
const set = this._guildPlayerIndex.get(gId);
|
|
||||||
if (!set) return [];
|
|
||||||
const result = [];
|
|
||||||
for (const channelId of set) {
|
|
||||||
const player = this.playerMap.get(channelId);
|
|
||||||
if (!player || player._destroyed) {
|
|
||||||
set.delete(channelId);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
result.push([channelId, player]);
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */
|
|
||||||
getPlayerByGuildAndChannel(guildId, channelId) {
|
|
||||||
const cId = cleanId(channelId);
|
|
||||||
const players = this.getGuildPlayers(guildId);
|
|
||||||
for (const [mapChannelId, player] of players) {
|
|
||||||
if (getPlayerChannelId(player, mapChannelId) === cId) return player;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Find a player by its channel ID across all guilds. @param {string} channelId @returns {Player|null} */
|
|
||||||
getPlayerByChannelId(channelId) {
|
|
||||||
const cId = cleanId(channelId);
|
|
||||||
for (const [, channelSet] of this._guildPlayerIndex) {
|
|
||||||
for (const mapChannelId of channelSet) {
|
|
||||||
const player = this.playerMap.get(mapChannelId);
|
|
||||||
if (player && getPlayerChannelId(player, mapChannelId) === cId) return player;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Bind dashboard update and message-sending events on a player. @param {Player} player @param {object} [context={}] @returns {Player} The same player, with events bound. */
|
|
||||||
setupEvents(player, context = {}) {
|
|
||||||
if (!player || player._dashboardEventsBound) return player;
|
|
||||||
|
|
||||||
Object.defineProperty(player, "_dashboardEventsBound", {
|
|
||||||
value: true,
|
|
||||||
configurable: true,
|
|
||||||
enumerable: false,
|
|
||||||
writable: true,
|
|
||||||
});
|
|
||||||
|
|
||||||
const emit = (type, data) => {
|
|
||||||
if (!this.dashboard?.enabled) return;
|
|
||||||
this.dashboard.updatePlayer({ type, data }, player);
|
|
||||||
};
|
|
||||||
|
|
||||||
const emitGlobal = (type) => {
|
|
||||||
if (!this.dashboard?.enabled) return;
|
|
||||||
this.dashboard.playerUpdate({ type }, player);
|
|
||||||
};
|
|
||||||
|
|
||||||
const sendUserUpdates = (eventType) => {
|
|
||||||
if (!this.dashboard?.enabled) return;
|
|
||||||
const channelId = getPlayerChannelId(player, context.channelId);
|
|
||||||
const channel = player.client?.channels?.get(channelId);
|
|
||||||
const guild = player.client?.guilds?.get(cleanId(player._guildId ?? context.guildId));
|
|
||||||
if (!guild) return;
|
|
||||||
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
|
||||||
if (!voiceStates) return;
|
|
||||||
const entries = Array.isArray(voiceStates)
|
|
||||||
? voiceStates
|
|
||||||
: typeof voiceStates.values === "function"
|
|
||||||
? [...voiceStates.values()]
|
|
||||||
: Object.values(voiceStates);
|
|
||||||
for (const state of entries) {
|
|
||||||
if (!state?.channelId && !state?.channel_id) continue;
|
|
||||||
const stateChannelId = cleanId(state.channelId ?? state.channel_id);
|
|
||||||
if (stateChannelId !== channelId) continue;
|
|
||||||
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
|
||||||
if (!member?.user || member.user?.bot) continue;
|
|
||||||
emit(eventType, member.user.id);
|
|
||||||
this.dashboard.userUpdate({
|
|
||||||
type: eventType,
|
|
||||||
guildId: cleanId(player._guildId ?? context.guildId),
|
|
||||||
channelId,
|
|
||||||
}, member.user);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
player.on("roomfetched", () => {
|
|
||||||
emitGlobal("init");
|
|
||||||
sendUserUpdates("join");
|
|
||||||
});
|
|
||||||
|
|
||||||
player.on("startplay", (song) => {
|
|
||||||
emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current));
|
|
||||||
emit("streamStartPlay", Date.now());
|
|
||||||
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
|
||||||
|
|
||||||
if (this._lastfm?.enabled && song) {
|
|
||||||
this._handleLastFmStartPlay(player, song);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
player.on("stopplay", () => {
|
|
||||||
emit("stopplay", null);
|
|
||||||
this.dashboard.playerUpdate({ type: "stopplay" }, player);
|
|
||||||
});
|
|
||||||
|
|
||||||
player.on("playback", (playing) => {
|
|
||||||
const elapsedMs = player._pausedAt
|
|
||||||
? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) -
|
|
||||||
(player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0))
|
|
||||||
: Date.now() - (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0));
|
|
||||||
const type = playing ? "resume" : "pause";
|
|
||||||
emit(type, { elapsedTime: Math.max(0, elapsedMs) });
|
|
||||||
this.dashboard.playerUpdate({ type }, player);
|
|
||||||
});
|
|
||||||
|
|
||||||
player.on("volume", (volume) => {
|
|
||||||
emit("volume", volume);
|
|
||||||
this.dashboard.playerUpdate({ type: "volume" }, player);
|
|
||||||
});
|
|
||||||
|
|
||||||
player.on("filter", (filter) => {
|
|
||||||
emit("filter", filter);
|
|
||||||
});
|
|
||||||
|
|
||||||
player.on("update", (scope) => {
|
|
||||||
this.dashboard.playerUpdate({ type: "update" }, player);
|
|
||||||
});
|
|
||||||
|
|
||||||
player.on("autoleave", () => {
|
|
||||||
sendUserUpdates("leave");
|
|
||||||
emitGlobal("close");
|
|
||||||
emit("stopplay", null);
|
|
||||||
});
|
|
||||||
|
|
||||||
player.on("leave", () => {
|
|
||||||
sendUserUpdates("leave");
|
|
||||||
emitGlobal("close");
|
|
||||||
emit("stopplay", null);
|
|
||||||
});
|
|
||||||
|
|
||||||
player.queue?.on("queue", (queueEvent) => {
|
|
||||||
const serialised = { type: queueEvent.type };
|
|
||||||
switch (queueEvent.type) {
|
|
||||||
case "add":
|
|
||||||
serialised.data = {
|
|
||||||
append: queueEvent.data?.append,
|
|
||||||
data: Dashboard.convertVideo(queueEvent.data?.data),
|
|
||||||
};
|
|
||||||
break;
|
|
||||||
case "addMany":
|
|
||||||
serialised.data = {
|
|
||||||
append: queueEvent.data?.append,
|
|
||||||
tracks: (queueEvent.data?.tracks ?? []).map(v => Dashboard.convertVideo(v)),
|
|
||||||
};
|
|
||||||
break;
|
|
||||||
case "remove":
|
|
||||||
serialised.data = {
|
|
||||||
index: queueEvent.data?.index,
|
|
||||||
removed: Dashboard.convertVideo(queueEvent.data?.removed),
|
|
||||||
old: (queueEvent.data?.old ?? []).map(v => Dashboard.convertVideo(v)),
|
|
||||||
new: (queueEvent.data?.new ?? []).map(v => Dashboard.convertVideo(v)),
|
|
||||||
};
|
|
||||||
break;
|
|
||||||
case "move":
|
|
||||||
serialised.data = {
|
|
||||||
from: queueEvent.data?.from,
|
|
||||||
to: queueEvent.data?.to,
|
|
||||||
track: Dashboard.convertVideo(queueEvent.data?.track),
|
|
||||||
};
|
|
||||||
break;
|
|
||||||
case "shuffle":
|
|
||||||
serialised.data = (queueEvent.data ?? []).map(v => Dashboard.convertVideo(v));
|
|
||||||
break;
|
|
||||||
case "update":
|
|
||||||
serialised.data = {
|
|
||||||
current: Dashboard.convertVideo(queueEvent.data?.current),
|
|
||||||
old: Dashboard.convertVideo(queueEvent.data?.old),
|
|
||||||
loop: queueEvent.data?.loop,
|
|
||||||
};
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
serialised.data = queueEvent.data;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
emit("queue", serialised);
|
|
||||||
this.dashboard.playerUpdate({ type: "queue" }, player);
|
|
||||||
});
|
|
||||||
|
|
||||||
return player;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @private Translate a locale key for a message context. @param {object} message @param {string} key @param {object} [replacements={}] @returns {string} */
|
|
||||||
_t(message, key, replacements = {}) {
|
|
||||||
if (!this.locale) return key;
|
|
||||||
const guildId = getMessageGuildId(message);
|
|
||||||
return this.locale.translate(guildId, key, replacements);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Detect which voice channel the message author is in. @async @param {object} message @param {object} settings @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} */
|
|
||||||
async checkVoiceChannels(message, settings) {
|
async checkVoiceChannels(message, settings) {
|
||||||
const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message);
|
const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message);
|
||||||
const userId = message?.author?.id ?? message?.member?.user?.id;
|
const userId = message?.author?.id ?? message?.member?.user?.id;
|
||||||
@@ -415,94 +136,9 @@ export class PlayerManager {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return { channelId, alreadyInVoice, hasHumans: hasHumansResult };
|
return { channelId, alreadyInVoice, hasHumans: hasHumansResult };
|
||||||
}
|
},
|
||||||
|
|
||||||
/** Get or spawn a player for the message's voice channel. @async @param {object} message @param {boolean} [promptJoin=true] @param {boolean} [verifyUser=true] @param {boolean} [shouldJoin=false] @returns {Promise<Player|null>} */
|
/** Prompt the user to select a voice channel via reactions or text input. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} msg @returns {Promise<Player|false>} */
|
||||||
async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) {
|
|
||||||
const guildId = getMessageGuildId(message);
|
|
||||||
const cleanGuildId = cleanId(guildId);
|
|
||||||
|
|
||||||
const { channelId: userChannelId } = await this.checkVoiceChannels(message);
|
|
||||||
const cleanUserChannelId = cleanId(userChannelId);
|
|
||||||
|
|
||||||
if (cleanUserChannelId) {
|
|
||||||
const player = this.playerMap.get(cleanUserChannelId)
|
|
||||||
?? this.getPlayerByGuildAndChannel(cleanGuildId, cleanUserChannelId);
|
|
||||||
if (player) {
|
|
||||||
player.textChannel = message.channel?.channel ?? message.channel;
|
|
||||||
try {
|
|
||||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
|
||||||
if (guildId && textChannelId) {
|
|
||||||
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
|
|
||||||
}
|
|
||||||
} catch(e) {
|
|
||||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
|
||||||
}
|
|
||||||
return player;
|
|
||||||
}
|
|
||||||
if (this._pendingJoins.has(cleanUserChannelId)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const serverPlayers = cleanGuildId
|
|
||||||
? this.getGuildPlayers(cleanGuildId)
|
|
||||||
: [];
|
|
||||||
|
|
||||||
if (serverPlayers.length > 0) {
|
|
||||||
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
|
|
||||||
|
|
||||||
if (!userChannelId) {
|
|
||||||
if (!verifyUser) {
|
|
||||||
const first = serverPlayers[0];
|
|
||||||
first[1].textChannel = message.channel?.channel ?? message.channel;
|
|
||||||
return first[1];
|
|
||||||
}
|
|
||||||
message.reply(this._t(message, "responses._common.noVoiceStrict"));
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const match = serverPlayers.find(([, player]) =>
|
|
||||||
getPlayerChannelId(player) === cleanUserChannelId
|
|
||||||
);
|
|
||||||
if (match) {
|
|
||||||
match[1].textChannel = message.channel?.channel ?? message.channel;
|
|
||||||
try {
|
|
||||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
|
||||||
if (cleanGuildId && textChannelId) {
|
|
||||||
this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId);
|
|
||||||
}
|
|
||||||
} catch(e) {
|
|
||||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
|
||||||
}
|
|
||||||
return match[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shouldJoin) {
|
|
||||||
return this.initPlayer(message, userChannelId);
|
|
||||||
}
|
|
||||||
|
|
||||||
const prefix = this.commands.getPrefix(guildId);
|
|
||||||
message.reply(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix }));
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!userChannelId) {
|
|
||||||
if (shouldJoin) {
|
|
||||||
return this.promptVC(message);
|
|
||||||
}
|
|
||||||
message.reply(this._t(message, "responses._common.noVoiceChannel"));
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shouldJoin) {
|
|
||||||
return this.initPlayer(message, userChannelId);
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Prompt the user to select a voice channel via reactions or text input. @async @param {object} msg @returns {Promise<Player|false>} */
|
|
||||||
async promptVC(msg) {
|
async promptVC(msg) {
|
||||||
const { channelId: autoDetected } = await this.checkVoiceChannels(msg);
|
const { channelId: autoDetected } = await this.checkVoiceChannels(msg);
|
||||||
if (autoDetected) {
|
if (autoDetected) {
|
||||||
@@ -585,9 +221,9 @@ export class PlayerManager {
|
|||||||
this.initPlayer(m, channel).then(p => resolve(p));
|
this.initPlayer(m, channel).then(p => resolve(p));
|
||||||
}, promptUser);
|
}, promptUser);
|
||||||
});
|
});
|
||||||
}
|
},
|
||||||
|
|
||||||
/** Leave a voice channel, destroy the player, and send a confirmation. @async @param {object} msg @param {string} [cid] @returns {Promise<void>} */
|
/** Leave a voice channel, destroy the player, and send a confirmation. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} msg @param {string} [cid] @returns {Promise<void>} */
|
||||||
async leave(msg, cid) {
|
async leave(msg, cid) {
|
||||||
if (!cid) {
|
if (!cid) {
|
||||||
const guildId = getMessageGuildId(msg);
|
const guildId = getMessageGuildId(msg);
|
||||||
@@ -620,18 +256,18 @@ export class PlayerManager {
|
|||||||
}
|
}
|
||||||
player.destroy();
|
player.destroy();
|
||||||
await msg.reply(this._t(msg, "responses._common.successfullyLeft"));
|
await msg.reply(this._t(msg, "responses._common.successfullyLeft"));
|
||||||
}
|
},
|
||||||
|
|
||||||
/** @private Restore saved volume for a player from guild settings. @param {Player} player @param {string} guildId */
|
/** @private Restore saved volume for a player from guild settings. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {string} guildId */
|
||||||
_restorePlayerVolume(player, guildId) {
|
_restorePlayerVolume(player, guildId) {
|
||||||
const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume");
|
const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume");
|
||||||
if (savedVol !== undefined && savedVol !== null) {
|
if (savedVol !== undefined && savedVol !== null) {
|
||||||
const vol = Number(savedVol);
|
const vol = Number(savedVol);
|
||||||
if (!isNaN(vol)) player.setVolume(vol / 100);
|
if (!isNaN(vol)) player.setVolume(vol / 100);
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
|
||||||
/** Create a new Player, join the voice channel, and set up events. @async @param {object} message @param {string} cid @returns {Promise<Player|null>} The spawned player, or null on failure. */
|
/** Create a new Player, join the voice channel, and set up events. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {string} cid @returns {Promise<Player|null>} The spawned player, or null on failure. */
|
||||||
async initPlayer(message, cid) {
|
async initPlayer(message, cid) {
|
||||||
const channel = this.commands.client?.channels?.get(cid);
|
const channel = this.commands.client?.channels?.get(cid);
|
||||||
|
|
||||||
@@ -917,96 +553,8 @@ export class PlayerManager {
|
|||||||
player.destroy();
|
player.destroy();
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
};
|
||||||
|
|
||||||
/** @private Handle Last.fm now-playing update and schedule scrobble timer. @param {Player} player @param {object} song */
|
export default PlayerLifecycleMixin;
|
||||||
_handleLastFmStartPlay(player, song) {
|
export { PlayerLifecycleMixin };
|
||||||
const lastfm = this._lastfm;
|
|
||||||
if (!lastfm?.enabled) return;
|
|
||||||
|
|
||||||
const guildId = cleanId(player._guildId);
|
|
||||||
if (!guildId) return;
|
|
||||||
|
|
||||||
const channelId = getPlayerChannelId(player);
|
|
||||||
const humanUserIds = [];
|
|
||||||
|
|
||||||
if (this.voiceCache) {
|
|
||||||
const users = this.voiceCache.getHumansInChannel(guildId, channelId);
|
|
||||||
humanUserIds.push(...users);
|
|
||||||
} else if (this.observedVoiceUsers) {
|
|
||||||
for (const [uid, info] of this.observedVoiceUsers) {
|
|
||||||
if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) {
|
|
||||||
humanUserIds.push(uid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const guild = player.client?.guilds?.get(guildId);
|
|
||||||
if (guild) {
|
|
||||||
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
|
||||||
if (voiceStates) {
|
|
||||||
const entries = Array.isArray(voiceStates)
|
|
||||||
? voiceStates
|
|
||||||
: typeof voiceStates.values === "function"
|
|
||||||
? [...voiceStates.values()]
|
|
||||||
: Object.values(voiceStates ?? {});
|
|
||||||
for (const state of entries) {
|
|
||||||
const uid = state?.userId ?? state?.user_id;
|
|
||||||
const chId = cleanId(state?.channelId ?? state?.channel_id);
|
|
||||||
if (uid && chId === channelId) {
|
|
||||||
const member = guild.members?.get?.(uid);
|
|
||||||
if (member?.user?.bot) continue;
|
|
||||||
if (!humanUserIds.includes(uid)) humanUserIds.push(uid);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const startedAtMs = player.startedPlaying;
|
|
||||||
|
|
||||||
const pendingKey = channelId;
|
|
||||||
const existing = this._pendingScrobbleTimers.get(pendingKey);
|
|
||||||
if (existing) {
|
|
||||||
clearTimeout(existing.timer);
|
|
||||||
this._pendingScrobbleTimers.delete(pendingKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const userId of humanUserIds) {
|
|
||||||
lastfm.updateNowPlaying(userId, song).catch(() => {});
|
|
||||||
}
|
|
||||||
|
|
||||||
const durationMs = (() => {
|
|
||||||
const d = song.duration;
|
|
||||||
if (!d) return null;
|
|
||||||
if (typeof d === "object" && d.seconds) return d.seconds * 1000;
|
|
||||||
if (typeof d === "number") return d;
|
|
||||||
return null;
|
|
||||||
})();
|
|
||||||
|
|
||||||
if (durationMs && durationMs >= 30_000) {
|
|
||||||
const thresholdMs = Math.min(
|
|
||||||
durationMs * lastfm.scrobbleThreshold,
|
|
||||||
lastfm.scrobbleMinMs
|
|
||||||
);
|
|
||||||
if (thresholdMs <= 600_000) {
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
this._pendingScrobbleTimers.delete(pendingKey);
|
|
||||||
const current = player.queue?.getCurrent();
|
|
||||||
if (!current || player._destroyed || player.leaving) return;
|
|
||||||
if (current.title !== song.title || current.url !== song.url) return;
|
|
||||||
if (player._paused) return;
|
|
||||||
|
|
||||||
const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now());
|
|
||||||
if (lastfm.shouldScrobble(song, playedMs)) {
|
|
||||||
for (const userId of humanUserIds) {
|
|
||||||
lastfm.scrobble(userId, song, startedAtMs).catch(() => {});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, thresholdMs);
|
|
||||||
|
|
||||||
this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
/**
|
||||||
|
* @module src/music/PlayerManager
|
||||||
|
* @description Manages all Player instances. Handles player lifecycle (spawn,
|
||||||
|
* join, leave, destroy), voice channel resolution, dashboard events, and
|
||||||
|
* autoleave suppression for 24/7 channels.
|
||||||
|
*
|
||||||
|
* Base class: class fields, constructor, the guild/channel player index,
|
||||||
|
* lookups and getPlayer. Dashboard event wiring and Last.fm scrobble
|
||||||
|
* scheduling live in PlayerEventsMixin.mjs; voice-channel detection, channel
|
||||||
|
* prompt, leave and player spawn/join live in PlayerLifecycleMixin.mjs.
|
||||||
|
* Both mixins are applied to the class at the bottom of this file.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import Player from "./player/index.mjs";
|
||||||
|
import { Utils, cleanId } from "../utils/Utils.mjs";
|
||||||
|
import { logger } from "../core/Logger.mjs";
|
||||||
|
import { getMessageGuildId } from "../ui/index.mjs";
|
||||||
|
import { applyMixins } from "../utils/mixins.mjs";
|
||||||
|
import PlayerEventsMixin, { getPlayerChannelId } from "./PlayerEventsMixin.mjs";
|
||||||
|
import PlayerLifecycleMixin from "./PlayerLifecycleMixin.mjs";
|
||||||
|
|
||||||
|
|
||||||
|
/** @class PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */
|
||||||
|
export class PlayerManager {
|
||||||
|
/** @type {RemoteSettingsManager} */
|
||||||
|
settings;
|
||||||
|
|
||||||
|
/** @type {CommandHandler} */
|
||||||
|
commands;
|
||||||
|
|
||||||
|
/** @type {Map<string, Player>} Player instances keyed by channel ID. */
|
||||||
|
playerMap = new Map();
|
||||||
|
|
||||||
|
/** @private @type {Map<string, Set<string>>} Guild ID → Set of channel IDs (for fast guild-player lookup). */
|
||||||
|
_guildPlayerIndex = new Map();
|
||||||
|
|
||||||
|
/** @private @type {Set<string>} Channel IDs currently being joined. */
|
||||||
|
_pendingJoins = new Set();
|
||||||
|
|
||||||
|
/** @private @type {Map<string, {timer: setTimeout, songUrl: string, startedAtMs: number}>} */
|
||||||
|
_pendingScrobbleTimers = new Map();
|
||||||
|
|
||||||
|
/** @type {object} Full bot config. */
|
||||||
|
config;
|
||||||
|
|
||||||
|
/** @type {object} Player-specific config (lavalink reference). */
|
||||||
|
playerConfig;
|
||||||
|
|
||||||
|
/** @type {Locale|null} */
|
||||||
|
locale = null;
|
||||||
|
|
||||||
|
/** @type {Dashboard|null} */
|
||||||
|
dashboard = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new PlayerManager.
|
||||||
|
* @param {RemoteSettingsManager} settings - The settings manager.
|
||||||
|
* @param {CommandHandler} commands - The command handler.
|
||||||
|
* @param {object} config - Configuration object.
|
||||||
|
* @param {object} config.config - Full bot config.
|
||||||
|
* @param {object} config.player - Player-specific config (lavalink, etc.).
|
||||||
|
* @param {Dashboard} [config.dashboard] - Dashboard instance.
|
||||||
|
* @param {Locale} [config.locale] - Locale manager.
|
||||||
|
* @param {object} [config.timers] - Timer configuration.
|
||||||
|
* @param {TrackOptionsManager} [config.trackOptions] - Track options manager.
|
||||||
|
*/
|
||||||
|
constructor(settings, commands, config) {
|
||||||
|
this.commands = commands;
|
||||||
|
this.settings = settings;
|
||||||
|
this.config = config.config;
|
||||||
|
this.playerConfig = config.player;
|
||||||
|
this.dashboard = config.dashboard ?? null;
|
||||||
|
this.locale = config.locale ?? null;
|
||||||
|
this.timers = config.timers ?? {};
|
||||||
|
this._lastfm = null;
|
||||||
|
this.trackOptions = config.trackOptions ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @private Index a player by guild and channel ID for fast lookups. @param {string} guildId @param {string} channelId */
|
||||||
|
_indexPlayer(guildId, channelId) {
|
||||||
|
const gId = cleanId(guildId);
|
||||||
|
const cId = cleanId(channelId);
|
||||||
|
if (!gId || !cId) return;
|
||||||
|
let set = this._guildPlayerIndex.get(gId);
|
||||||
|
if (!set) { set = new Set(); this._guildPlayerIndex.set(gId, set); }
|
||||||
|
set.add(cId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @private Remove a player from the guild-player index. @param {string} guildId @param {string} channelId */
|
||||||
|
_unindexPlayer(guildId, channelId) {
|
||||||
|
const gId = cleanId(guildId);
|
||||||
|
const cId = cleanId(channelId);
|
||||||
|
if (!gId) return;
|
||||||
|
const set = this._guildPlayerIndex.get(gId);
|
||||||
|
if (set) {
|
||||||
|
set.delete(cId);
|
||||||
|
if (set.size === 0) this._guildPlayerIndex.delete(gId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get all active (non-destroyed) players for a guild. @param {string} guildId @returns {Array<[string, Player]>} Array of [channelId, Player] pairs. */
|
||||||
|
getGuildPlayers(guildId) {
|
||||||
|
const gId = cleanId(guildId);
|
||||||
|
const set = this._guildPlayerIndex.get(gId);
|
||||||
|
if (!set) return [];
|
||||||
|
const result = [];
|
||||||
|
for (const channelId of set) {
|
||||||
|
const player = this.playerMap.get(channelId);
|
||||||
|
if (!player || player._destroyed) {
|
||||||
|
set.delete(channelId);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
result.push([channelId, player]);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */
|
||||||
|
getPlayerByGuildAndChannel(guildId, channelId) {
|
||||||
|
const cId = cleanId(channelId);
|
||||||
|
const players = this.getGuildPlayers(guildId);
|
||||||
|
for (const [mapChannelId, player] of players) {
|
||||||
|
if (getPlayerChannelId(player, mapChannelId) === cId) return player;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Find a player by its channel ID across all guilds. @param {string} channelId @returns {Player|null} */
|
||||||
|
getPlayerByChannelId(channelId) {
|
||||||
|
const cId = cleanId(channelId);
|
||||||
|
for (const [, channelSet] of this._guildPlayerIndex) {
|
||||||
|
for (const mapChannelId of channelSet) {
|
||||||
|
const player = this.playerMap.get(mapChannelId);
|
||||||
|
if (player && getPlayerChannelId(player, mapChannelId) === cId) return player;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get or spawn a player for the message's voice channel. @async @param {object} message @param {boolean} [promptJoin=true] @param {boolean} [verifyUser=true] @param {boolean} [shouldJoin=false] @returns {Promise<Player|null>} */
|
||||||
|
async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) {
|
||||||
|
const guildId = getMessageGuildId(message);
|
||||||
|
const cleanGuildId = cleanId(guildId);
|
||||||
|
|
||||||
|
const { channelId: userChannelId } = await this.checkVoiceChannels(message);
|
||||||
|
const cleanUserChannelId = cleanId(userChannelId);
|
||||||
|
|
||||||
|
if (cleanUserChannelId) {
|
||||||
|
const player = this.playerMap.get(cleanUserChannelId)
|
||||||
|
?? this.getPlayerByGuildAndChannel(cleanGuildId, cleanUserChannelId);
|
||||||
|
if (player) {
|
||||||
|
player.textChannel = message.channel?.channel ?? message.channel;
|
||||||
|
try {
|
||||||
|
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||||
|
if (guildId && textChannelId) {
|
||||||
|
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||||
|
}
|
||||||
|
return player;
|
||||||
|
}
|
||||||
|
if (this._pendingJoins.has(cleanUserChannelId)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const serverPlayers = cleanGuildId
|
||||||
|
? this.getGuildPlayers(cleanGuildId)
|
||||||
|
: [];
|
||||||
|
|
||||||
|
if (serverPlayers.length > 0) {
|
||||||
|
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
|
||||||
|
|
||||||
|
if (!userChannelId) {
|
||||||
|
if (!verifyUser) {
|
||||||
|
const first = serverPlayers[0];
|
||||||
|
first[1].textChannel = message.channel?.channel ?? message.channel;
|
||||||
|
return first[1];
|
||||||
|
}
|
||||||
|
message.reply(this._t(message, "responses._common.noVoiceStrict"));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const match = serverPlayers.find(([, player]) =>
|
||||||
|
getPlayerChannelId(player) === cleanUserChannelId
|
||||||
|
);
|
||||||
|
if (match) {
|
||||||
|
match[1].textChannel = message.channel?.channel ?? message.channel;
|
||||||
|
try {
|
||||||
|
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||||
|
if (cleanGuildId && textChannelId) {
|
||||||
|
this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId);
|
||||||
|
}
|
||||||
|
} catch(e) {
|
||||||
|
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||||
|
}
|
||||||
|
return match[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldJoin) {
|
||||||
|
return this.initPlayer(message, userChannelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const prefix = this.commands.getPrefix(guildId);
|
||||||
|
message.reply(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix }));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!userChannelId) {
|
||||||
|
if (shouldJoin) {
|
||||||
|
return this.promptVC(message);
|
||||||
|
}
|
||||||
|
message.reply(this._t(message, "responses._common.noVoiceChannel"));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldJoin) {
|
||||||
|
return this.initPlayer(message, userChannelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attach the split-out concerns: dashboard event wiring (PlayerEventsMixin)
|
||||||
|
// and voice-channel detection / player lifecycle (PlayerLifecycleMixin).
|
||||||
|
applyMixins(PlayerManager, PlayerEventsMixin, PlayerLifecycleMixin);
|
||||||
@@ -0,0 +1,419 @@
|
|||||||
|
/** @module src/music/audio/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. Supports MP3/AAC/radio streams via Lavalink resolve-through. Base class: lifecycle (play/stop/destroy), state getters, volume and cleanup. Stream pipeline building and Lavalink REST HTTP helpers live in the StreamPipeline/HttpStreams mixin modules applied at the bottom of this file. */
|
||||||
|
|
||||||
|
import { logger } from "../../core/Logger.mjs";
|
||||||
|
import { EventEmitter } from "node:events";
|
||||||
|
import { Readable } from "node:stream";
|
||||||
|
import { applyMixins } from "../../utils/mixins.mjs";
|
||||||
|
import StreamPipeline from "./StreamPipeline.mjs";
|
||||||
|
import HttpStreams from "./HttpStreams.mjs";
|
||||||
|
|
||||||
|
/** @type {number} @description livekit TrackKind.KIND_AUDIO — publications with this kind are managed by the bridge. */
|
||||||
|
const TRACK_KIND_AUDIO = 1;
|
||||||
|
|
||||||
|
/** @extends {EventEmitter} */
|
||||||
|
export class FluxerAudioBridge extends EventEmitter {
|
||||||
|
_conn = null;
|
||||||
|
_stream = null;
|
||||||
|
_encoder = null;
|
||||||
|
_sourceStream = null;
|
||||||
|
_sourceReq = null;
|
||||||
|
_playing = false;
|
||||||
|
_stopped = false;
|
||||||
|
_startedAt = 0;
|
||||||
|
_currentUri = null;
|
||||||
|
_lavalink = null;
|
||||||
|
_playGeneration = 0;
|
||||||
|
_durationTimer = null;
|
||||||
|
_endResolve = null;
|
||||||
|
_endReject = null;
|
||||||
|
_usedTrackstream = false;
|
||||||
|
|
||||||
|
/** @type {boolean} @description Whether audio is currently playing. */
|
||||||
|
get playing() { return this._playing; }
|
||||||
|
/** @type {number} @description Timestamp (ms) when playback started. */
|
||||||
|
get startedAt() { return this._startedAt; }
|
||||||
|
/** @type {string|null} @description URI of the currently playing track. */
|
||||||
|
get currentUri() { return this._currentUri; }
|
||||||
|
|
||||||
|
/** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */
|
||||||
|
constructor(lavalinkManager = null) {
|
||||||
|
super();
|
||||||
|
this._lavalink = lavalinkManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Play a track through a Fluxer voice connection, entirely in-process.
|
||||||
|
* Routing order:
|
||||||
|
* 1. trackstream passthrough (seek=0, no filters) — NodeLink hands back a WebM/Opus
|
||||||
|
* direct URL which the voice connection plays natively (zero re-encode).
|
||||||
|
* 2. loadstream — NodeLink returns raw PCM (48k stereo s16le) with server-side
|
||||||
|
* seek/filters; PCM is Opus-encoded in-process and muxed to WebM.
|
||||||
|
* 3. direct URL fallback — magic-byte sniff: WebM passthrough or Ogg/Opus remux.
|
||||||
|
* @param {object} conn - Fluxer voice connection
|
||||||
|
* @param {object} trackInfo - Track metadata (encoded, title, url, guildId)
|
||||||
|
* @param {object} [options]
|
||||||
|
* @param {number} [options.seekSeconds=0]
|
||||||
|
* @param {number} [options.durationMs=0]
|
||||||
|
* @param {object} [options.filterPayload]
|
||||||
|
* @returns {Promise<"finished"|"stopped">}
|
||||||
|
*/
|
||||||
|
async play(conn, trackInfo, options = {}) {
|
||||||
|
this.stop();
|
||||||
|
if (!conn) throw new Error("[AudioBridge] No voice connection provided");
|
||||||
|
|
||||||
|
this._unpublishStaleAudioTracks(conn);
|
||||||
|
|
||||||
|
const generation = ++this._playGeneration;
|
||||||
|
this._conn = conn;
|
||||||
|
this._playing = true;
|
||||||
|
this._stopped = false;
|
||||||
|
this._startedAt = Date.now();
|
||||||
|
this._currentUri = trackInfo?.url ?? trackInfo?.title ?? "unknown";
|
||||||
|
this._usedTrackstream = false;
|
||||||
|
|
||||||
|
const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000);
|
||||||
|
let durationMs = options.durationMs || 0;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) {
|
||||||
|
try {
|
||||||
|
const direct = await this._getTrackstreamUrl(trackInfo);
|
||||||
|
if (direct?.url && /webm|opus/i.test(direct.format || "")) {
|
||||||
|
this._usedTrackstream = true;
|
||||||
|
logger.player("[AudioBridge] Passthrough webm/opus via trackstream (zero-copy): " + (trackInfo.title || "unknown"));
|
||||||
|
|
||||||
|
await conn.play(direct.url);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
if (durationMs > 0) await this._waitDuration(durationMs);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
if (this._playing && !this._stopped) {
|
||||||
|
this._playing = false;
|
||||||
|
logger.player("[AudioBridge] Track finished naturally (trackstream passthrough)");
|
||||||
|
return "finished";
|
||||||
|
}
|
||||||
|
return "stopped";
|
||||||
|
}
|
||||||
|
if (direct?.url && this._lavalink && trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||||
|
logger.player("[AudioBridge] trackstream format " + (direct.format || "?") + " — resolving original source URL via Lavalink for fresh encoded track...");
|
||||||
|
const freshEncoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
|
||||||
|
if (freshEncoded) {
|
||||||
|
trackInfo.encoded = freshEncoded;
|
||||||
|
logger.player("[AudioBridge] Fresh encoded track obtained — retrying trackstream for webm/opus...");
|
||||||
|
try {
|
||||||
|
const freshDirect = await this._getTrackstreamUrl(trackInfo);
|
||||||
|
if (freshDirect?.url && /webm|opus/i.test(freshDirect.format || "")) {
|
||||||
|
this._usedTrackstream = true;
|
||||||
|
logger.player("[AudioBridge] Fresh trackstream is webm/opus — zero-copy passthrough: " + (trackInfo.title || "unknown"));
|
||||||
|
await conn.play(freshDirect.url);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
if (durationMs > 0) await this._waitDuration(durationMs);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
if (this._playing && !this._stopped) {
|
||||||
|
this._playing = false;
|
||||||
|
logger.player("[AudioBridge] Track finished naturally (fresh trackstream passthrough)");
|
||||||
|
return "finished";
|
||||||
|
}
|
||||||
|
return "stopped";
|
||||||
|
}
|
||||||
|
logger.player("[AudioBridge] Fresh trackstream also " + (freshDirect?.format || "?") + ", falling through to loadstream");
|
||||||
|
} catch (e2) {
|
||||||
|
logger.player("[AudioBridge] Fresh trackstream failed, falling through to loadstream: " + e2.message);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.player("[AudioBridge] Could not resolve source URL via Lavalink, using original encoded track for loadstream");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), falling through to loadstream");
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message);
|
||||||
|
this._playing = true;
|
||||||
|
this._stopped = false;
|
||||||
|
this._startedAt = Date.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackInfo.encoded && this._lavalink) {
|
||||||
|
const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload);
|
||||||
|
if (generation !== this._playGeneration) {
|
||||||
|
loaded.stream.destroy();
|
||||||
|
return "stopped";
|
||||||
|
}
|
||||||
|
|
||||||
|
const routed = await this._routeByMagic(loaded.stream);
|
||||||
|
this._sourceStream = loaded.stream;
|
||||||
|
this._sourceReq = loaded.req || null;
|
||||||
|
|
||||||
|
if (routed.kind === "webm") {
|
||||||
|
logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") +
|
||||||
|
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : ""));
|
||||||
|
this._stream = routed.stream;
|
||||||
|
await conn.play(routed.stream);
|
||||||
|
} else if (routed.kind === "ogg") {
|
||||||
|
logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown"));
|
||||||
|
const oggResult = await this._remuxOggToWebM(routed.stream);
|
||||||
|
this._stream = oggResult;
|
||||||
|
if (durationMs <= 0) durationMs = oggResult.getDurationMs();
|
||||||
|
await conn.play(this._stream);
|
||||||
|
} else {
|
||||||
|
logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") +
|
||||||
|
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") +
|
||||||
|
(options.filterPayload ? " [filters]" : ""));
|
||||||
|
this._stream = this._buildPcmPipeline(routed.stream);
|
||||||
|
await conn.play(this._stream);
|
||||||
|
}
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
await this._awaitEnd(durationMs);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
if (this._playing && !this._stopped) {
|
||||||
|
this._playing = false;
|
||||||
|
logger.player("[AudioBridge] Track finished naturally (loadstream)");
|
||||||
|
return "finished";
|
||||||
|
}
|
||||||
|
return "stopped";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||||
|
logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "...");
|
||||||
|
const response = await fetch(trackInfo.url, {
|
||||||
|
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
|
||||||
|
redirect: "follow",
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error("HTTP " + response.status + " for " + trackInfo.url);
|
||||||
|
}
|
||||||
|
const stream = Readable.fromWeb(response.body);
|
||||||
|
this._sourceStream = stream;
|
||||||
|
|
||||||
|
const routed = await this._routeByMagic(stream);
|
||||||
|
if (routed.kind === "webm") {
|
||||||
|
logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown"));
|
||||||
|
this._stream = routed.stream;
|
||||||
|
await conn.play(routed.stream);
|
||||||
|
} else if (routed.kind === "ogg") {
|
||||||
|
logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown"));
|
||||||
|
const oggResult = await this._remuxOggToWebM(routed.stream);
|
||||||
|
this._stream = oggResult;
|
||||||
|
await conn.play(this._stream);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
await new Promise(r => {
|
||||||
|
if (this._stream.readableEnded) return r();
|
||||||
|
const done = () => { this._stream.off("end", done); this._stream.off("close", done); r(); };
|
||||||
|
this._stream.once("end", done);
|
||||||
|
this._stream.once("close", done);
|
||||||
|
});
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
const fullDurationMs = oggResult.getDurationMs();
|
||||||
|
const elapsedMs = Date.now() - this._startedAt;
|
||||||
|
const remainingMs = Math.max(0, fullDurationMs - elapsedMs);
|
||||||
|
logger.player("[AudioBridge] Route 3b: OGG " + fullDurationMs + "ms total, " + elapsedMs + "ms elapsed, waiting " + remainingMs + "ms more");
|
||||||
|
|
||||||
|
if (remainingMs > 0) await this._awaitEnd(remainingMs);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
if (this._playing && !this._stopped) {
|
||||||
|
this._playing = false;
|
||||||
|
logger.player("[AudioBridge] Track finished naturally (direct URL, OGG remux)");
|
||||||
|
return "finished";
|
||||||
|
}
|
||||||
|
return "stopped";
|
||||||
|
} else {
|
||||||
|
stream.destroy();
|
||||||
|
this._sourceStream = null;
|
||||||
|
logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink...");
|
||||||
|
|
||||||
|
if (this._lavalink) {
|
||||||
|
const encoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
|
||||||
|
if (encoded) {
|
||||||
|
trackInfo.encoded = encoded;
|
||||||
|
logger.player("[AudioBridge] Route 3c: Got encoded track from Lavalink, retrying via loadstream...");
|
||||||
|
const loaded = await this._streamFromLoadstream(trackInfo, 0, null);
|
||||||
|
if (generation !== this._playGeneration) {
|
||||||
|
loaded.stream.destroy();
|
||||||
|
return "stopped";
|
||||||
|
}
|
||||||
|
|
||||||
|
const routed2 = await this._routeByMagic(loaded.stream);
|
||||||
|
this._sourceStream = loaded.stream;
|
||||||
|
this._sourceReq = loaded.req || null;
|
||||||
|
|
||||||
|
if (routed2.kind === "webm") {
|
||||||
|
logger.player("[AudioBridge] Route 3c (Lavalink): webm/opus passthrough");
|
||||||
|
this._stream = routed2.stream;
|
||||||
|
await conn.play(routed2.stream);
|
||||||
|
} else if (routed2.kind === "ogg") {
|
||||||
|
logger.player("[AudioBridge] Route 3c (Lavalink): ogg/opus remux to webm");
|
||||||
|
const oggResult3c = await this._remuxOggToWebM(routed2.stream);
|
||||||
|
this._stream = oggResult3c;
|
||||||
|
if (durationMs <= 0) durationMs = oggResult3c.getDurationMs();
|
||||||
|
await conn.play(this._stream);
|
||||||
|
} else {
|
||||||
|
logger.player("[AudioBridge] Route 3c (Lavalink): PCM -> Opus -> WebM");
|
||||||
|
this._stream = this._buildPcmPipeline(routed2.stream);
|
||||||
|
await conn.play(this._stream);
|
||||||
|
}
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
await this._awaitEnd(durationMs);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
if (this._playing && !this._stopped) {
|
||||||
|
this._playing = false;
|
||||||
|
logger.player("[AudioBridge] Track finished naturally (Route 3c Lavalink resolve)");
|
||||||
|
return "finished";
|
||||||
|
}
|
||||||
|
return "stopped";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(
|
||||||
|
"[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " +
|
||||||
|
"Lavalink resolve also failed or is unavailable. " +
|
||||||
|
"Make sure your Lavalink/NodeLink node is running and can decode this stream format."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
await this._awaitEnd(durationMs);
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
|
||||||
|
if (this._playing && !this._stopped) {
|
||||||
|
this._playing = false;
|
||||||
|
logger.player("[AudioBridge] Track finished naturally (direct URL)");
|
||||||
|
return "finished";
|
||||||
|
}
|
||||||
|
return "stopped";
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error("Could not get audio stream for: " + (trackInfo.title || trackInfo.url || "unknown"));
|
||||||
|
|
||||||
|
} catch (e) {
|
||||||
|
if (generation !== this._playGeneration) return "stopped";
|
||||||
|
if (this._stopped || !this._playing) return "stopped";
|
||||||
|
this._playing = false;
|
||||||
|
logger.error("[AudioBridge] Playback error: " + e.message);
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
this._cleanup();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stop current playback and clean up resources. */
|
||||||
|
stop() {
|
||||||
|
const wasPlaying = this._playing;
|
||||||
|
this._stopped = true;
|
||||||
|
this._playing = false;
|
||||||
|
this._playGeneration++;
|
||||||
|
|
||||||
|
this._cleanup();
|
||||||
|
|
||||||
|
if (this._conn) {
|
||||||
|
try { this._conn.stop(); } catch (_) {}
|
||||||
|
this._unpublishStaleAudioTracks(this._conn);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasPlaying) {
|
||||||
|
this.emit("stopped");
|
||||||
|
logger.player("[AudioBridge] Playback stopped");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object} conn - Fluxer voice connection
|
||||||
|
* @param {string|null} [keepSid=null] - Track SID to keep (currently active publication)
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_unpublishStaleAudioTracks(conn, keepSid = null) {
|
||||||
|
try {
|
||||||
|
const room = conn?.room;
|
||||||
|
const participant = room?.localParticipant;
|
||||||
|
if (!room?.isConnected || typeof participant?.unpublishTrack !== "function") return;
|
||||||
|
|
||||||
|
const publications = participant.trackPublications;
|
||||||
|
if (!publications || typeof publications.entries !== "function") return;
|
||||||
|
|
||||||
|
for (const [sid, pub] of publications.entries()) {
|
||||||
|
if (keepSid && sid === keepSid) continue;
|
||||||
|
if (pub?.kind !== TRACK_KIND_AUDIO) continue;
|
||||||
|
try {
|
||||||
|
const p = participant.unpublishTrack(sid, true);
|
||||||
|
if (p?.catch) p.catch(() => {});
|
||||||
|
logger.player("[AudioBridge] Unpublished stale audio track: " + sid);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Set the playback volume on the voice connection.
|
||||||
|
* @param {number} percent - Volume 0–100.
|
||||||
|
*/
|
||||||
|
setVolume(percent) {
|
||||||
|
if (this._conn) {
|
||||||
|
try { this._conn.setVolume(percent); } catch (e) {
|
||||||
|
logger.warn("[AudioBridge] setVolume error: " + e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @returns {number} Current volume percentage (0–100). */
|
||||||
|
getVolume() {
|
||||||
|
if (this._conn) {
|
||||||
|
try { return this._conn.getVolume(); } catch (_) {}
|
||||||
|
}
|
||||||
|
return 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @returns {boolean} Whether the voice connection is currently active. */
|
||||||
|
isConnected() {
|
||||||
|
if (this._conn) {
|
||||||
|
try { return this._conn.isConnected(); } catch (_) {}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear timers, settle pending waits, and tear down the pipeline.
|
||||||
|
* @private
|
||||||
|
*/
|
||||||
|
_cleanup() {
|
||||||
|
if (this._durationTimer) { clearTimeout(this._durationTimer); this._durationTimer = null; }
|
||||||
|
if (this._endResolve) {
|
||||||
|
const resolve = this._endResolve;
|
||||||
|
this._endResolve = null;
|
||||||
|
this._endReject = null;
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
for (const s of [this._stream, this._encoder, this._sourceStream]) {
|
||||||
|
if (s) {
|
||||||
|
try { s.destroy(); } catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (this._sourceReq) {
|
||||||
|
try { this._sourceReq.destroy(); } catch (_) {}
|
||||||
|
}
|
||||||
|
this._stream = null;
|
||||||
|
this._encoder = null;
|
||||||
|
this._sourceStream = null;
|
||||||
|
this._sourceReq = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stop playback, release the voice connection, and remove all listeners. */
|
||||||
|
destroy() {
|
||||||
|
this.stop();
|
||||||
|
this._conn = null;
|
||||||
|
this._currentUri = null;
|
||||||
|
this.removeAllListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Attach the split-out concerns: stream pipeline building/routing
|
||||||
|
// (StreamPipeline) and Lavalink REST HTTP helpers (HttpStreams).
|
||||||
|
applyMixins(FluxerAudioBridge, StreamPipeline, HttpStreams);
|
||||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user