Star ✨ on GitHub

Manager

API reference for the Manager class in Moonlink.js

Manager Class

The Manager class is the main entry point for Moonlink.js. It manages connections to Lavalink nodes, creates and manages players, and handles events. The Manager class extends EventEmitter to provide a robust event system.See also:

Configuration

Configuration Options

When creating a manager, you can specify several options:

interface IConfigManager {
  nodes: INode[];
  sendPayload: (guildId: string, payload: any) => void;
  options: IOptionsManager;
}

interface INode {
  host: string;
  port: number;
  password: string;
  secure?: boolean;
  identifier?: string;
  retryAmount?: number;
  retryDelay?: number;
  regions?: string[];
  sessionId?: string;
  pathVersion?: string;
}

interface IOptionsManager {
  clientName?: string;
  clientId?: string;
  defaultPlatformSearch?: string;
  sortTypeNode?: TSortTypeNode;
  plugins?: Plugin[];
  noReplace?: boolean;
  NodeLinkFeatures?: boolean;
  logFile?: { path: string; log: boolean };
  movePlayersOnReconnect?: boolean;
  sortPlayersByRegion?: boolean;
  autoResume?: boolean;
  resume?: boolean;
  partialTrack?: TPartialTrackProperties[];
  disableDatabase?: boolean;
  disableNativeSources?: boolean;
  blacklisteSources?: string[];
  spotify?: {
    limitLoadPlaylist?: number;
    limitLoadAlbum?: number;
    limitLoadArtist?: number;
    limitLoadSearch?: number;
    limitLoadRecommendations?: number;
  };
  deezer?: {
    maxSearchResults?: number;
    maxAlbumTracks?: number;
    maxPlaylistTracks?: number;
    maxArtistTracks?: number;
  };
}

Properties

Available Properties


PropertyTypeDescriptionDefault
initializebooleanWhether the manager has been initializedfalse
optionsIOptionsManagerManager configuration optionsCreated
sendPayloadFunctionFunction for sending voice state updatesRequired
nodesNodeManagerNode manager instanceCreated
playersPlayerManagerPlayer manager instanceCreated
versionstringCurrent version of Moonlink.jsPackage version
databaseDatabaseDatabase instanceCreated
sourcesSourceManagerSource manager instanceCreated
pluginManagerPluginManagerPlugin manager instanceCreated

Methods

init

initmethod

Initialize Manager

Initializes the manager and connects to all configured nodes. This method sets up the database, initializes nodes, and prepares the manager for handling voice connections.

Parameters
clientIdrequiredstring
The Discord client ID

Returns & Example

Returnsvoid

client.once('ready', () => {
  manager.init(client.user.id);
});

searchmethod

Search Tracks

Searches for tracks using the configured nodes or native sources (like Spotify). The search will be performed on the best available node or a specific node if provided. Supports fallback sources.

Parameters
optionsrequiredObject
Search options
options.queryrequiredstring
Search query
options.sourcestring
Platform to search on (youtube, soundcloud, etc.)
options.nodestring
Specific node to use
options.requesterunknown
Track requester info
options.fallbackSourcesTSearchSources[]
Optional: An array of fallback sources to try if the initial search fails.

Returns & Example

ReturnsPromise<SearchResult> — Search results containing tracks and playlist info

const results = await manager.search({
  query: 'Never Gonna Give You Up',
  source: 'youtube',
  fallbackSources: ['soundcloud', 'deezer']
});

lavaSearch

lavaSearchmethod

LavaSearch Tracks

Performs a search using the LavaSearch plugin, supporting multiple result types (tracks, albums, artists, playlists, text). Requires a NodeLink server with LavaSearch plugin.

Parameters
optionsrequiredObject
LavaSearch options
options.queryrequiredstring
Search query
options.sourcestring
Platform to search on (youtube, soundcloud, etc.)
options.nodestring
Specific node to use
options.requesterunknown
Track requester info
options.typesstring
Comma-separated string of result types to return (e.g., "track,album,artist"). Defaults to "track,album,artist,playlist,text".

Returns & Example

ReturnsPromise<SearchResult> — Search results containing various types of data.

const results = await manager.lavaSearch({
  query: 'Never Gonna Give You Up',
  source: 'youtube',
  types: 'track,artist'
});

if (results.tracks.length > 0) {
  console.log('Found tracks:', results.tracks.map(t => t.title));
}
if (results.artists && results.artists.length > 0) {
  console.log('Found artists:', results.artists.map(a => a.info.name));
}

getLyrics

getLyricsmethod

Get Lyrics

Fetches lyrics for a track using available lyrics plugins. Supports fetching by player's current track, encoded track, or video ID. Prioritizes timed lyrics.

Parameters
optionsrequiredObject
Lyrics options
options.playerPlayer
The player instance to get lyrics for its current track.
options.encodedTrackstring
Base64 encoded track string.
options.videoIdstring
YouTube video ID.
options.skipTrackSourceboolean
Whether to skip the track's original source when searching for lyrics.
options.provider'lavalyrics' | 'lyrics' | 'java-lyrics-plugin'
Specific lyrics provider to use.

Returns & Example

ReturnsPromise<ILavaLyricsObject | null> — Lyrics data or null if not found.

// Get lyrics for current playing track
const lyrics = await manager.getLyrics({ player: myPlayer });
if (lyrics) {
  console.log(`Lyrics for ${lyrics.track.title}:
${lyrics.text}`);
}

// Get lyrics by video ID
const youtubeLyrics = await manager.getLyrics({ videoId: 'dQw4w9WgXcQ' });

searchLyrics

searchLyricsmethod

Search Lyrics

Searches for lyrics based on a query using available lyrics plugins.

Parameters
optionsrequiredObject
Search options
options.queryrequiredstring
The search query (e.g., song title and artist).
options.provider'lavalyrics' | 'lyrics' | 'java-lyrics-plugin'
Specific lyrics provider to use.
options.nodestring
Specific node to use for the search.
options.sourcestring
Optional source to narrow down the search (e.g., "youtube").

Returns & Example

ReturnsPromise<any[] | null> — An array of search results or null if no results found.

const searchResults = await manager.searchLyrics({ query: 'Never Gonna Give You Up Rick Astley' });
if (searchResults && searchResults.length > 0) {
  console.log('Found lyrics search results:', searchResults);
}

subscribeLyrics

subscribeLyricsmethod

Subscribe to Live Lyrics

Subscribes to live lyrics updates for a specific guild. The provided callback will be invoked with each new lyrics line.

Parameters
guildIdrequiredstring
The ID of the guild.
callbackrequired(line: ILavaLyricsLine) => void
The callback function to receive lyrics line updates.
skipTrackSourceboolean
Whether to skip the track's original source when searching for lyrics.
provider'lavalyrics' | 'lyrics' | 'java-lyrics-plugin'
Specific lyrics provider to use.

Returns & Example

ReturnsPromise<void>

manager.subscribeLyrics('123456789', (line) => {
  console.log(`Live Lyric: ${line.line} (at ${line.timestamp}ms)`);
});

unsubscribeLyrics

unsubscribeLyricsmethod

Unsubscribe from Live Lyrics

Unsubscribes from live lyrics updates for a specific guild.

Parameters
guildIdrequiredstring
The ID of the guild.
provider'lavalyrics' | 'lyrics' | 'java-lyrics-plugin'
Specific lyrics provider to unsubscribe from.

Returns & Example

ReturnsPromise<void>

manager.unsubscribeLyrics('123456789');
console.log('Unsubscribed from live lyrics.');

createPlayer

createPlayermethod

Create Player

Creates a new player instance for a guild. The player will be automatically managed by the PlayerManager.
Parameters
configrequiredIPlayerConfig
Player configuration. See Player Configuration

Returns & Example

ReturnsPlayer — The created player instance

const player = manager.createPlayer({
  guildId: '123456789',
  voiceChannelId: '123456789',
  textChannelId: '123456789'
});

getPlayer

getPlayermethod

Get Player

Gets an existing player instance for a guild.
Parameters
guildIdrequiredstring
Guild ID

Returns & Example

ReturnsPlayer — The player instance if it exists

const player = manager.getPlayer('123456789');

hasPlayer

hasPlayermethod

Has Player

Checks if a player exists for a guild.
Parameters
guildIdrequiredstring
Guild ID

Returns & Example

Returnsboolean — Whether the player exists

const exists = manager.hasPlayer('123456789');

deletePlayer

deletePlayermethod

Delete Player

Deletes a player instance and cleans up its resources.
Parameters
guildIdrequiredstring
Guild ID

Returns & Example

Returnsboolean — Whether the deletion was successful

manager.deletePlayer('123456789');

getAllPlayers

getAllPlayersmethod

Get All Players

Gets all active player instances from the cache.

Returns & Example

ReturnsMap<string, Player> — Map of all players

const players = manager.getAllPlayers();

Events

#title Available Events#description The Manager class extends EventEmitter and provides these event categories:

General Events

EventDescriptionParameters
autoLeavedEmitted when a player automatically leaves a voice channel.player: Player, track: Track
debugEmitted when debug information is available....args: any

Node Events

EventDescriptionParameters
nodeRawEmitted when a raw WebSocket message is received from a node.node: INode, payload: any
nodeCreateEmitted when a new node is created.node: INode
nodeReadyEmitted when a node is ready and connected.node: INode, stats: INodeStats
nodeConnectedEmitted when a node successfully connects.node: INode
nodeErrorEmitted when a node encounters an error.node: INode, error: Error
nodeReconnectEmitted when a node attempts to reconnect.node: INode
nodeDisconnectEmitted when a node disconnects.node: INode, code: number, reason: string
nodeDestroyEmitted when a node is destroyed.identifier: string
nodeAutoResumedEmitted when players are auto-resumed on a node.node: INode, players: Player[]
nodeStateChangeEmitted when a node's state changes.node: Node, oldState: NodeState, newState: NodeState

Player Events

EventDescriptionParameters
playerCreateEmitted when a new player is created.player: Player
playerUpdateEmitted when player state updates.player: Player, track: Track, payload: any
playerDestroyEmitted when a player is destroyed.player: Player
playerSwitchedNodeEmitted when a player switches to a different node.player: Player, oldNode: Node, newNode: Node
playerConnectingEmitted when a player attempts to connect to a voice channel.player: Player
playerReadyEmitted when a player is ready to play.player: Player
playerResumingEmitted when a player is attempting to resume playback.player: Player
playerResumedEmitted when a player successfully resumes playback.player: Player
playerConnectedEmitted when a player connects to a voice channel.player: Player
playerDisconnectedEmitted when a player disconnects from a voice channel.player: Player
playerReconnectEmitted when a player attempts to reconnect.player: Player, reason?: string
playerMovedEmitted when a player moves voice channels.player: Player, oldChannel: string, newChannel: string
playerDestroyedEmitted when a player is destroyed.player: Player, reason?: string
playerTriggeredBackEmitted when a player goes back to the previous track.player: Player, track: Track
playerChapterSkippedEmitted when a player skips to a new chapter.player: Player, chapter: IChapter

Track Events

EventDescriptionParameters
trackStartEmitted when a track starts playing.player: Player, track: Track
trackEndEmitted when a track ends.player: Player, track: Track, type: TTrackEndType, payload?: any
trackStuckEmitted when a track gets stuck.player: Player, track: Track, threshold: number
trackExceptionEmitted when a track encounters an exception.player: Player, track: Track, exception: any
queueEndEmitted when the queue ends.player: Player, track?: any
trackBlacklistedEmitted when a track from a blacklisted source is encountered.player: Player, track: Track

Player State Events

EventDescriptionParameters
playerTriggeredPlayEmitted when a player starts playing.player: Player, track: Track
playerTriggeredPauseEmitted when playback is paused.player: Player
playerTriggeredResumeEmitted when playback is resumed.player: Player
playerTriggeredStopEmitted when playback is stopped.player: Player
playerTriggeredSkipEmitted when a track is skipped.player: Player, oldTrack: Record<string, any>, currentTrack: Track, postion: number
playerTriggeredSeekEmitted when a track is seeked.player: Player, position: number
playerTriggeredShuffleEmitted when the queue is shuffled.player: Player, oldQueue: Record<string, any>, currentQueue: Track[]
playerSpeakEmitted when the player speaks using TTS.player: Player, text: string, options?: ISpeakOptions

Settings Events

EventDescriptionParameters
playerChangedVolumeEmitted when the player's volume changes.player: Player, oldVolume: number, newVolume: number
playerChangedLoopEmitted when the player's loop mode changes.player: Player, oldLoop: TPlayerLoop, newLoop: TPlayerLoop, oldLoopCount?: number, newLoopCount?: number
playerAutoPlaySetEmitted when the player's auto-play setting changes.player: Player, autoPlay: boolean
playerAutoLeaveSetEmitted when the player's auto-leave setting changes.player: Player, autoLeave: boolean
playerTextChannelIdSetEmitted when the player's text channel ID changes.player: Player, oldChannel: string, newChannel: string
playerVoiceChannelIdSetEmitted when the player's voice channel ID changes.player: Player, oldChannel: string, newChannel: string
playerNodeSetEmitted when the player's node changes.player: Player, oldNode: string, newNode: string

Queue Events

EventDescriptionParameters
queueAddEmitted when tracks are added to the queue.`player: Player, tracks: Track
queueRemoveEmitted when tracks are removed from the queue.`player: Player, tracks: Track
queueMoveRangeEmitted when a range of tracks is moved within the queue.player: Player, tracks: Track[], fromIndex: number, toIndex: number
queueRemoveRangeEmitted when a range of tracks is removed from the queue.player: Player, tracks: Track[], startIndex: number, endIndex: number
queueDuplicateEmitted when tracks are duplicated in the queue.player: Player, tracks: Track[], index: number

Filter Events

EventDescriptionParameters
filtersUpdateEmitted when audio filters are updated.player: Player, filters: Filters

Source Events

EventDescriptionParameters
sourceAddEmitted when a source is added.source: ISource
sourceRemoveEmitted when a source is removed.source: string
sourceClearEmitted when all sources are cleared.void

SponsorBlock Events

EventDescriptionParameters
segmentsLoadedEmitted when SponsorBlock segments are loaded for a track.player: Player, segments: ISegment[]
segmentSkippedEmitted when a SponsorBlock segment is skipped.player: Player, segment: ISegment

Chapter Events

EventDescriptionParameters
chaptersLoadedEmitted when chapters are loaded for a track.player: Player, chapters: IChapter[]
chapterStartedEmitted when a new chapter starts playing.player: Player, chapter: IChapter

WebSocket Events

EventDescriptionParameters
socketClosedEmitted when the WebSocket connection is closed.player: Player, code: number, reason: string, byRemote: boolean
Example: ```js manager.on('trackStart', (player, track) => { console.log(Now playing: ${track.title}); });manager.on('nodeError', (node, error) => { console.error(Node ${node.identifier} had an error:, error); });
  ::