lavalink-client 2.5.8 → 2.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
- # Lavalink Client
2
- Easy, flexible and feature-rich lavalink@v4 Client. Both for Beginners and Proficients.
1
+ <div style="font-family: Arial, sans-serif; border: 1px solid #ddd; border-radius: 15px; padding: 25px; background-color: #f9f9f9;">
2
+
3
+ <h1 align="center" style="color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px;">Lavalink Client</h1>
4
+ <p align="center" style="font-size: 1.2em; color: #555;">An easy, flexible, and feature-rich Lavalink v4 Client for both beginners and experts.</p>
3
5
 
4
6
  <div align="center">
5
7
  <p>
@@ -8,123 +10,186 @@ Easy, flexible and feature-rich lavalink@v4 Client. Both for Beginners and Profi
8
10
  </p>
9
11
  <p>
10
12
  <a href="https://www.npmjs.com/package/lavalink-client">
11
- <img src="https://img.shields.io/npm/v/lavalink-client.svg?maxAge=3600&style=for-the-badge&logo=npm&logoColor=red" alt="NPM version" />
13
+ <img src="https://img.shields.io/npm/v/lavalink-client.svg?maxAge=3600&style=for-the-badge&logo=npm&logoColor=red" alt="NPM Version" />
12
14
  </a>
13
15
  <a href="https://www.npmjs.com/package/lavalink-client">
14
- <img src="https://img.shields.io/npm/dt/lavalink-client.svg?maxAge=3600&style=for-the-badge&logo=npm&logoColor=red" alt="NPM downloads" />
16
+ <img src="https://img.shields.io/npm/dt/lavalink-client.svg?maxAge=3600&style=for-the-badge&logo=npm&logoColor=red" alt="NPM Downloads" />
15
17
  </a>
16
18
  <a href="https://tomato6966.github.io/lavalink-client/">
17
- <img src="https://img.shields.io/badge/Documation-%230288D1.svg?style=for-the-badge&logo=gitbook&logoColor=white" alt="Get Started Now">
19
+ <img src="https://img.shields.io/badge/Documentation-%230288D1.svg?style=for-the-badge&logo=gitbook&logoColor=white" alt="Get Started Now">
18
20
  </a>
19
21
  </p>
20
22
  <p>
21
- <a href="https://www.npmjs.com/package/lavalink-client"><img src="https://nodei.co/npm/lavalink-client.png?downloads=true&stars=true" alt="npm install lavalink-client" /></a>
23
+ <a href="https://www.npmjs.com/package/lavalink-client"><img src="https://nodei.co/npm/lavalink-client.png?downloads=true&stars=true" alt="NPM Install: lavalink-client" /></a>
22
24
  </p>
23
25
  </div>
24
26
 
25
- # Install
27
+ ***
26
28
 
27
- Latest stable Version: **`v2.4.0`**
29
+ ## 🚀 Features
30
+ - 💯 **Lavalink v4 Native:** Full support for Lavalink v4, including its powerful plugin ecosystem.
31
+ - ✅ **Detailed Player-Destroy Reasons:** Understand precisely why a player was destroyed (e.g., channel deleted, bot disconnected).
32
+ - ✨ **Flexible Queue Stores:** Use the default in-memory store or bring your own (Redis, databases, etc.) to sync queues across multiple processes.
33
+ - 🎶 **Unresolved Tracks:** Supports unresolved track objects, fetching full data only when a track is about to play, saving API requests and resources.
34
+ - 🎚️ **Built-in Filters & EQ:** Easy-to-use management for audio filters and equalizers.
35
+ - ⚙️ **Advanced Player Options:** Fine-tune player behavior for disconnects, empty queues, volume handling, and more.
36
+ - 🛡️ **Lavalink-Side Validation:** Ensures you only use filters, plugins, and sources that your Lavalink node actually supports.
37
+ - 🔒 **Client-Side Validation:** Whitelist and blacklist URLs or domains to prevent unwanted requests and protect your bot.
38
+ - 🧑‍💻 **Developer-Friendly:** A memory-efficient design with a clean, intuitive API that mirrors Lavalink's own implementation.
39
+ - 🤖 **Automated Handling:** Automatically handles track skipping on errors, voice channel deletions, server-wide mutes, and much more.
28
40
 
29
- <details><summary>👉 via NPM</summary>
41
+ ***
30
42
 
31
- ```bash
32
- npm install --save lavalink-client
33
- ```
43
+ ## 📦 Installation
34
44
 
45
+ **Latest Stable Version: `v2.5.x`**
35
46
 
36
- Dev Version: (Current)
47
+ <details>
48
+ <summary><strong>👉 via NPM</strong></summary>
37
49
 
38
50
  ```bash
39
- npm install --save tomato6966/lavalink-client
51
+ # Stable (install release)
52
+ npm install --save lavalink-client
53
+
54
+ # Development (Install github dev-branch)
55
+ npm install --save tomato6966/lavalink-client
40
56
  ```
41
57
 
42
58
  </details>
43
59
 
44
- <details><summary>👉 via YARN</summary>
60
+ <details>
61
+ <summary><strong>👉 via YARN</strong></summary>
45
62
 
46
63
  ```bash
64
+ # Stable (install release)
47
65
  yarn add lavalink-client
66
+
67
+ # Development (Install github dev-branch)
68
+ yarn add tomato6966/lavalink-client
48
69
  ```
49
70
 
50
- Dev Version: (Current)
71
+ </details>
72
+
73
+ <details>
74
+ <summary><strong>👉 via BUN</strong></summary>
51
75
 
52
76
  ```bash
53
- yarn add tomato6966/lavalink-client
77
+ # Stable (install release)
78
+ bun add lavalink-client
79
+
80
+ # Development (Install github dev-branch)
81
+ bun add tomato6966/lavalink-client
54
82
  ```
55
83
 
56
84
  </details>
57
85
 
58
- # Documentation
59
-
60
- Check out the [Documentation](https://tomato6966.github.io/lavalink-client/)
61
- - See all [Manager-Events, e.g. for Track / player and general errors / logs](https://tomato6966.github.io/lavalink-client/extra/manager-events)
62
- - See all [NodeManager-Events e.g. for Node Errors / logs](https://tomato6966.github.io/lavalink-client/extra/node-events)
63
- - See the Guide on [How to do resuming](https://tomato6966.github.io/lavalink-client/extra/resuming)
86
+ <details>
87
+ <summary><strong>👉 via pnpm</strong></summary>
64
88
 
65
- # Used in:
89
+ ```bash
90
+ # Stable (install release)
91
+ pnpm add lavalink-client
66
92
 
67
- - [**Mivator** *(Bot by Chrissy8283 aka @Tomato6966)*](https://discord.gg/5dUb7M2qCj)
68
- - [Betty *(Bot by good friend of Chrissy, aka fb_sean)*](https://betty.cx/)
69
- - **Bots by Contributors:**
70
- - [Mintone (@appujet)](https://mintone.tech/)
71
- - [Stelle (@EvilG-MC)](https://github.com/Ganyu-Studios/stelle-music)
72
- - [Panais (@LucasB25)](https://panais.xyz/)
73
- - **Community:**
74
- - [Soundy (@idMJA)](https://github.com/idMJA/Soundy)
93
+ # Development (Install github dev-branch)
94
+ pnpm add tomato6966/lavalink-client
95
+ ```
75
96
 
97
+ </details>
76
98
 
77
- # Features
99
+ ## 📖 Documentation & Guides
78
100
 
79
- - 💯 Lavalink v4 Supported only (with Lavalink Plugins)
101
+ - **[Full Documentation](https://tomato6966.github.io/lavalink-client/)** - Your starting point for everything.
102
+ - **[Manager Events](https://tomato6966.github.io/lavalink-client/extra/manager-events)** - Handle track, player, and general client events.
103
+ - **[NodeManager Events](https://tomato6966.github.io/lavalink-client/extra/node-events)** - Manage node connections, errors, and logs.
104
+ - **[Session Resuming Guide](https://tomato6966.github.io/lavalink-client/extra/resuming)** - Learn how to implement session resuming for seamless restarts.
80
105
 
81
- - ✅ Player-Destroy Reasons like:
82
- - Channel got deleted, Player got disconnected...
106
+ ***
83
107
 
84
- - Choose able queue stores (maps, collections, redis, databases, ...)
85
- - You can create your own queueStore, thus make it easy to sync queues accross multiple connections (e.g. dashboard-bot)
86
- - Automated Queue Sync methods
87
- - Automated unresolveable Tracks (save the queries as Partial Track Objects -> Fetch the tracks only once they are gonna play)
108
+ ## 💖 Used In
109
+ This client powers various Discord bots:
110
+ - **[Mivator](https://discord.gg/5dUb7M2qCj)** (Public Bot by @Tomato6966)
111
+ - **[Betty](https://betty.cx/)** (Public Bot by fb_sean)
112
+ - **Bots by Contributors:**
113
+ - [Mintone](https://mintone.tech/) (@appujet)
114
+ - [Stelle](https://github.com/Ganyu-Studios/stelle-music) (@EvilG-MC)
115
+ - [Panais](https://panais.xyz/) (@LucasB25)
116
+ - [Akyn](https://akynbot.vercel.app/) (@notdeltaxd)
117
+ - **Bots Community (Users):**
118
+ - [Soundy](https://github.com/idMJA/Soundy) (@idMJA)
88
119
 
89
- - 😍 Included Filter & Equalizer Management
120
+ ***
90
121
 
91
- - 👍 Multiple Player Options *for easier use*
92
- - onDisconnect -> Player Destroy / auto Reconnect
93
- - onEmptyQueue -> Player Destroy / leave After x Time
94
- - instaFixFilter -> seek the player after applying a filter, to instantly apply it's effect (only works for little-durational-songs)
95
- - applyVolumeAsFilter -> instead of using lavalink.volume, it uses lavalink.filters.volume which is much different!
122
+ ## 🛠️ Configuration Examples
96
123
 
97
- - 🛡️ Lavalink Validations
98
- - It only let's you use the filters / plugins / sources, if Lavalink actually has it enabled
124
+ ### Basic Setup
125
+ A minimal example to get you started quickly.
126
+ ```typescript
127
+ import { LavalinkManager } from "lavalink-client";
128
+ import { Client, GatewayIntentBits } from "discord.js"; // example for a discord bot
99
129
 
100
- - 🛡️ Client Validations
101
- - Allows you to whitelist links and even blacklist links / words / domain names, so that it doesn't allow requests you don't want!
102
- - Checks almost all Lavalink Requests for out of bound errors, right before the request is made to prevent process breaking errors.
130
+ // Extend the Client type to include the lavalink manager
131
+ declare module "discord.js" {
132
+ interface Client {
133
+ lavalink: LavalinkManager;
134
+ }
135
+ }
103
136
 
104
- - 🧑‍💻 Memory friendly and easy style
105
- - Only the required data is displayed, and the store-way & types match Lavalink#IMPLEMENTATION.md
137
+ const client = new Client({
138
+ intents: [
139
+ GatewayIntentBits.Guilds,
140
+ GatewayIntentBits.GuildVoiceStates,
141
+ ]
142
+ });
106
143
 
107
- - 😘 Automated Handlings
108
- - Skips the songs, on TrackEnd, TrackStuck, TrackError,
109
- - Destroys the player on channeldelete
110
- - Pauses / resumes the player if it get's muted / unmuted (server-wide) [soon]
111
- - ...
144
+ client.lavalink = new LavalinkManager({
145
+ nodes: [
146
+ {
147
+ authorization: "youshallnotpass", // The password for your Lavalink server
148
+ host: "localhost",
149
+ port: 2333,
150
+ id: "Main Node",
151
+ }
152
+ ],
153
+ // A function to send voice server updates to the Lavalink client
154
+ sendToShard: (guildId, payload) => {
155
+ const guild = client.guilds.cache.get(guildId);
156
+ if (guild) guild.shard.send(payload);
157
+ },
158
+ autoSkip: true,
159
+ client: {
160
+ id: process.env.CLIENT_ID, // Your bot's user ID
161
+ username: "MyBot",
162
+ },
163
+ });
112
164
 
113
- - 😁 Much much more!
165
+ // Listen for the 'raw' event from discord.js and forward it
166
+ client.on("raw", (d) => client.lavalink.sendRawData(d));
114
167
 
115
- ***
168
+ client.on("ready", () => {
169
+ console.log(`Logged in as ${client.user.tag}!`);
170
+ // Initialize the Lavalink client
171
+ client.lavalink.init({ ...client.user });
172
+ });
116
173
 
117
- # Sample Configuration
174
+ client.login(process.env.DISCORD_TOKEN);
175
+ ```
118
176
 
177
+ <details>
178
+ <summary><strong>🔩 Complete Configuration Example (almost all Options)</strong></summary>
119
179
 
120
- <details><summary>Complete Configuration Example, with all available options</summary>
180
+ ```typescript
181
+ import { LavalinkManager, QueueChangesWatcher, QueueStoreManager, StoredQueue } from "lavalink-client";
182
+ import { RedisClientType, createClient } from "redis";
183
+ import { Client, GatewayIntentBits, User } from "discord.js";
121
184
 
122
- ```ts
123
- import { LavalinkManager, QueueChangesWatcher, QueueStoreManager } from "lavalink-client";
124
- import { RedisClientType } from "redis"; // example for custom queue store
125
- import { Client, GatewayIntentBits } from "discord.js"; // example for a discord bot
185
+ // It's recommended to extend the Client type
186
+ declare module "discord.js" {
187
+ interface Client {
188
+ lavalink: LavalinkManager;
189
+ redis: RedisClientType;
190
+ }
191
+ }
126
192
 
127
- // you might want to extend the types of the client, to bind lavalink to it.
128
193
  const client = new Client({
129
194
  intents: [
130
195
  GatewayIntentBits.Guilds,
@@ -132,721 +197,262 @@ const client = new Client({
132
197
  ]
133
198
  });
134
199
 
135
- const previouslyUsedSessions = new Map<string, string>(); //nodeManager.on("connect", node => previouslyUsedSessions.set(node.id, node.sessionId))
136
-
137
200
  client.lavalink = new LavalinkManager({
138
201
  nodes: [
139
202
  {
140
- authorization: "localhoist",
203
+ authorization: "youshallnotpass",
141
204
  host: "localhost",
142
205
  port: 2333,
143
206
  id: "testnode",
144
- // get the previously used session, to restart with "resuming" enabled
145
- sessionId: previouslyUsedSessions.get("testnode"),
146
- requestSignalTimeoutMS: 3000,
147
- closeOnError: true,
148
- heartBeatInterval: 30_000,
149
- enablePingOnStatsCheck: true,
150
- retryDelay: 10e3,
151
- secure: false,
207
+ secure: false, // Set to true for wss://
152
208
  retryAmount: 5,
209
+ retryDelay: 10_000, // 10 seconds
153
210
  }
154
211
  ],
155
212
  sendToShard: (guildId, payload) => client.guilds.cache.get(guildId)?.shard?.send(payload),
156
- autoSkip: true,
157
- client: { // client: client.user
158
- id: envConfig.clientId, // REQUIRED! (at least after the .init)
213
+ autoSkip: true, // automatically play the next song of the queue, on: trackend, trackerror, trackexception
214
+ client: {
215
+ id: process.env.CLIENT_ID,
159
216
  username: "TESTBOT",
160
217
  },
161
- autoSkipOnResolveError: true, // skip song, if resolving an unresolved song fails
162
- emitNewSongsOnly: true, // don't emit "looping songs"
163
218
  playerOptions: {
164
- // These are the default prevention methods
165
- maxErrorsPerTime: {
166
- threshold: 10_000,
167
- maxAmount: 3,
168
- },
169
- // only allow an autoplay function to execute, if the previous function was longer ago than this number.
170
- minAutoPlayMs: 10_000,
171
-
172
219
  applyVolumeAsFilter: false,
173
- clientBasedPositionUpdateInterval: 50, // in ms to up-calc player.position
220
+ clientBasedPositionUpdateInterval: 50,
174
221
  defaultSearchPlatform: "ytmsearch",
175
- volumeDecrementer: 0.75, // on client 100% == on lavalink 75%
176
- requesterTransformer: requesterTransformer,
222
+ volumeDecrementer: 0.75,
177
223
  onDisconnect: {
178
- autoReconnect: true, // automatically attempts a reconnect, if the bot disconnects from the voice channel, if it fails, it get's destroyed
179
- destroyPlayer: false // overrides autoReconnect and directly destroys the player if the bot disconnects from the vc
224
+ autoReconnect: true,
225
+ destroyPlayer: false,
180
226
  },
181
227
  onEmptyQueue: {
182
- destroyAfterMs: 30_000, // 0 === instantly destroy | don't provide the option, to don't destroy the player
183
- autoPlayFunction: autoPlayFunction,
228
+ destroyAfterMs: 30_000,
229
+ // function get's called onqueueempty, and if there are songs added to the queue, it continues playing. if not then not (autoplay functionality)
230
+ // autoPlayFunction: async (player) => { /* ... */ },
184
231
  },
185
232
  useUnresolvedData: true,
186
233
  },
187
234
  queueOptions: {
188
235
  maxPreviousTracks: 10,
189
- // only needed if you want and need external storage, don't provide if you don't need to
190
- queueStore: new myCustomStore(client.redis), // client.redis = new redis()
191
- // only needed, if you want to watch changes in the queue via a custom class,
192
- queueChangesWatcher: new myCustomWatcher(client)
236
+ queueStore: new MyCustomRedisStore(client.redis),
237
+ queueChangesWatcher: new MyCustomQueueWatcher(client),
193
238
  },
239
+ // Whitelist/Blacklist links or words
194
240
  linksAllowed: true,
195
- // example: don't allow p*rn / youtube links., you can also use a regex pattern if you want.
196
- // linksBlacklist: ["porn", "youtube.com", "youtu.be"],
197
- linksBlacklist: [],
241
+ linksBlacklist: ["somebadsite.com"],
198
242
  linksWhitelist: [],
199
243
  advancedOptions: {
200
- enableDebugEvents: true,
201
- maxFilterFixDuration: 600_000, // only allow instafixfilterupdate for tracks sub 10mins
202
244
  debugOptions: {
203
245
  noAudio: false,
204
- playerDestroy: {
205
- dontThrowError: false,
206
- debugLog: false,
207
- },
208
- logCustomSearches: false,
246
+ playerDestroy: { dontThrowError: false, debugLog: false },
209
247
  }
210
248
  }
211
249
  });
212
250
 
251
+ client.on("raw", d => client.lavalink.sendRawData(d));
252
+ client.on("ready", () => client.lavalink.init({ ...client.user }));
213
253
 
214
- client.on("raw", d => client.lavalink.sendRawData(d)); // send raw data to lavalink-client to handle stuff
215
-
216
- client.on("ready", () => {
217
- client.lavalink.init(client.user); // init lavalink
218
- });
219
-
220
- // for the custom queue Store create a redis instance
221
- client.redis = createClient({ url: "redis://localhost:6379", password: "securepass" });
222
- client.redis.connect();
223
-
224
-
225
- // Custom external queue Store
226
- export class myCustomStore implements QueueStoreManager {
227
- private redis:RedisClientType;
228
- constructor(redisClient:RedisClientType) {
254
+ // Example Custom Redis Queue Store
255
+ class MyCustomRedisStore implements QueueStoreManager {
256
+ private redis: RedisClientType;
257
+ constructor(redisClient: RedisClientType) {
229
258
  this.redis = redisClient;
230
259
  }
231
- async get(guildId): Promise<any> {
232
- return await this.redis.get(this.id(guildId));
233
- }
234
- async set(guildId, stringifiedQueueData): Promise<any> {
235
- return await this.redis.set(this.id(guildId), stringifiedQueueData);
236
- }
237
- async delete(guildId): Promise<any> {
238
- return await this.redis.del(this.id(guildId));
239
- }
240
- async parse(stringifiedQueueData): Promise<Partial<StoredQueue>> {
241
- return JSON.parse(stringifiedQueueData);
242
- }
243
- async stringify(parsedQueueData): Promise<any> {
244
- return JSON.stringify(parsedQueueData);
245
- }
246
- private id(guildId) {
247
- return `lavalinkqueue_${guildId}`; // transform the id to your belikings
248
- }
260
+ private key(guildId: string) { return `lavalinkqueue_${guildId}`; }
261
+ async get(guildId: string) { return await this.redis.get(this.key(guildId)); }
262
+ async set(guildId: string, data: string) { return await this.redis.set(this.key(guildId), data); }
263
+ async delete(guildId: string) { return await this.redis.del(this.key(guildId)); }
264
+ async parse(data: string): Promise<Partial<StoredQueue>> { return JSON.parse(data); }
265
+ stringify(data: Partial<StoredQueue>): string { return JSON.stringify(data); }
249
266
  }
250
267
 
251
- // Custom Queue Watcher Functions
252
- export class myCustomWatcher implements QueueChangesWatcher {
253
- constructor() {
254
- }
255
- shuffled(guildId, oldStoredQueue, newStoredQueue) {
256
- console.log(`${this.client.guilds.cache.get(guildId)?.name || guildId}: Queue got shuffled`)
257
- }
258
- tracksAdd(guildId, tracks, position, oldStoredQueue, newStoredQueue) {
259
- console.log(`${this.client.guilds.cache.get(guildId)?.name || guildId}: ${tracks.length} Tracks got added into the Queue at position #${position}`);
260
- }
261
- tracksRemoved(guildId, tracks, position, oldStoredQueue, newStoredQueue) {
262
- console.log(`${this.client.guilds.cache.get(guildId)?.name || guildId}: ${tracks.length} Tracks got removed from the Queue at position #${position}`);
263
- }
268
+ // Example Custom Queue Watcher
269
+ class MyCustomQueueWatcher implements QueueChangesWatcher {
270
+ private client: Client;
271
+ constructor(client: Client) { this.client = client; }
272
+ shuffled(guildId: string) { console.log(`Queue shuffled in guild: ${guildId}`); }
273
+ tracksAdd(guildId: string, tracks: any[], position: number) { console.log(`${tracks.length} tracks added at position ${position} in guild: ${guildId}`); }
274
+ tracksRemoved(guildId: string, tracks: any[], position: number) { console.log(`${tracks.length} tracks removed at position ${position} in guild: ${guildId}`); }
264
275
  }
265
276
  ```
266
277
 
267
278
  </details>
268
279
 
280
+ ***
269
281
 
270
-
271
- ```ts
272
- import { LavalinkManager } from "lavalink-client";
273
- import { Client, GatewayIntentBits } from "discord.js"; // example for a discord bot
274
-
275
- // you might want to extend the types of the client, to bind lavalink to it.
276
- const client = new Client({
277
- intents: [
278
- GatewayIntentBits.Guilds,
279
- GatewayIntentBits.GuildVoiceStates,
280
- ]
282
+ ## 📢 Events
283
+ Listen to events to create interactive and responsive logic.
284
+
285
+ ### Lavalink Manager Events
286
+ These events are emitted from the main `LavalinkManager` instance and relate to players and tracks.
287
+
288
+ - `playerCreate (player)`
289
+ - `playerDestroy (player, reason)`
290
+ - `playerDisconnect (player, voiceChannelId)`
291
+ - `playerMove (player, oldChannelId, newChannelId)`
292
+ - `trackStart (player, track)`
293
+ - `trackEnd (player, track)`
294
+ - `trackStuck (player, track, payload)`
295
+ - `trackError (player, track, payload)`
296
+ - `queueEnd (player)`
297
+
298
+ <details>
299
+ <summary><strong>📢 Example for Manager-Event-Listeners</strong></summary>
300
+
301
+ ```javascript
302
+ // Example: Listening to a track start event
303
+ client.lavalink.on("trackStart", (player, track) => {
304
+ const channel = client.channels.cache.get(player.textChannelId);
305
+ if(channel) channel.send(`Now playing: ${track.info.title}`);
281
306
  });
282
307
 
283
- // create instance
284
- client.lavalink = new LavalinkManager({
285
- nodes: [
286
- {
287
- authorization: "localhoist",
288
- host: "localhost",
289
- port: 2333,
290
- id: "testnode",
291
- }
292
- ],
293
- sendToShard: (guildId, payload) => client.guilds.cache.get(guildId)?.shard?.send(payload),
294
- autoSkip: true,
295
- client: {
296
- id: envConfig.clientId,
297
- username: "TESTBOT",
298
- },
308
+ // Example: Handling queue end
309
+ client.lavalink.on("queueEnd", (player) => {
310
+ const channel = client.channels.cache.get(player.textChannelId);
311
+ if(channel) channel.send("The queue has finished. Add more songs!");
312
+ player.destroy();
299
313
  });
314
+ ```
315
+ </details>
300
316
 
301
- client.on("raw", d => client.lavalink.sendRawData(d)); // send raw data to lavalink-client to handle stuff
317
+ ### Node Manager Events
318
+ These events are emitted from `lavalink.nodeManager` and relate to the Lavalink node connections.
302
319
 
303
- client.on("ready", () => {
304
- client.lavalink.init(client.user); // init lavalink
305
- });
320
+ - `create (node)`
321
+ - `connect (node)`
322
+ - `disconnect (node, reason)`
323
+ - `reconnecting (node)`
324
+ - `destroy (node)`
325
+ - `error (node, error, payload)`
326
+ - `resumed (node, payload, players)`
306
327
 
307
- ```
328
+ <details>
329
+ <summary><strong>📢 Example for Node-Event-Listeners</strong></summary>
308
330
 
309
- # All Events:
310
-
311
- ## On **Lavalink-Manager**:
312
- > *Player related logs*
313
- - `playerCreate` ➡️ `(player) => {}`
314
- - `playerDestroy` ➡️ `(player, reason) => {}`
315
- - `playerDisconnect` ➡️ `(player, voiceChannelId) => {}`
316
- - `playerMove` ➡️ `(player, oldChannelId, newChannelId) => {}`
317
- - Updating the voice channel is handled by the client automatically
318
- - `playerSocketClosed` ➡️ `(player, payload) => {}`
319
-
320
- > *Track / Manager related logs*
321
- - `trackStart` ➡️ `(player, track, payload) => {}`
322
- - `trackStuck` ➡️ `(player, track, payload) => {}`
323
- - `trackError` ➡️ `(player, track, payload) => {}`
324
- - `trackEnd` ➡️ `(player, track, payload) => {}`
325
- - `queueEnd` ➡️ `(player, track, payload) => {}`
326
- - `playerUpdate` ➡️ `(player) => {}`
327
-
328
- ```js
329
- client.lavalink.on("create", (node, payload) => {
330
- console.log(`The Lavalink Node #${node.id} connected`);
331
+ ```javascript
332
+ // Example: Logging node connections and errors
333
+ client.lavalink.nodeManager.on("connect", (node) => {
334
+ console.log(`Node "${node.id}" connected!`);
331
335
  });
332
- // for all node based errors:
333
- client.lavalink.on("error", (node, error, payload) => {
334
- console.error(`The Lavalink Node #${node.id} errored: `, error);
335
- console.error(`Error-Payload: `, payload)
336
- });
337
- ```
338
336
 
339
- ## On **Node-Manager**:
340
- - `raw` ➡️ `(node, payload) => {}`
341
- - `disconnect` ➡️ `(node, reason) => {}`
342
- - `connect` ➡️ `(node) => {}`
343
- - `reconnecting` ➡️ `(node) => {}`
344
- - `create` ➡️ `(node) => {}`
345
- - `destroy` ➡️ `(node) => {}`
346
- - `error` ➡️ `(node, error, payload) => {}`
347
- - `resumed` ➡️ `(node, payload, players) => {}`
348
- - Resuming needs to be handled manually by you *(aka add the players to the manager)*
349
- - e.g. of listening to node events:
350
- ```js
351
- client.lavalink.nodeManager.on("create", (node, payload) => {
352
- console.log(`The Lavalink Node #${node.id} connected`);
353
- });
354
- // for all node based errors:
355
- client.lavalink.nodeManager.on("error", (node, error, payload) => {
356
- console.error(`The Lavalink Node #${node.id} errored: `, error);
357
- console.error(`Error-Payload: `, payload)
337
+ client.lavalink.nodeManager.on("error", (node, error) => {
338
+ console.error(`Node "${node.id}" encountered an error:`, error.message);
358
339
  });
359
340
  ```
341
+ </details>
360
342
 
361
- ## How to log queue logs?
362
- > When creating the manager, add the option: `queueOptions.queueChangesWatcher: new myCustomWatcher(botClient)`
363
- > E.g:
364
- ```js
365
- import { QueueChangesWatcher, LavalinkManager } from "lavalink-client";
343
+ ***
366
344
 
367
- class myCustomWatcher implements QueueChangesWatcher {
368
- constructor(client) {
369
- this.client = client;
370
- }
371
- shuffled(guildId, oldStoredQueue, newStoredQueue) {
372
- console.log(`${this.client.guilds.cache.get(guildId)?.name || guildId}: Queue got shuffled`)
373
- }
374
- tracksAdd(guildId, tracks, position, oldStoredQueue, newStoredQueue) {
375
- console.log(`${this.client.guilds.cache.get(guildId)?.name || guildId}: ${tracks.length} Tracks got added into the Queue at position #${position}`);
376
- }
377
- tracksRemoved(guildId, tracks, position, oldStoredQueue, newStoredQueue) {
378
- console.log(`${this.client.guilds.cache.get(guildId)?.name || guildId}: ${tracks.length} Tracks got removed from the Queue at position #${position}`);
379
- }
380
- }
345
+ ## 📚 Advanced How-To Guides
381
346
 
382
- client.lavalink = new LavalinkManager({
383
- // ... other options
384
- queueOptions: {
385
- queueChangesWatcher: new myCustomWatcher(client)
386
- }
387
- })
388
- ```
347
+ ### How to Implement Session Resuming
348
+ Resuming allows your music bot to continue playback even after a restart.
389
349
 
390
- ## How to do resuming
391
-
392
- 1. You need to enable resuming on a __connected__ Lavalink node : **` node.updateSession(true, 360e3) `**
393
- 2. The NodeManager#resumed event will emit when the node resumes, you retrieves all fetchedPlayers (fetched by the client), and thus all you need to do is re-create all player instances (and possibly the queues too)
394
- - For that is the queuestore useful
395
- - To save the playerData you can utilize smt like playerUpdate event.
396
-
397
- ## Resuming full Example
398
- Full code sample: can be found on the [Testbot in here](https://github.com/Tomato6966/lavalink-client/blob/main/testBot/Utils/handleResuming.ts)
399
- ```js
400
- // but here is the schema:
401
- client.lavalink.nodeManager.on("connect", (node) => node.updateSession(true, 360e3));
402
- client.lavalink.nodeManager.on("resumed", (node, payload, fetchedPlayers) => {
403
- // create players:
404
- for(const fetchedPlayer of fetchedPlayers) {
405
- // fetchedPlayer is the live data from lavalink
406
- // saved Player data is the config you should save in a database / file or smt
407
- const savedPlayerData = await getSavedPlayerData(fetchedPlayer.guildId);
408
- const player = client.lavalink.createPlayer({
409
- guildId: fetchedPlayer.guildId,
410
- });
411
- // if lavalink says the bot got disconnected, we can skip the resuming, or force reconnect whatever you want!, here we choose to not do anything and thus delete the saved player data
412
- if(!data.state.connected) {
413
- console.log("skipping resuming player, because it already disconnected");
414
- await deletedSavedPlayerData(data.guildId);
415
- continue;
350
+ 1. **Enable Resuming on the Node:** When a node connects, enable resuming with a timeout.
351
+ 2. **Listen for the `resumed` Event:** This event fires on a successful reconnect, providing all player data from Lavalink.
352
+ 3. **Re-create Players:** Use the data from the `resumed` event and your own saved data (from a database/store) to rebuild the players and their queues.
353
+
354
+ > 💡 **For a complete, working example, see the [official test bot's implementation](https://github.com/Tomato6966/lavalink-client/blob/main/testBot/Utils/handleResuming.ts).**
355
+
356
+ <details>
357
+ <summary><strong>💡 Principle of how to enable **resuming**</strong></summary>
358
+
359
+ ```javascript
360
+ // 1. Enable resuming on connect
361
+ client.lavalink.nodeManager.on("connect", (node) => {
362
+ // Enable resuming for 5 minutes (300,000 ms)
363
+ node.updateSession(true, 300_000);
364
+ });
365
+
366
+ // 2. Listen for the resumed event
367
+ client.lavalink.nodeManager.on("resumed", async (node, payload, fetchedPlayers) => {
368
+ console.log(`Node "${node.id}" successfully resumed with ${fetchedPlayers.length} players.`);
369
+
370
+ for (const lavalinkData of fetchedPlayers) {
371
+ // 3. Get your saved data (e.g., from Redis/DB)
372
+ const savedData = await getFromDatabase(lavalinkData.guildId);
373
+ if (!savedData || !lavalinkData.state.connected) {
374
+ if(savedData) await deleteFromDatabase(lavalinkData.guildId);
375
+ continue; // Skip if no saved data or Lavalink reports disconnected
416
376
  }
417
- // now you can create the player based on the live and saved data
377
+
378
+ // Re-create the player instance
418
379
  const player = client.lavalink.createPlayer({
419
- guildId: data.guildId,
380
+ guildId: lavalinkData.guildId,
381
+ voiceChannelId: savedData.voiceChannelId,
382
+ textChannelId: savedData.textChannelId,
383
+ // Important: Use the same node that was resumed
420
384
  node: node.id,
421
- // you need to update the volume of the player by the volume of lavalink which might got decremented by the volume decrementer
422
- volume: client.lavalink.options.playerOptions?.volumeDecrementer
423
- ? Math.round(data.volume / client.lavalink.options.playerOptions.volumeDecrementer)
424
- : data.volume,
425
- // all of the following options are needed to be provided by some sort of player saving
426
- voiceChannelId: dataOfSaving.voiceChannelId,
427
- textChannelId: dataOfSaving.textChannelId,
428
- // all of the following options can either be saved too, or you can use pre-defined defaults
429
- selfDeaf: dataOfSaving.options?.selfDeaf || true,
430
- selfMute: dataOfSaving.options?.selfMute || false,
431
-
432
- applyVolumeAsFilter: dataOfSaving.options.applyVolumeAsFilter,
433
- instaUpdateFiltersFix: dataOfSaving.options.instaUpdateFiltersFix,
434
- vcRegion: dataOfSaving.options.vcRegion,
385
+ // Set volume from Lavalink's data, accounting for the volume decrementer
386
+ volume: lavalinkData.volume,
387
+ selfDeaf: savedData.selfDeaf,
435
388
  });
436
389
 
437
- // player.voice = data.voice;
438
- // normally just player.voice is enough, but if you restart the entire bot, you need to create a new connection, thus call player.connect();
390
+ // Re-establish voice connection
439
391
  await player.connect();
440
392
 
441
- player.filterManager.data = data.filters; // override the filters data
442
- await player.queue.utils.sync(true, false); // get the queue data including the current track (for the requester)
443
- // override the current track with the data from lavalink
444
- if(data.track) player.queue.current = client.lavalink.utils.buildTrack(data.track, player.queue.current?.requester || client.user);
445
- // override the position of the player
446
- player.lastPosition = data.state.position;
447
- player.lastPositionChange = Date.now();
448
- // you can also override the ping of the player, or wait about 30s till it's done automatically
449
- player.ping.lavalink = data.state.ping;
450
- // important to have skipping work correctly later
451
- player.paused = data.paused;
452
- player.playing = !data.paused && !!data.track;
453
- // That's about it
454
- }
455
- })
456
- client.lavalink.on("playerUpdate", (oldPlayer, newPlayer) => { // automatically sync player data on updates. if you don'T want to save everything you can instead also just save the data on playerCreate
457
- setSavedPlayerData(newPlayer.toJSON());
458
- });
459
- // delete the player again
460
- client.lavalink.on("playerDestroy", (player) => {
461
- deleteSavedPlayerData(player.guildId);
462
- })
463
- ```
464
-
465
- ***
393
+ // Restore player state
394
+ player.paused = lavalinkData.paused;
395
+ player.lastPosition = lavalinkData.state.position;
396
+ player.filterManager.data = lavalinkData.filters;
466
397
 
398
+ // Restore the queue
399
+ await player.queue.utils.sync(true, false); // Syncs with your QueueStore
467
400
 
468
- ### How to use flowertts with custom options
469
-
470
- - First enable flowertts within the lava-src plugin
471
- - Then make sure to pass through the extraQueryUrlParams object
401
+ // Restore the current track
402
+ if (lavalinkData.track) {
403
+ player.queue.current = client.lavalink.utils.buildTrack(lavalinkData.track, savedData.requester);
404
+ }
405
+ }
406
+ });
472
407
 
473
- ```js
474
- const query = interaction.options.getString("text");
475
- const voice = interaction.options.getString("voice");
408
+ // Persist player data on updates to use for resuming later
409
+ client.lavalink.on("playerUpdate", (oldPlayer, newPlayer) => {
410
+ saveToDatabase(newPlayer.toJSON());
411
+ });
476
412
 
477
- const extraParams = new URLSearchParams();
478
- if(voice) extraParams.append(`voice`, voice);
479
-
480
- // all params for flowertts can be found here: https://flowery.pw/docs
481
- const response = await player.search({
482
- query: `${query}`,
483
- extraQueryUrlParams: extraParams, // as of my knowledge this is currently only used for flowertts, adjusting the playback url dynamically mid-request
484
- source: "ftts"
485
- }, interaction.user);
413
+ // Clean up data when a player is permanently destroyed
414
+ client.lavalink.on("playerDestroy", (player) => {
415
+ deleteFromDatabase(player.guildId);
416
+ });
486
417
  ```
418
+ </details>
487
419
 
420
+ ### How to Use Plugins
421
+ Lavalink client supports most of the major lavalink-plugins.
422
+ The client itself is - for beginner friendly reasons - atm not extendable (via plugins)
423
+ You can just use the built in functions (sponsor block, lyrics) or search plattforms (deezer, spotify, apple music, youtube, ...) and use the lavalink-plugins without any configuration on the client side.
424
+
425
+ Some plugins require extra-parameters, such as flowerytts:
426
+ Pass extra parameters to the search function to use plugin-specific features.
488
427
 
489
- ***
490
-
428
+ <details>
429
+ <summary><strong>How to use the flowerytts plugin</strong></summary>
491
430
 
492
- # UpdateLog
493
-
494
-
495
- ## **Version 1.2.0**
496
- - Added `player.stopPlaying()`: When executed it **clears the Queue** and **stops playing**, **without destroying the Player**
497
- - Adjusted `Player.skip()`
498
- - Added `throwError` Property to: `player.skip(skipTo?:number = 0, throwError?:boolean = true)`.
499
- - If throwError = false, and no more tracks are in the queue, it won't throw an error and "ignore it". same thing as stopPlaying.
500
- - Added all Events and Methods from the [SponsorBlock Plugin](https://github.com/topi314/Sponsorblock-Plugin).
501
- - It also validates if the plugin is in the bot, in order so that you can use the functions:
502
- - `player.getSponsorBlock()` / `node.getSponsorBlock()`
503
- - `player.setSponsorBlock(segments:SponsorBlockSegment[])` / `node.setSponsorBlock(segments:SponsorBlockSegment[])`
504
- - `player.deleteSponsorBlock()` / `node.deleteSponsorBlock()`
505
- - That Plugin adds following **Events** to the **Manager**: `"SegmentsLoaded"`, `"SegmentSkipped"`, `"ChapterStarted"`, `"ChaptersLoaded"`
506
- - Example Bot show example in autoplayFunction how to "disable" / "enable" Autoplay with bot data variables.
507
- - Added `ManagerOptions#emitNewSongsOnly`. If set to true, it won't emit "trackStart" Event, when track.loop is active, or the new current track == the previous (current) track.
508
- - Added `ManagerOptions#linksBlacklist` which allows user to specify an array of regExp / strings to match query strings (for links / words) and if a match happens it doesn't allow the request (blacklist)
509
- - Added `ManagerOptions#linksWhitelist` which allows user to specify an array of regExp / strings to match query strings (for links only) and if a match does NOT HAPPEN it doesn't allow the request (whitelist)
510
- - Added `ManagerOptions#linksAllowed` if set to false, it does not allow requests which are links
511
- - Moved `ManaagerOptions#debugOptions` to `ManaagerOptions#advancedOptions.debugOptions`
512
-
513
- ### **Version 1.2.1**
514
- - Adjusted `player.stopPlaying()`
515
- - There are now following parameters. `stopPlaying(clearQueue:boolean = true, executeAutoplay:boolean = false)`.
516
- - On Default it now clears the queue and stops playing. Also it does not execute Autoplay on default. IF you want the function to behave differently, you can use the 2 states for that.
517
- - Fixed that it looped the current track if repeatmode === "track" / "queue". (it stops playing and loop stays)
518
- - Implemented a `parseLavalinkConnUrl(connectionUrl:string)` Util Function.
519
- - It allows you to parse Lavalink Connection Data of a Lavalink Connection Url.
520
- Pattern: `lavalink://<nodeId>:<nodeAuthorization(Password)>@<NodeHost>:<NodePort>`
521
- - Note that the nodeId and NodeAuthorization must be encoded via encodeURIComponents before you provide it into the function.
522
- - The function will return the following: `{ id: string, authorization: string, host: string, port: number }`
523
- - Example: `parseLavalinkConnUrl("lavalink://LavalinkNode_1:strong%23password1@localhost:2345")` will give you:
524
- `{ id: "LavalinkNode_1", authorization: "strong#password1", host: "localhost", port: 2345 }`
525
- - Note that the password "strong#password1" when encoded turns into "strong%23password1". For more information check the example bot
526
-
527
- ### **Version 2.0.0**
528
- - Lavalink v4 released, adjusted all features from the stable release, to support it in this client!
529
- ```diff
530
-
531
- # How to load tracks / stop playing has changed for the node.updatePlayer rest endpoint the Client handles it automatically
532
- - await player.node.updatePlayer({ encodedTrack?: Base64|null, track?: Track|UnresolvedTrack, identifer?: string });
533
- + await player.node.updatePlayer({ track: { encoded?: Base64|null, identifier?: string }, clientTrack?: Track|UnresolvedTrack });
534
-
535
- # To satisfy the changes from lavalink updatePlayer endpoint, player play also got adjusted for that (Most users won't need this feature!)
536
- - await player.play({ encodedTrack?: Base64|null, track?: Track|UnresolvedTrack, identifer?: string });
537
- + await player.play({ track: { encoded?: Base64|null, identifier?: string }, clientTrack?: Track|UnresolvedTrack });
538
- # However it' still recommended to do it like that:
539
- # first add tracks to the queue
540
- + await player.queue.add(Track: Track|UnresolvedTrack|(Track|UnresolvedTrack)[]);
541
- # then play the next track from the queue
542
- + await player.play();
543
-
544
- # Node Resuming got supported
545
- # First enable it by doing:
546
- + await player.node.updateSession(true, 360_000);
547
- # then when reconnecting to the node add to the node.createeOptions the sessionId: "" of the previous session
548
- # and after connecting the nodeManager.on("resumed", (node, payload, players) => {}) will be executed, where you can sync the players!
549
-
550
- # Node Options got adjusted # It's a property not a method should be treated readonly
551
- + node.resuming: { enabled: boolean, timeout: number | null };
552
-
553
- # Player function got added to stop playing without disconnecting
554
- + player.stopPlaying(clearQueue:boolean = true, executeAutoplay:boolean = false);
555
-
556
- # Node functions for sponsorBlock Plugin (https://github.com/topi314/Sponsorblock-Plugin) got added
557
- + deleteSponsorBlock(player:Player)
558
- + setSponsorBlock(player:Player, segments: ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "filler"])
559
- # only works if you ever set the sponsor blocks once before
560
- + getSponsorBlock(player:Player)
561
- # Corresponding nodeManager events got added:
562
- + nodeManager.on("ChapterStarted");
563
- + nodeManager.on("ChaptersLoaded");
564
- + nodeManager.on("SegmentsLoaded");
565
- + nodeManager.on("SegmentSkipped");
566
- # Filters sending got supported for filters.pluginFilters key from lavalink api: https://lavalink.dev/api/rest.html#plugin-filters
567
- # Native implementation for lavaSearch plugin officially updated https://github.com/topi314/LavaSearch
568
- # Native implementation for lavaSrc plugin officially updated https://github.com/topi314/LavaSrc including floweryTTS
569
- # couple other changes, which aren't noticeable by you.
570
-
571
- # Lavalink track.userData got added (basically same feature as my custom pluginInfo.clientData system)
572
- # You only get the track.userData data through playerUpdate object
573
- ```
574
- In one of the next updates, there will be more queueWatcher options and more custom nodeevents to trace
575
-
576
- Most features of this update got tested, but if you encounter any bugs feel free to open an issue!
577
-
578
- ## **Version 2.1.0**
579
- - Fixed that, if you skip and have trackloop enabled, it doesn't skip the track
580
- - I fixed that in the past, but for some reason i removed the fix on accident ig.
581
- - Reworked the Filter Manager for custom filters via [LavalinkFilterPlugin](https://github.com/rohank05/lavalink-filter-plugin) / [LavalinkLavaDSPX-Plugin](https://github.com/devoxin/LavaDSPX-Plugin/)
582
- - Note that the [LavalinkLavaDSPX-Plugin](https://github.com/devoxin/LavaDSPX-Plugin/) is by a Community Member of Lavalink and UNOFFICIAL
583
- - They now have individual state-variabels (booleans): `player.filterManager.filters.lavalinkLavaDspxPlugin`
584
- - `player.filterManager.filters.lavalinkLavaDspxPlugin.echo`
585
- - `player.filterManager.filters.lavalinkLavaDspxPlugin.normalization`
586
- - `player.filterManager.filters.lavalinkLavaDspxPlugin.highPass`
587
- - `player.filterManager.filters.lavalinkLavaDspxPlugin.lowPass`
588
- - and for: `player.filterManager.filters.lavalinkFilterPlugin` (this plugins seems to not work on v4 at the moment)
589
- - `player.filterManager.filters.lavalinkLavaDspxPlugin.echo`
590
- - `player.filterManager.filters.lavalinkLavaDspxPlugin.reverb`
591
- - They also now have individual state-changing-methods: `player.filterManager.lavalinkLavaDspxPlugin`
592
- - `player.filterManager.lavalinkLavaDspxPlugin.toggleEcho(decay:number, echoLength:number)`
593
- - `player.filterManager.lavalinkLavaDspxPlugin.toggleNormalization(maxAmplitude:number, adaptive:boolean)`
594
- - `player.filterManager.lavalinkLavaDspxPlugin.toggleHighPass(boostFactor:number, cutoffFrequency:number)`
595
- - `player.filterManager.lavalinkLavaDspxPlugin.toggleLowPass(boostFactor:number, cutoffFrequency:number)`
596
- - and for: `player.filterManager.lavalinkFilterPlugin`
597
- - `player.filterManager.lavalinkFilterPlugin.toggleEcho(delay:number, decay:number)`
598
- - `player.filterManager.lavalinkFilterPlugin.toggleReverb(delays:number[], gains:number[])`
599
-
600
- ## **Version 2.1.1**
601
- - Enforce link searches for users with following searchPlatform Options: "http" | "https" | "link" | "uri"
602
- - Additionally strongend the code behind that
603
- - Added searchPlatform for local tracks (aka files on the lavalink server...): "local"
604
-
605
- ## **Version 2.2.0**
606
- - Changed console.error to throw error on queue.utils.sync if no data was provided/found
607
- - Changed undici.fetch to native fetch, but requires nodejs v18+ to support other runtimes, e.g. bun
608
- - Added sourceNames for `bandcamp` (from native lavalink) if it's supported it will use lavalink'S search, else the client search on player.search({ source: "bandcamp" }) (you can also use bcsearch or bc)
609
- - Added sourceName for `phsearch` from the dunktebot plugin, released in v.1.7.0
610
- - Support for youtube still going via the youtube-source plugin (disable youtube for lavalink, and use the plugin instead)
611
- - Exporting events
612
- - Added new debugOption: logCustomSearches
613
- - *(Next version update i will remove the internal interval for position update, to calculations)*
614
-
615
- ## **Version 2.2.1**
616
- - Player position is now calculated instead of using intervals
617
- - Instaplayer fix update now requires quite good internet connection on the lavalink server due to removal of intervals for updating player.position (everything above 300mbps should be good)
618
- - Internal updates for handling query params and url-requests (url-parsing) to fix quite few bugs and make the code more readable, now you don't have to ever provide stuff encoded via encodeURIComponent anymore.
619
- - Added a bunch of jsdoc information, to make the autogenerated docs more accurate!
620
-
621
- - Because of the adjustments from the encoding, you now need to pass url params for stuff like flowery tts like this:
622
-
623
- ```js
431
+ ```javascript
432
+ // Example for flowertts plugin
624
433
  const query = interaction.options.getString("text");
625
- const voice = interaction.options.getString("voice");
434
+ const voice = interaction.options.getString("voice"); // e.g., "MALE_1"
626
435
 
627
436
  const extraParams = new URLSearchParams();
628
- if(voice) extraParams.append(`voice`, voice);
629
-
630
- // all params for flowertts can be found here: https://flowery.pw/docs
631
- const response = await player.search({
632
- query: `${query}`,
633
- extraQueryUrlParams: extraParams, // as of my knowledge this is currently only used for flowertts, adjusting the playback url dynamically mid-request
634
- source: "ftts"
635
- }, interaction.user);
636
- ```
637
-
437
+ if (voice) extraParams.append(`voice`, voice);
438
+
439
+ // All params for flowertts can be found here: https://flowery.pw/docs
440
+ const response = await player.search(
441
+ {
442
+ query: `${query}`,
443
+ // This is used by plugins like ftts to adjust the request
444
+ extraQueryUrlParams: extraParams,
445
+ source: "ftts" // Specify the plugin source
446
+ },
447
+ interaction.user // The requester
448
+ );
638
449
 
639
- ## **Version 2.2.2**
640
- - Fixed a bug in player.pause() where when you pause the track longer than the left over currentTrack.info.duration is, then it would auto skip the track on resume.
641
- - Fixed the handling of the previous track array ( sometimes it adds "null", due to lavalink errors )
642
- - Added new functions for the queue, to make migrations and coding easier for beginners,
643
- - ` const previousTrack = await player.queue.shiftPrevious() ` -> removes the previously played track from the player.queue.previous array, and returns it, so you can use it for something like "play previous"
644
- - *Neat 1-liner: ` await player.queue.shiftPrevious().then(clientTrack => player.play({ clientTrack })) `*
645
- - ` await player.queue.remove(removeQuery) ` -> Remove function to remove stuff from the queue.tracks array., following params are valid:
646
- - Array of Tracks / UnresolvedTracks, e.g. ` await player.queue.remove( player.queue.tracks.slice(4, 10) ) ` *(would remove tracks from #4 (incl.) to #10 (excl.) aka those indexes: 4, 5, 6, 7, 8, 9 - this is how array.slice works)*
647
- - Single Track / UnresolveTrack, e.g. ` await player.queue.remove(player.queue.tracks[player.queue.tracks.length - 1]); ` *(would remove the last track)*
648
- - Array of track-indexes, e.g. ` await player.queue.remove([1, 4, 5]) ` *(Would remove track #1, #4 and #5)*
649
- - Single track index, e.g. ` await player.queue.remove(5) ` *(would remove the #5 track from the queue)*
650
- - **NOTE:** I still highly recommend, to use the ` player.queue.splice() ` function for mutating the queue:
651
- - it is possible to remove single tracks, multiple tracks and insert tracks at specific positions!
652
- - *the remove function haven't been fully tested yet*
653
- - Added `track.pluginInfo.clientData?.previousTrack` handling:
654
- - If a track has this property in the pluginInfo in the clientData object set to "true" then it won't get added to the previous track array. Example:
655
- ```js
656
- const previousTrack = await player.queue.shiftPrevious();
657
- if(previousTrack) {
658
- const previousClientData = previousTrack.pluginInfo.clientData || {};
659
- previousTrack.pluginInfo.clientData = { previousTrack: true, ...previousClientData }
660
- await player.play({ clientTrack: previousTrack });
450
+ // Add the TTS track to the queue
451
+ if (response.tracks.length > 0) {
452
+ player.queue.add(response.tracks[0]);
453
+ if (!player.playing) player.play();
661
454
  }
662
455
  ```
456
+ </details>
663
457
 
664
-
665
- ## **Version 2.3.0**
666
-
667
- - Added a heartbeat + ping-pong system to check wether the client is still connected to the node, if the node doesn't receive a ping in time, it will destroy the node and thus cause a reconnect.
668
- - For that following new nodeOptions got added:
669
- - `enablePingOnStatsCheck: boolean` (default: true)
670
- - `heartBeatInterval: number` (default: 30_000)
671
- - Added new Property on a node:
672
- - `isAlive: boolean` (if it's false, then it's not connected to the node anymore, and will AUTOMATICALLY Cause a reconnect within the heartBeatInterval)
673
- - `heartBeatPing: number` (the ping it takes lavalink to respond to the acknowledge of heartbeat)
674
- - Added new NodeManager Events:
675
- - `reconnectinprogress` (when the client internal reconnect system is triggered, the actual reconnect gets triggered by the node after your retryDelay)
676
- - Refactored internal code for better readability and maintainability
677
- - Removed several intermediate promises
678
- - Added new types for better type safety
679
- - Updated types for better type safety
680
- - Reduced default retryDelay from 30s to 10s
681
- - Added example on the testbot how to store player data easily and how to use the resume feature, and updated the Resuming Example in the README [jump](#how-to-do-resuming) by adding a [full example](#resuming-full-example)
682
-
683
- - **"Breaking Change" for providing track / clientTrack for player.play()**
684
- - Instead of adding the track to the queue and skipping to it, they get directly played by lavalink through replacing the track.
685
- - To make this work, we need to pass the transformed requester object to the userData of the track. (all handled by the client)
686
- - *This is technically better than skipping to a track but i wanted to point it out.*
687
- - You can play with clientTrack like this: `player.play({ clientTrack: searchResult.tracks[0] })`
688
- - You can play with just track like this: `player.play({ track: { encoded: "base64string..." }, requester: interaction.user })`
689
-
690
-
691
- ## **Version 2.3.1**
692
-
693
- - Fixed Export, where types of Manager weren't exported correctly
694
- - Fixed Dist Folder containing old, left over not needed files
695
-
696
- ## **Version 2.3.2** / **Version 2.3.3**
697
- - Added Missing function calls for the QueueWatcher of tracksRemoved within the queue.remove() function:
698
- - Added new DestroyReasons:
699
- - TrackStuckMaxTracksErroredPerTime
700
- - TrackErrorMaxTracksErroredPerTime
701
- - Added new Prevention Systems for CrashbackLoop recognitions:
702
- - `this.NodeManager.LavalinkManager.options.playerOptions.maxErrorsPerTime`:
703
- - object: `{ threshold: number, maxAmount: number }` (set threshold to 0 or maxAmount to -1 to disable)
704
- - Default: `{ threshold: 10_000, maxAmount: 3 }`
705
- - If there are trackError or trackStuck Events > maxAmount within the given treshhold, the player will be destroyed prevent more errors and thus potential ratelimits.
706
- - `this.NodeManager.LavalinkManager.options.playerOptions.minAutoPlayMs`:
707
- - number: `10_000` (default)
708
- - If there is an AutoplayFunction, and it get's executed before that threshold, than it won't trigger the autoplay function again. *(this is ignored for when the player is skipped)*
709
- - This prevents autoplays from happeneing on a crashbackloop
710
- - Set to `0` to disable
711
- - **Added new Event "debug":**
712
- - `LavalinkManager#debug(event:DebugEvents, data:{ state: "log" | "warn" | "error", message:string, functionLayer:string, error?:Error })`
713
- - This function Event will emit, when the following option is set to **` true `**: `LavalinkManager.options.advancedOptions.enableDebugEvents`
714
- - You can use the **` DebugEvents `** Enum to listen to specific events and only show those you care
715
- - You can filter for the **` data.state `** to only show the certain log-level state
716
- - The **` functionLayer `** string will show you where the debug event was triggered from
717
- - The **` message `** string will show what is debugged
718
- - The **` error `** object will show you the error that happened, if there was one.
719
- - *This took quite some time to code, and i am sure there are still many logs you might want, feel free to open an issue
720
-
721
-
722
- ## **Version 2.3.4**
723
- - Improved the package bundling with tsc-alias, to export files with file types
724
- - Added package.json to exported dist, for easier parsing ability and compatibility with older and newer node versions
725
- - Added error handling for resolving unresolved tracks on trackend
726
-
727
-
728
- ## **Version 2.3.5**
729
- - FIXED not able to import :: Accidentally removed tsc-alias configuration, which made importing not work
730
- - FIXED autoplay not working :: Accidentally added an invalid if statement, which made autoplay not working anymore (during the if statement to not prevent autoplay spam)
731
- - Added a new AutoplayExecution Debug Log
732
- - Added more samples to the Testbot related configuration
733
-
734
-
735
- ## **Version 2.3.6**
736
- - Added Lyrics Support:
737
- - New Player Functions:
738
- - **` const lyrics = await player.getCurrentLyrics(false); `** -> *Get lyrics of current playing track*
739
- - **` const lyrics = await player.getLyrics(track, true); `** -> *Get lyrics of a specific track with ignoring it's sources*
740
- - **` player.subscribeLyrics(); `** -> *Subscribe this guild to retrieve "live lyrics" as the song is *playing
741
- - **` player.unsubscribeLyrics(); `** -> *Unsubscribe from lyrics
742
- - New Node Functions ( same as from player, just so you can access it without player too ):*
743
- - **` const lyrics = await player.node.lyrics.getCurrent(player.guildId, false); `**
744
- - **` const lyrics = await player.node.lyrics.get(track, true); `**
745
- - **` player.node.lyrics.subscribe(player.guildId); `**
746
- - **` player.node.lyrics.unsubscribe(player.guildId); `**
747
- - New Manager Event sfor Lyrics:
748
- - **` lavalink.on("LyricsLine", (player, track, lyricsLine) => {}); `**
749
- - **` lavalink.on("LyricsFound", (player, track, data) => {}); `**
750
- - **` lavalink.on("LyricsNotFound", (player, track, lyricsLine) => {}); `**
751
-
752
-
753
- ## **Version 2.4.0**
754
- - Refactored a little the project folder Structure
755
- - Added PR Packages to install all commits / packages at once `https://pkg.pr.new/Tomato6966/lavalink-client`
756
- - Removed the dist folder, and added prepare Scripts
757
- - Added attributes for git linting
758
- - Removed the old (gitbook) documentation, and swapped it to a NEW TSDOC Themed Documentation via astro.dev and mdx
759
- - Added new player events:
760
- - **`playerMuteChange`**** ➡️ **`(player, selfMuted, serverMuted) => {}`
761
- *Triggered when the player's voice state related to muting changed*
762
-
763
- - **`playerDeafChange`** ➡️ `(player, selfDeafed, serverDeafed) => {}`
764
- *Triggered when the player's voice state related to deafing changed*
765
-
766
- - **`playerSuppressChange`** ➡️ `(player, suppress) => {}`
767
- *Triggered when the player's voice state related to suppressing changed*
768
-
769
- - **`playerQueueEmptyStart`** ➡️ `(player, timeoutMs) => {}`
770
- *Triggered when the queue empty handler started (the timeout)*
771
-
772
- - **`playerQueueEmptyEnd`** ➡️ `(player) => {}`
773
- *Triggered when the queue empty handler finished (successfully) and thus destroyed the player*
774
-
775
- - **`playerQueueEmptyCancel`** ➡️ `(player) => {}`
776
- *Triggered when the queue empty handler cancelled (e.g. because a new track got added)*
777
-
778
- ~~- **`playerVoiceEmptyStart`** ➡️ `(player, timeoutMs) => {}`~~
779
- ~~*Triggered when the voice empty handler started (the timeout)*~~
780
- *Removed again because of memory overhall and not wanting to handle voice states*
781
-
782
- ~~- **`playerVoiceEmptyEnd`** ➡️ `(player) => {}`~~
783
- ~~*Triggered when the voice empty handler finished (successfully) and thus destroyed the player*~~
784
- *Removed again because of memory overhall and not wanting to handle voice states*
785
-
786
- ~~- **`playerVoiceEmptyCancel`** ➡️ `(player, userId) => {}`~~
787
- ~~*Triggered when the voice empty handler cancelled (e.g. when a user rejoined)*~~
788
- *Removed again because of memory overhall and not wanting to handle voice states*
789
-
790
- - **`playerVoiceJoin`** ➡️ `(player, userId) => {}`~~
791
- *Added instead of the playerVoiceEmpty handler, emitted when a user joins the player-vc while there is a player*
792
- *Allows you to inmplement a custom playerVoiceEmpty handler*
793
-
794
- - **`playerVoiceLeave`** ➡️ `(player, userId) => {}`~~
795
- *Added instead of the playerVoiceEmpty handler, emitted when a user leaves (or. switches away) the player-vc while there is a player*
796
- *Allows you to inmplement a custom playerVoiceEmpty handler*
797
-
798
- - Added the new events and configuration to the docs
799
-
800
- ## **Version 2.4.1**
801
-
802
- - Did some cleanup and comment removal + removed the playerVoiceEmptyStart because it would mean i'd need to add voice-state tracking, which wasn't the plan of doing by the client.
803
-
804
- ## **Verison 2.4.2**
805
-
806
- - Merged [PR#78](https://github.com/Tomato6966/lavalink-client/pull/78) from @hwangsihu - Added the configs to eslint ignore
807
- - Merged [PR#80](https://github.com/Tomato6966/lavalink-client/pull/80) from @EvilG-MC - Argument Typo fix in resume event type declaration
808
- - Merged [PR#83](https://github.com/Tomato6966/lavalink-client/pull/83) from @EvilG-MC - Fix if statement in Node#syncPlayerData() to allow syncing of "single entry objects"
809
- - Some minor improvements by removing unnecessary spreading
810
-
811
- ## **Version 2.4.3**
812
- - `managerOptions#playerOptions.onDisconnect.autoReconnect`:
813
- - Added the option `managerOptions#playerOptions.onDisconnect.autoReconnectOnlyWithTracks` to control wether to try reconnecting only when there are tracks in the queue / current track or not
814
- - Added a new debug log for that
815
- - Added the try to play the next track if there is no current track
816
- - *There was a problem trying to auto-reconnect on-Disconnect while the queue was empty, which caused the player to get destroyed by that and log the error in console "`There is no Track in the Queue, nor provided in the PlayOptions`"*
817
- - *Now you have to handle that case manually if you want to or set autoReconnectOnlyWithTracks to false (default)*
818
-
819
-
820
- ## **Version 2.4.4 - Version 2.4.6**
821
- - `player.changeNode()` is fixed and works - thanks to @PandaIN95
822
- - The code got re-formatted and re-structured, no code-changes are needed to be made, but it's now cleaner & more readable in some areas
823
- - The same for the testbot Folder(s), also it imports lavalink-client directly, so you can just copy it and move on from it.
824
- - Some minor Fixess:
825
- - Autoplay sometimes doesn't get called when previousAutoplay call failed.
826
- - remove structuredClone so that it works in bun more stable
827
- - Player Options Validation also allows single property objects
828
- - Some typos were fixed
829
-
830
-
831
-
832
- ## **Version 2.5.0**
833
- - Deps got updated
834
- - Handling of parsing url got updated to use the URL object
835
- - Flowerytts requests needs to be changed now:
836
-
837
- ```js
838
- const query = "Hello World How are you?";
839
- const voice = "Ava";
840
- const speed = "1.0";
841
-
842
- const fttsParams = new URLSearchParams();
843
- if(voice) fttsParams.append("voice", voice);
844
- if(speed) fttsParams.append("speed", speed);
845
-
846
- const response = await player.search({
847
- // For flowerytts you need to send a URL
848
- // and if you want to add optiojns, this is how you add the params to the query..
849
- query: `${encodeURI(query)}${fttsParams.size ? `?${fttsParams.toString()}` : ""}`,
850
- source: "ftts"
851
- }, interaction.user);
852
- ```
458
+ </div>