### Complete Lavalink Client Configuration Example Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/configuration.md A comprehensive example demonstrating the setup of LavalinkManager with nodes, client integration, player and queue options, and event handling. This serves as a template for a full client configuration. ```typescript import { LavalinkManager, EQList } from "lavalink-client"; import { Client, GatewayIntentBits } from "discord.js"; const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] }); const lavalink = new LavalinkManager({ // === NODES === nodes: [ { host: "lavalink.example.com", port: 2333, authorization: "very-secure-password", id: "primary", secure: false, retryAmount: 5, retryDelay: 10000 }, { host: "lavalink-backup.example.com", port: 2333, authorization: "very-secure-password", id: "secondary", secure: true // WSS } ], // === REQUIRED === sendToShard: (guildId, payload) => { const guild = client.guilds.cache.get(guildId); if (guild) guild.shard.send(payload); }, client: { id: process.env.CLIENT_ID, username: "MyMusicBot" }, // === PLAYER OPTIONS === playerOptions: { applyVolumeAsFilter: false, clientBasedPositionUpdateInterval: 100, defaultSearchPlatform: "ytmsearch", volumeDecrementer: 0.75, onDisconnect: { autoReconnect: true, destroyPlayer: false }, onEmptyQueue: { destroyAfterMs: 60000 }, useUnresolvedData: true, maxErrorsPerTime: { threshold: 35000, maxAmount: 3 } }, // === QUEUE OPTIONS === queueOptions: { maxPreviousTracks: 50 }, // === LINK FILTERING === linksAllowed: true, linksWhitelist: [], linksBlacklist: ["piracy-site.com"], // === ADVANCED OPTIONS === advancedOptions: { maxFilterFixDuration: 600000, enableDebugEvents: true, debugOptions: { noAudio: false, playerDestroy: { debugLog: false, dontThrowError: false } } }, // === MANAGER OPTIONS === autoSkip: true, autoMove: true, autoSkipOnResolveError: true }); client.on("ready", () => { lavalink.init({ id: client.user.id, username: client.user.username }); }); client.on("raw", (d) => lavalink.sendRawData(d)); ``` -------------------------------- ### Start the Test Bot Source: https://github.com/tomato6966/lavalink-client/blob/main/testBot/README.md Runs the test bot after dependencies are installed and environment variables are configured. ```bash npm run start ``` -------------------------------- ### Install Dev Version with Bun Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/installings/bun.mdx Install the development version directly from GitHub using this command. ```bash bun install tomato6966/lavalink-client ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/tomato6966/lavalink-client/blob/main/testBot/README.md Installs all necessary packages for the project using npm. ```bash npm i ``` -------------------------------- ### Basic Lavalink Client Setup with Discord.js Source: https://github.com/tomato6966/lavalink-client/blob/main/README.md A minimal example to quickly set up the Lavalink client with discord.js. Ensure you have the necessary intents configured for your Discord bot. ```typescript import { LavalinkManager } from "lavalink-client"; import { Client, GatewayIntentBits } from "discord.js"; // example for a discord bot // Extend the Client type to include the lavalink manager declare module "discord.js" { interface Client { lavalink: LavalinkManager; } } const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates], }); client.lavalink = new LavalinkManager({ nodes: [ { authorization: "youshallnotpass", // The password for your Lavalink server host: "localhost", port: 2333, id: "Main Node", }, // you can also use the util like this, and it will return a valid node option object. // parseLavalinkConnUrl("nodelink://:@:") ], // A function to send voice server updates to the Lavalink client sendToShard: (guildId, payload) => { const guild = client.guilds.cache.get(guildId); if (guild) guild.shard.send(payload); }, autoSkip: true, client: { id: process.env.CLIENT_ID, // Your bot's user ID username: "MyBot", }, }); // Listen for the 'raw' event from discord.js and forward it client.on("raw", (d) => client.lavalink.sendRawData(d)); client.on("ready", () => { console.log(`Logged in as ${client.user.tag}!`); // Initialize the Lavalink client client.lavalink.init({ ...client.user }); }); client.login(process.env.DISCORD_TOKEN); ``` -------------------------------- ### Install Development Version via pnpm Source: https://github.com/tomato6966/lavalink-client/blob/main/README.md Install the development version directly from the GitHub repository using pnpm. ```bash pnpm add tomato6966/lavalink-client ``` -------------------------------- ### Install lavalink-client with NPM Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/installings/npm.mdx Use this command to install the stable version of the lavalink-client package from npm. ```bash npm install lavalink-client ``` -------------------------------- ### Retrieve Node Information Example Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/node.md Demonstrates how to get the first available node and retrieve its version, filters, and plugins. Assumes a Lavalink instance is already connected. ```typescript const node = lavalink.nodeManager.nodes.values().next().value; const info = await node.getInfo(); console.log(`Version: ${info.version.semver}`); console.log(`Filters: ${info.filters.join(", ")}`); console.log(`Plugins: ${info.plugins.map(p => p.name).join(", ")}`); ``` -------------------------------- ### Install Development Version via NPM Source: https://github.com/tomato6966/lavalink-client/blob/main/README.md Install the development version directly from the GitHub repository using NPM. ```bash npm install --save tomato6966/lavalink-client ``` -------------------------------- ### Install Development Version from GitHub Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/installings/npm.mdx Install the latest development version directly from the GitHub repository. This is useful for testing the newest features or bug fixes. ```bash npm install tomato6966/lavalink-client ``` -------------------------------- ### Install Development Version via YARN Source: https://github.com/tomato6966/lavalink-client/blob/main/README.md Install the development version directly from the GitHub repository using YARN. ```bash yarn add tomato6966/lavalink-client ``` -------------------------------- ### Install Stable Version with Bun Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/installings/bun.mdx Use this command to install the latest stable version of the lavalink-client package. ```bash bun install lavalink-client ``` -------------------------------- ### Configure Custom Queue Store with Redis Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/configuration.mdx Implement a custom queue store using Redis for persistent queue management. This example shows how to connect to a Redis instance and define methods for getting, setting, and deleting queue data. ```typescript import { createClient, RedisClientType } from "redis"; import { QueueStoreManager, StoredQueue } from "lavalink-client"; // for the custom queue Store create a redis instance client.redis = createClient({ url: "redis://localhost:6379", password: "securepass" }); client.redis.connect(); // Custom external queue Store // if queueStore is not provided on default it uses MiniMap export class myCustomStore implements QueueStoreManager { private redis: RedisClientType; constructor(redisClient: RedisClientType) { this.redis = redisClient; } async get(guildId): Promise { return await this.redis.get(this.id(guildId)); } async set(guildId, stringifiedQueueData): Promise { return await this.redis.set(this.id(guildId), stringifiedQueueData); } async delete(guildId): Promise { return await this.redis.del(this.id(guildId)); } async parse(stringifiedQueueData): Promise> { return JSON.parse(stringifiedQueueData); } async stringify(parsedQueueData): Promise { return JSON.stringify(parsedQueueData); } private id(guildId) { return `lavalinkqueue_${guildId}`; // transform the id to your belikings } } ``` -------------------------------- ### Install Lavalink Client via pnpm Source: https://github.com/tomato6966/lavalink-client/blob/main/README.md Install the latest stable version of the lavalink-client package using pnpm. ```bash pnpm add lavalink-client ``` -------------------------------- ### Listen for SponsorBlock Chapter Started Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/events.md Emitted when a new SponsorBlock chapter begins. Logs the title of the started chapter. ```typescript lavalink.on("ChapterStarted", (player, track, payload) => { console.log(`Chapter started: ${payload.title}`); }); ``` -------------------------------- ### Example of Parsing Lavalink Connection URL Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/extra/version-log.mdx Shows a practical example of using the `parseLavalinkConnUrl` utility function. ```javascript parseLavalinkConnUrl("lavalink://LavalinkNode_1:strong%23password1@localhost:2345") ``` -------------------------------- ### Install pnpm Dev Version from GitHub Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/installings/pnpm.mdx Use this command to install the development version of the lavalink-client package directly from its GitHub repository using pnpm. ```bash pnpm install tomato6966/lavalink-client ``` -------------------------------- ### Build a Queue From Search Results Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/queue.md Demonstrates how to build a queue by adding tracks from search results, including handling playlists and starting playback if the player is not already playing. ```APIDOC ## Build a Queue From Search Results ### Description Build a Queue From Search Results ### Example ```typescript const result = await player.search({ query: "playlist" }, user); if (result.isPlaylist) { player.queue.add(result.tracks); console.log(`Added ${result.tracks.length} tracks`); if (!player.playing) { await player.play(); } } ``` ``` -------------------------------- ### Install Stable Version with Yarn Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/installings/yarn.mdx Use this command to install the latest stable release of the lavalink-client package from the npm registry using Yarn. ```bash yarn install lavalink-client ``` -------------------------------- ### Create and Play Music Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/player.md Creates a new player, connects to a voice channel, searches for a track, and starts playback. ```typescript const player = lavalink.createPlayer({ guildId: interaction.guildId, voiceChannelId: interaction.member.voice.channelId, textChannelId: interaction.channelId }); await player.connect(); const result = await player.search({ query: "track name" }, interaction.user); if (result.tracks.length > 0) { player.queue.add(result.tracks[0]); await player.play(); } ``` -------------------------------- ### Install Development Version with Yarn Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/installings/yarn.mdx Install the development version of lavalink-client directly from its GitHub repository using Yarn. This is useful for testing the latest unreleased features. ```bash yarn install tomato6966/lavalink-client ``` -------------------------------- ### Development Setup with Debugging Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/configuration.md Configuration for development environments with debugging enabled. This includes options for no-audio debugging and player destruction logging. ```typescript new LavalinkManager({ nodes: [...], sendToShard: ..., client: { id: botId }, advancedOptions: { enableDebugEvents: true, debugOptions: { noAudio: true, playerDestroy: { debugLog: true } } } }); ``` -------------------------------- ### play() Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/player.md Starts playback of the next track in the queue, or a specific track. Supports options for position, volume, and filters. ```APIDOC ## play() ### Description Starts playback of the next track in the queue, or a specific track. ### Method `async play(options?: PlayOptions): Promise` ### Parameters #### Path Parameters - **options** (`PlayOptions`) - Optional - Play options (position, volume, filters, etc.). ### Returns `Promise` — the player instance ### Example ```typescript await player.play(); // With specific position and volume await player.play({ position: 5000, volume: 80 }); ``` ``` -------------------------------- ### Install pnpm Stable Version Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/installings/pnpm.mdx Use this command to install the latest stable version of the lavalink-client package using pnpm. ```bash pnpm install lavalink-client ``` -------------------------------- ### Enable Node Resuming Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/extra/version-log.mdx Example of how to enable session resuming for a node with a specified timeout. ```javascript await player.node.updateSession(true, 360_000); ``` -------------------------------- ### NodeLink Get YouTube Configuration Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/extra/version-log.mdx Get the current YouTube configuration. Optionally validate the configuration. ```javascript node.getYoutubeConfig(validate?) ``` -------------------------------- ### Create Player and Play Music Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/lavalink-manager.md Creates a new player instance for a guild, connects it to a voice channel, searches for a track, and starts playback. Handles cases where no tracks are found. ```typescript const player = lavalink.createPlayer({ guildId: interaction.guildId, voiceChannelId: interaction.member.voice.channelId, textChannelId: interaction.channelId }); await player.connect(); const result = await player.search({ query: "Never Gonna Give You Up" }, interaction.user); if (result.tracks.length > 0) { player.queue.add(result.tracks[0]); await player.play(); } ``` -------------------------------- ### Monitor Node Health Example Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/node.md Shows how to fetch node statistics and log CPU load, memory usage, and active players. Includes a warning for high CPU load. ```typescript const stats = await node.getStats(); const cpuLoad = (stats.cpu.lavalink * 100).toFixed(1); const memUsed = (stats.memory.used / 1024 / 1024 / 1024).toFixed(2); console.log(`CPU Load: ${cpuLoad}%`); console.log(`Memory: ${memUsed}GB`); console.log(`Active Players: ${stats.playingPlayers}`); if (stats.cpu.lavalink > 0.8) { console.warn("High CPU load detected"); } ``` -------------------------------- ### Persistent Queue Lavalink Manager Setup Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/configuration.md Configuration for a persistent queue using Redis. This setup allows the queue to survive restarts by storing tracks in Redis. ```typescript new LavalinkManager({ nodes: [...], sendToShard: ..., client: { id: botId }, queueOptions: { maxPreviousTracks: 100, queueStore: new RedisQueueStore() } }); ``` -------------------------------- ### Listen to Track Start and Queue End Events Source: https://github.com/tomato6966/lavalink-client/blob/main/README.md Listen to 'trackStart' to announce the currently playing song and 'queueEnd' to notify when the queue is finished and then destroy the player. ```javascript client.lavalink.on("trackStart", (player, track) => { const channel = client.channels.cache.get(player.textChannelId); if (channel) channel.send(`Now playing: ${track.info.title}`); }); client.lavalink.on("queueEnd", (player) => { const channel = client.channels.cache.get(player.textChannelId); if (channel) channel.send("The queue has finished. Add more songs!"); player.destroy(); }); ``` -------------------------------- ### Get SponsorBlock Configuration Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/player.md Retrieves the current SponsorBlock filtering configuration for the player. ```typescript const config = await player.getSponsorBlock(); console.log(config); ``` -------------------------------- ### Handle Queue Empty Start Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/events.md Emitted when the queue becomes empty and the empty-queue timeout begins. Logs the remaining time until destruction. ```typescript lavalink.on("playerQueueEmptyStart", (player, timeoutMs) => { console.log(`Queue empty, destroying in ${timeoutMs}ms`); }); ``` -------------------------------- ### SponsorBlock Plugin Node Functions Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/extra/version-log.mdx Provides examples of using node functions to interact with the SponsorBlock plugin. ```javascript deleteSponsorBlock(player:Player) setSponsorBlock(player:Player, segments: ["sponsor", ...]) getSponsorBlock(player:Player) ``` -------------------------------- ### High-Performance Lavalink Manager Setup Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/configuration.md Optimized configuration for high performance. Features include applying volume as a filter to reduce CPU load and faster position updates. ```typescript new LavalinkManager({ nodes: [...], sendToShard: ..., client: { id: botId }, playerOptions: { applyVolumeAsFilter: true, // Reduce CPU load clientBasedPositionUpdateInterval: 200, onDisconnect: { destroyPlayer: true } }, autoSkip: true, autoMove: true }); ``` -------------------------------- ### Minimal Lavalink Manager Setup Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/configuration.md A basic configuration for the LavalinkManager. Ensure you provide at least one node, a sendToShard function, and a client ID. ```typescript new LavalinkManager({ nodes: [{ host: "localhost", port: 2333, authorization: "pass" }], sendToShard: (gid, p) => shard.send(p), client: { id: botId } }); ``` -------------------------------- ### Listen to Track Start Event Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/README.md Logs a message when a new track begins playing. This listener should be registered after the LavalinkManager is initialized. ```typescript lavalink.on("trackStart", (player, track) => { console.log(`Now playing: ${track.info.title}`); }); ``` -------------------------------- ### Listen for Track Start Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/events.md Emitted when a track begins playing. Use this to announce the currently playing track in a text channel. ```typescript lavalink.on("trackStart", (player, track, payload) => { console.log(`Now playing: ${track.info.title}`); }); ``` ```typescript lavalink.on("trackStart", (player, track) => { const channel = client.channels.cache.get(player.textChannelId); if (channel) { channel.send(`🎵 Now playing: **${track.info.title}** by ${track.info.author}`); } }); ``` -------------------------------- ### Handle MixStartedEvent Source: https://github.com/tomato6966/lavalink-client/blob/main/README.md Log details when a player mix starts. This includes guild ID, mix ID, volume, and track information. ```javascript case "MixStartedEvent": { const { guildId, mixId, volume, track } = payload.player; console.log( `Player mix started in guildId: ${guildId}, mixId: ${mixId}, volume: ${volume}, track: `, track, ); } break; ``` -------------------------------- ### Play Track Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/player.md Starts playback of the next track in the queue. Supports specifying playback options like position and volume. ```typescript await player.play(); // With specific position and volume await player.play({ position: 5000, volume: 80 }); ``` -------------------------------- ### Custom Queue Storage Implementation Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/configuration.md Provides an example of a custom queue storage manager using Redis. This allows for persistent or distributed queue management by implementing the QueueStoreManager interface. ```typescript class MyQueueStore implements QueueStoreManager { async get(guildId: string): Promise { return await redis.get(`queue:${guildId}`); } async set(guildId: string, data: string): Promise { await redis.set(`queue:${guildId}`, data, "EX", 86400); } async delete(guildId: string): Promise { await redis.del(`queue:${guildId}`); } stringify(data: Partial): string { return JSON.stringify(data); } parse(data: string): Partial { return JSON.parse(data); } } const lavalink = new LavalinkManager({ // ... queueOptions: { queueStore: new MyQueueStore() } }); ``` -------------------------------- ### Syncing with Custom Storage Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/queue.md The Queue can be synced with a custom QueueStore for distributed queue management. Example shows integration with Redis. ```APIDOC ## Syncing with Custom Storage ### Description The Queue can be synced with a custom QueueStore for distributed queue management. ### Example ```typescript // Example with Redis store class RedisQueueStore implements QueueStoreManager { async get(guildId: string): Promise { return await redis.get(`queue_${guildId}`); } async set(guildId: string, data: string): Promise { await redis.set(`queue_${guildId}`, data); } async delete(guildId: string): Promise { await redis.del(`queue_${guildId}`); } stringify(data: Partial): string { return JSON.stringify(data); } parse(data: string): Partial { return JSON.parse(data); } } const lavalink = new LavalinkManager({ // ... queueOptions: { maxPreviousTracks: 25, queueStore: new RedisQueueStore() } }); ``` ``` -------------------------------- ### Search and Filter the Queue Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/queue.md Provides examples for searching for a specific track using `find()`, filtering tracks by author using `filter()`, and sorting the queue by duration. ```APIDOC ## Search and Filter the Queue ### Description Search and Filter the Queue ### Example ```typescript // Find a specific track const found = player.queue.find((t) => t.info.title === "song name"); // Remove all tracks by an artist player.queue.filter((t) => !t.info.author.includes("unwanted artist")); // Sort by duration player.queue.sort((a, b) => a.info.duration - b.info.duration); ``` ``` -------------------------------- ### Handle Track Start and End Events Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/lavalink-manager.md Listens for 'trackStart' to announce the currently playing song and 'trackEnd' to log when a track finishes. Destroys the player when the queue is empty. ```typescript lavalink.on("trackStart", (player, track) => { const channel = client.channels.cache.get(player.textChannelId); if (channel) channel.send(`Now playing: **${track.info.title}**`); }); lavalink.on("trackEnd", (player, track) => { console.log(`Track ended: ${track.info.title}`); }); lavalink.on("queueEnd", (player) => { player.destroy(); }); ``` -------------------------------- ### Create or Get Player Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/lavalink-manager.md Create a new player for a guild or retrieve the existing one if it already exists. Connects the player to the specified voice channel. ```typescript const player = lavalink.createPlayer({ guildId: interaction.guildId, voiceChannelId: interaction.member.voice.channelId, textChannelId: interaction.channelId, volume: 100, selfDeaf: true }); await player.connect(); ``` -------------------------------- ### Implement Custom Queue Watcher for Gapless Playback Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/configuration.mdx Create a custom queue watcher to monitor changes in the queue and trigger actions like updating gapless playback settings. This example logs queue changes and calls `updateNextTrackGapLess` for NodeLink users. ```typescript // Custom Queue Watcher Functions (with couple special features..) function updateNextTrackGapLess(guildId: string) { // this function is for nodelink users relevant for gapless audio. const player = this.client.lavalink.getPlayer(guildId); if (!player || !player.node.isNodeLink()) return; return player.node.removeNextTrackGapLess(player); } class myCustomWatcher implements QueueChangesWatcher { constructor(client) { this.client = client; } shuffled(guildId, oldStoredQueue, newStoredQueue) { console.log(`${this.client.guilds.cache.get(guildId)?.name || guildId}: Queue got shuffled`); updateNextTrackGapLess(guildId); } tracksAdd(guildId, tracks, position, oldStoredQueue, newStoredQueue) { console.log( `${this.client.guilds.cache.get(guildId)?.name || guildId}: ${tracks.length} Tracks got added into the Queue at position #${position}`, ); updateNextTrackGapLess(guildId); } tracksRemoved(guildId, tracks, position, oldStoredQueue, newStoredQueue) { console.log( `${this.client.guilds.cache.get(guildId)?.name || guildId}: ${tracks.length} Tracks got removed from the Queue at position #${position}`, ); updateNextTrackGapLess(guildId); } } ``` -------------------------------- ### Configuration Options Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/README.md Reference for all configuration options available for the LavalinkManager. Covers essential setup, node configuration, player and queue settings, link filtering, and advanced debugging. ```APIDOC ## Configuration ### Description Complete reference for all LavalinkManager configuration options. ### Topics - Required options (nodes, sendToShard) - Node configuration details - Player options (volume, autoplay, filters) - Queue options (e.g., custom storage) - Link filtering (whitelist/blacklist) - Advanced debugging options - Custom queue storage implementations - Custom player class definitions ### Example Configurations - Minimal setup - High-performance setup - Persistent queue setup - Development setup with debugging enabled ``` -------------------------------- ### Create LavalinkManager with NodeLink Source: https://github.com/tomato6966/lavalink-client/blob/main/README.md Configure the LavalinkManager to use NodeLink by setting the nodeType to NodeType.NodeLink in the nodes array. This example shows a basic setup. ```typescript client.lavalink = new LavalinkManager({ nodes: [ { host: "localhost", nodeType: NodeType.NodeLink, // provide nodeType "nodelink" to it. }, ], }); ``` -------------------------------- ### Sync Queue with Custom Redis Store Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/queue.md Demonstrates how to implement a custom QueueStoreManager using Redis for distributed queue management. This involves defining methods for getting, setting, deleting, parsing, and stringifying queue data. ```typescript // Example with Redis store class RedisQueueStore implements QueueStoreManager { async get(guildId: string): Promise { return await redis.get(`queue_${guildId}`); } async set(guildId: string, data: string): Promise { await redis.set(`queue_${guildId}`, data); } async delete(guildId: string): Promise { await redis.del(`queue_${guildId}`); } stringify(data: Partial): string { return JSON.stringify(data); } parse(data: string): Partial { return JSON.parse(data); } } const lavalink = new LavalinkManager({ // ... queueOptions: { maxPreviousTracks: 25, queueStore: new RedisQueueStore() } }); ``` -------------------------------- ### Correct LavalinkManager Initialization with nodes Array Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/errors.md The `nodes` option for LavalinkManager must be an array of node configurations. This example shows the correct way to provide node details. ```typescript // ✅ Correct new LavalinkManager({ nodes: [{ host: "localhost", port: 2333 }] }); ``` -------------------------------- ### Implement Custom Queue Changes Watcher Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/queue.md Provides an example of a custom QueueChangesWatcher implementation to track additions, removals, and shuffles of tracks in the queue. This allows for custom logging or event handling. ```typescript class MyQueueWatcher implements QueueChangesWatcher { tracksAdd(guildId: string, tracks: Track[], position: number): void { console.log(`Added ${tracks.length} tracks at position ${position}`); } tracksRemoved(guildId: string, tracks: Track[], position: number): void { console.log(`Removed ${tracks.length} tracks`); } shuffled(guildId: string): void { console.log("Queue shuffled"); } } ``` -------------------------------- ### init() Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/lavalink-manager.md Initializes the manager and connects all Lavalink nodes. This method must be called after the bot client is ready. ```APIDOC ## init(clientData: BotClientOptions) ### Description Initializes the manager and connects all Lavalink nodes. This method must be called after the bot client is ready. ### Method `async` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **clientData** (`BotClientOptions`) - Optional - Bot client info (id, username). ### Returns * `Promise` - The manager instance. ### Throws * `Error` - If nodes fail to connect. ### Example ```typescript client.on("ready", () => { lavalink.init({ id: client.user.id, username: client.user.username }); }); ``` ``` -------------------------------- ### Initialize LavalinkManager with Basic Options Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/configuration.md Demonstrates the required options for initializing LavalinkManager: an array of node configurations and a function to send voice updates to Discord shards. ```typescript const manager = new LavalinkManager({ // Required: Array of node configurations nodes: [ { host: "localhost", port: 2333, authorization: "youshallnotpass", id: "main" } ], // Required: Function to send voice updates to Discord sendToShard: (guildId, payload) => { const guild = client.guilds.cache.get(guildId); if (guild) guild.shard.send(payload); } }); ``` -------------------------------- ### Sample Lavalink Configuration Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/setup-lavalink.mdx This snippet shows a sample application.yaml configuration for Lavalink. It enables various external service integrations and configures logging settings. ```yaml pornhub: true # should be self-explanatory reddit: true # should be self-explanatory ocremix: true # www.ocremix.org tiktok: true # tiktok.com mixcloud: true # mixcloud.com soundgasm: true # soundgasm.net metrics: prometheus: enabled: false endpoint: /metrics sentry: dsn: "" environment: "" logging: file: max-history: 5 max-size: 10MB path: ./logs/ level: root: DEBUG lavalink: DEBUG request: enabled: true includeClientInfo: true includeHeaders: true includeQueryString: true includePayload: true maxPayloadLength: 10000 logback: rollingpolicy: max-file-size: 10MB max-history: 5 ``` -------------------------------- ### NodeLink Get Connection Metrics Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/extra/version-log.mdx Retrieve connection metrics for the node. ```javascript node.getConnectionMetrics() ``` -------------------------------- ### Queue.remove() Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/queue.md Removes a specified number of tracks from the queue starting at a given index. ```APIDOC ## Queue.remove() ### Description Removes tracks from the queue by index. ### Method `remove(index: number, amount?: number): (Track | UnresolvedTrack)[]` ### Parameters #### Path Parameters - **index** (number) - Required - Starting index. - **amount** (number) - Optional - Default: 1 - Number of tracks to remove. ### Returns Array of removed tracks ### Example ```typescript const removed = player.queue.remove(0); // Remove first track const removed = player.queue.remove(2, 3); // Remove 3 tracks starting at index 2 ``` ``` -------------------------------- ### PlayerOptions Interface Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/types.md Configuration options for creating a new player instance. Includes essential IDs and optional settings like volume and node. ```typescript interface PlayerOptions { guildId: string; voiceChannelId: string; textChannelId?: string; volume?: number; vcRegion?: string; selfDeaf?: boolean; selfMute?: boolean; node?: LavalinkNode | string; instaUpdateFiltersFix?: boolean; applyVolumeAsFilter?: boolean; customData?: anyObject; } ``` -------------------------------- ### Get Typed Lavalink Node Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/extra/version-log.mdx Retrieve a specific Lavalink node with typed return. ```javascript Manager.lavalinkManager.getNode() ``` -------------------------------- ### Create and Connect Player Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/player.md Instantiates a new Player and connects it to a voice channel. Ensure the guildId and voiceChannelId are correctly set. ```typescript const player = lavalink.createPlayer({ guildId: "123456789", voiceChannelId: "987654321" }); await player.connect(); ``` -------------------------------- ### length Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/queue.md Gets the number of tracks currently in the queue, excluding the currently playing track. ```APIDOC ## length ### Description Number of queued tracks (excludes current). ### Method `public get length(): number` ``` -------------------------------- ### Get Connected Nodes Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/node-manager.md Retrieves an array containing all Lavalink nodes that are currently connected. ```typescript const connected = nodeManager.getConnectedNodes(); console.log(`${connected.length} nodes connected`); ``` -------------------------------- ### setEQPreset() Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/filter-manager.md Applies a predefined equalizer preset from a list of available options. ```APIDOC ## setEQPreset(preset: keyof typeof EQList) ### Description Applies a built-in equalizer preset. ### Method `public async setEQPreset(preset: keyof typeof EQList): Promise` ### Parameters #### Path Parameters - **preset** (`string`) - Required - Preset name (e.g., "BassboostHigh", "Pop", "Rock"). ### Returns `Promise` ### Example ```typescript const { EQList } = require("lavalink-client"); await player.filterManager.setEQPreset("BassboostHigh"); await player.filterManager.setEQPreset("Rock"); await player.filterManager.setEQPreset("Electronic"); ``` ``` -------------------------------- ### Get Valid SponsorBlock Categories Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/utils-and-helpers.md Retrieves an array of valid category names for SponsorBlock segments. ```typescript import { validSponsorBlocks } from "lavalink-client"; // Returns array of valid categories: // ["sponsor", "selfpromo", "interaction", "intro", "outro", "preview", "music_offtopic", "filler"] ``` -------------------------------- ### Shuffle, Move, and Reverse Queue Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/queue.md Demonstrates how to shuffle all tracks in the queue, move a specific track to the front, and reverse the entire queue. ```typescript await player.queue.shuffle(); // Move track to front player.queue.moveTrack(3, 0); // Reverse the queue player.queue.reverse(); ``` -------------------------------- ### Listen for Track Stuck Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/events.md Emitted when a track gets stuck for a prolonged period. Log the threshold time. ```typescript lavalink.on("trackStuck", (player, track, payload) => { console.log(`Track stuck after ${payload.thresholdMs}ms`); }); ``` -------------------------------- ### connect() Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/player.md Connects the player to the configured voice channel. Throws a RangeError if no voice channel ID is set. ```APIDOC ## connect() ### Description Connects the player to the configured voice channel. ### Method `async connect(): Promise` ### Returns `Promise` — the player instance ### Throws `RangeError` if no voice channel ID is set ### Example ```typescript const player = lavalink.createPlayer({ guildId: "123456789", voiceChannelId: "987654321" }); await player.connect(); ``` ``` -------------------------------- ### NodeLink Get YouTube Chapters Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/extra/version-log.mdx Retrieve chapters for YouTube videos using NodeLink. Optionally specify a track. ```javascript node.getChapters(player, track?) ``` -------------------------------- ### Getting the Next Autoplay Track Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/extra/autoplay-system.mdx Retrieve the next track from the autoplay queue. This is used when the current track finishes. ```typescript import { AutoplayManager } from "@lavalink/client"; const autoplayManager = new AutoplayManager(); // Add some tracks first // autoplayManager.add(...); const nextTrack = autoplayManager.get(); ``` -------------------------------- ### Get Lyrics for a Track Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/player.md Fetches lyrics for a specific track. Optionally skip the track's source plugin. ```typescript const lyrics = await player.getLyrics(player.queue.current); console.log(lyrics.lines); ``` -------------------------------- ### getChapters Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/node.md Retrieves chapter information from a YouTube video. ```APIDOC ## getChapters() ### Description Retrieves chapters from a YouTube video. ### Method `public async getChapters(player: Player, track?: Track): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript // Example usage: // const chapters = await node.getChapters(player, track); // const currentTrackChapters = await node.getChapters(player); ``` ### Response #### Success Response - **Chapter[]** - An array of Chapter objects. #### Response Example ```json // Example response structure: // [ // { "title": "Introduction", "startTime": 0, "endTime": 60000 }, // { "title": "Main Content", "startTime": 60000, "endTime": 180000 } // ] ``` ``` -------------------------------- ### Initialize LavalinkManager Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/lavalink-manager.md Initialize the LavalinkManager and connect all nodes after the bot is ready. Pass bot client information if available. ```typescript client.on("ready", () => { lavalink.init({ id: client.user.id, username: client.user.username }); }); ``` -------------------------------- ### Sample Lavalink Configuration Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/home/setup-lavalink.mdx This configuration enables multiple plugins for additional sources, filters, and lyrics. It includes settings for server port, Lavalink password, buffer durations, and plugin dependencies. ```yaml server: port: 2333 address: 0.0.0.0 lavalink: server: sources: youtube: false # Using Youtube nativly on lavalink is deprecated, disable it and use https://github.com/lavalink-devs/youtube-source instead. password: "youshallnotpass" bufferDurationMs: 225 frameBufferDurationMs: 5000 youtubePlaylistLoadLimit: 3 opusEncodingQuality: 5 resamplingQuality: MEDIUM trackStuckThresholdMs: 5000 playerUpdateInterval: 3 useSeekGhosting: true youtubeSearchEnabled: true soundcloudSearchEnabled: true gc-warnings: true lavalink: plugins: - dependency: "dev.lavalink.youtube:youtube-plugin:1.18.0" # https://github.com/lavalink-devs/youtube-source - dependency: "com.github.topi314.lavasrc:lavasrc-plugin:4.8.1" # https://github.com/topi314/LavaSrc - dependency: "com.github.topi314.lavasearch:lavasearch-plugin:1.0.0" # https://github.com/topi314/LavaSearch - dependency: "com.dunctebot:skybot-lavalink-plugin:1.7.0" # https://github.com/DuncteBot/skybot-lavalink-plugin - dependency: "com.github.devoxin:lavadspx-plugin:0.0.5" # https://github.com/devoxin/LavaDSPX-Plugin repository: "https://jitpack.io" - dependency: "com.github.topi314.lavalyrics:lavalyrics-plugin:1.1.0" # https://github.com/topi314/LavaLyrics - dependency: "me.duncte123:java-lyrics-plugin:1.6.6" # https://github.com/DuncteBot/java-timed-lyrics plugins: lyrics: countryCode: de geniusApiKey: "" lavalyrics: sources: - genius - spotify - youtube - deezer - yandexMusic youtube: enabled: true # YouTube's cipher changes are becoming more frequent and complex, making it harder to keep up. # To simplify signature deciphering, you can use a remote cipher server like yt-cipher, a lightweight Deno server with a REST API. More details are available at https://github.com/kikkia/yt-cipher remoteCipher: userAgent: "your_service_name" url: "http://localhost:8001" # The base URL of your remote cipher server. password: "your_secret_password" # The password to authenticate with your remote cipher server. oauth: enabled: false # refreshToken: "Insert your refresh token here" # For more details, please refer to https://github.com/lavalink-devs/youtube-source?tab=readme-ov-file#using-oauth-tokens allowSearch: true allowDirectVideoIds: true allowDirectPlaylistIds: true # For more details about client setup, refer to https://github.com/lavalink-devs/youtube-source?tab=readme-ov-file#available-clients clients: - "ANDROID_MUSIC" - "MUSIC" - "WEB" - "WEBEMBEDDED" - "TVHTML5_SIMPLY" ANDROID_MUSIC: videoLoading: true searching: true playback: true MUSIC: searching: true playback: false WEB: videoLoading: true searching: true playback: true WEBEMBEDDED: playback: true TVHTML5_SIMPLY: playback: true lavasrc: providers: - 'ytsearch:"%ISRC%"' - "dzisrc:%ISRC%" - "ytsearch:%QUERY%" - "dzsearch:%QUERY%" - "jssearch:%QUERY%" - "pdsearch:%QUERY%" - "scsearch:%QUERY%" - "tdsearch:%QUERY%" sources: spotify: true # Enable Spotify source applemusic: true # Enable Apple Music source deezer: true # Enable Deezer source jiosaavn: true # Enabled JioSaavn source pandora: true # Enable Pandora source yandexmusic: true # Enable Yandex Music source flowerytts: true # Enable Flowery TTS source youtube: true # Enable YouTube search source (https://github.com/topi314/LavaSearch) tidal: true # Enable Tidal source vkmusic: true # Enable Vk Music source qobuz: true # Enabled qobuz source ytdlp: true # Enable yt-dlp source lyrics-sources: spotify: true # Enable Spotify lyrics source deezer: true # Enable Deezer lyrics source youtube: true # Enable YouTube lyrics source yandexmusic: true # Enable Yandex Music lyrics source vkmusic: true # Enable Vk Music lyrics source lrcLib: true # Enable LRC Library lyrics source (https://lrclib.net) spotify: # clientId & clientSecret are required for using spsearch # clientId: "" # clientSecret: "" ``` -------------------------------- ### NodeLink Get YouTube Lyrics Source: https://github.com/tomato6966/lavalink-client/blob/main/docs/src/content/docs/extra/version-log.mdx Retrieve lyrics for YouTube videos using NodeLink. Optionally specify a track and language. ```javascript node.nodeLinkLyrics(player, track?, language?) ``` -------------------------------- ### Get a Specific Node Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/node-manager.md Retrieves a specific Lavalink node by its ID. If no ID is provided, a random connected node is returned. ```typescript const node = nodeManager.getNode("main-node"); if (!node) { console.log("Node not found"); } ``` -------------------------------- ### Handle Search Results Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/utils-and-helpers.md Demonstrates how to handle different `loadType` values from a search result. Use this to add tracks or playlists to the player queue. ```typescript const result = await player.search({ query: "my song" }, user); if (result.loadType === "TRACK_LOADED") { // Single track found player.queue.add(result.tracks[0]); } if (result.loadType === "PLAYLIST_LOADED") { // Playlist found player.queue.add(result.tracks); console.log(`Added ${result.data.selectedTrack} to playlist`); } if (result.loadType === "SEARCH_RESULT") { // Multiple tracks found console.log(`Found ${result.tracks.length} results`); } if (result.loadType === "NO_MATCHES") { console.log("No tracks found"); } if (result.loadType === "LOAD_FAILED") { console.error("Search failed:", result.data); } ``` -------------------------------- ### createPlayer() Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/lavalink-manager.md Creates a new player instance for a given guild or returns the existing one if it already exists. ```APIDOC ## createPlayer(options: PlayerOptions) ### Description Creates a new player instance for a given guild or returns the existing one if it already exists. ### Method N/A (SDK Method) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **options** (`PlayerOptions`) - Required - Player configuration. ### Returns * `CustomPlayerT` - The new or existing player instance. ### Example ```typescript const player = lavalink.createPlayer({ guildId: interaction.guildId, voiceChannelId: interaction.member.voice.channelId, textChannelId: interaction.channelId, volume: 100, selfDeaf: true }); await player.connect(); ``` ``` -------------------------------- ### Remove Tracks from Queue by Index Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/queue.md The remove method allows you to remove a specified number of tracks starting from a given index. ```typescript const removed = player.queue.remove(0); // Remove first track const removed = player.queue.remove(2, 3); // Remove 3 tracks starting at index 2 ``` -------------------------------- ### Initialize Lavalink Manager Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/lavalink-manager.md Initializes the LavalinkManager with node configurations and connects it to the Discord client. Ensure the 'ready' event is handled before initialization. ```typescript const lavalink = new LavalinkManager({ nodes: [{ authorization: "pass", host: "localhost", port: 2333 }], sendToShard: (guildId, payload) => client.guilds.cache.get(guildId)?.shard?.send(payload), client: { id: client.user.id } }); client.on("ready", () => { lavalink.init({ id: client.user.id }); }); client.on("raw", (d) => lavalink.sendRawData(d)); ``` -------------------------------- ### Handle NodeLink Features Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/node.md Demonstrates how to use NodeLink specific features like adding a mixer layer, retrieving chapters, and fetching lyrics. ```typescript if (node.isNodeLink()) { // Add mixer layer const mixResult = await node.addMixerLayer( player, backgroundTrack, 0.3 ); // Get chapters const chapters = await node.getChapters(player); // Get lyrics const lyrics = await node.nodeLinkLyrics(player); } ``` -------------------------------- ### Get Track Chapters Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/node.md Retrieves chapter information for a YouTube video. Can specify a track or use the player's current track. ```typescript public async getChapters( player: Player, track?: Track ): Promise ``` -------------------------------- ### resume() Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/player.md Resumes playback from a paused state. Throws an error if not paused. ```APIDOC ## resume() ### Description Resumes playback from a paused state. ### Method `async resume(): Promise` ### Returns `Promise` — the player instance ### Throws `Error` if not paused ### Example ```typescript await player.resume(); ``` ``` -------------------------------- ### Get YouTube OAuth Token Source: https://github.com/tomato6966/lavalink-client/blob/main/_autodocs/node.md Exchanges a refresh token for an access token for YouTube. Requires a valid YouTube refresh token. ```typescript public async getYoutubeOAUTH(refreshToken: string): Promise ```