Star ✨ on GitHub

Player

API reference for the Player class in Moonlink.js

The Player class represents a music player for a specific guild. It handles voice connections, track playback, queue management, audio filters, and additional features like lyrics and listening analysis when using NodeLink.

Configuration

When creating a player, you can specify several options:

interface IPlayerConfig {
  guildId: string;
  voiceChannelId: string;
  textChannelId: string;
  node?: string;
  volume?: number;
  loop?: "off" | "track" | "queue";
  loopCount?: number;
  autoPlay?: boolean;
  autoLeave?: boolean;
}

Example:

const player = manager.createPlayer({
  guildId: '123456789012345678',
  voiceChannelId: '123456789012345678',
  textChannelId: '123456789012345678',
  volume: 80,
  loop: 'off',
  loopCount: 5,
  autoPlay: true,
  autoLeave: false
});

Properties

PropertyTypeDescriptionDefault
managerManagerThe Manager instance that created this playerRequired
guildIdstringThe ID of the guild this player belongs toRequired
voiceChannelIdstringThe ID of the voice channelRequired
textChannelIdstringThe ID of the text channelRequired
regionstringThe voice server regionDetected
voiceStateIVoiceStateVoice connection state{}
autoPlaybooleanWhether to auto-play next trackfalse
autoLeavebooleanWhether to auto-leave when emptyfalse
connectedbooleanWhether connected to voicefalse
playingbooleanWhether currently playingfalse
destroyedbooleanWhether the player is destroyedfalse
pausedbooleanWhether playback is pausedfalse
volumenumberCurrent volume level (0-1000)80
loopTPlayerLoopLoop mode ("off"/"track"/"queue")"off"
loopCountnumberNumber of times to loop the current track or queue. undefined if not set.undefined
currentTrackCurrently playing tracknull
previousTrack[]Array of previously played tracks (history)[]
historySizenumberMaximum number of tracks to keep in history10
pingnumberVoice connection latency0
queueQueueTrack queue instanceCreated
nodeNodeConnected Lavalink nodeSelected
dataRecord<string, unknown>Custom data storage{}
filtersFiltersAudio filters instanceCreated
listenListenListening analysis (NodeLink)Optional
lyricsLyricsLyrics provider (NodeLink)Optional

Methods

connect

connectmethod

Connect to Voice

Connects the player to a voice channel.

Parameters
optionsObject
Connection options
options.setMuteboolean
Whether to join muted
options.setDeafboolean
Whether to join deafened

Returns & Example

Returnsboolean — Whether the connection was successful

player.connect({ setDeaf: true });

disconnect

disconnectmethod

Disconnect from Voice

Disconnects from the voice channel.

Returns & Example

Returnsboolean — Whether the disconnection was successful

player.disconnect();

play

playmethod

Play Track

Starts or resumes playback. Handles blacklisted sources and attempts to find a suitable node if the current one is not compatible.

Parameters
optionsObject
Playback options
options.encodedstring
Base64 encoded track
options.requestedBystring | object
Track requester info. Can be a string or an object with id and userData properties.
options.positionnumber
Start position in milliseconds
options.endTimenumber
End position in milliseconds
options.isBackPlayboolean
Internal: Indicates if the track is being played from history.

Returns & Example

ReturnsPromise<boolean> — Whether playback started successfully

await player.play({
  encoded: 'base64track',
  requestedBy: '123456789',
  position: 0
});

speak

speakmethod

Speak Text (TTS)

Converts text to speech and plays it. Supports different TTS providers. Requires a NodeLink server with appropriate capabilities.

Parameters
optionsrequiredISpeakOptions
Speak options
options.textrequiredstring
The text to speak.
options.provider'flowery' | 'google' | 'skybot'
Optional: The TTS provider to use. Defaults to flowery.
options.optionsIFloweryTTSOptions | { language?: string }
Optional: Provider-specific options.
options.addToQueueboolean
Optional: Whether to add the TTS track to the queue. If false, it will play immediately and then resume the current track.

Returns & Example

ReturnsPromise<boolean> — Whether the TTS playback was successful.

// Speak a message using default provider
await player.speak({ text: 'Hello, I am a bot.' });

// Speak in a specific language using Google TTS
await player.speak({ text: 'Hola, soy un bot.', provider: 'google', options: { language: 'es-ES' } });

// Add to queue instead of interrupting
await player.speak({ text: 'This will be added to the queue.', addToQueue: true });

replay

replaymethod

Replay Track

Replays the current track from the beginning.

Returns & Example

ReturnsPromise<boolean> — Whether the replay was successful.

await player.replay();

back

backmethod

Play Previous Track

Plays the previous track from the history. Skips blacklisted tracks.

Returns & Example

ReturnsPromise<boolean> — Whether a previous track was played.

await player.back();

restart

restartmethod

Restart Player

Restarts the player and current track. Reconnects to the voice channel if necessary.

Returns & Example

ReturnsPromise<boolean> — Whether the restart was successful

await player.restart();

transferNode

transferNodemethod

Transfer Node

Transfers the player to another node. Reconnects and resumes playback on the new node.

Parameters
noderequiredNode | string
Target node or node identifier

Returns & Example

ReturnsPromise<boolean> — Whether the transfer was successful

await player.transferNode('node-2');

pause

pausemethod

Pause Playback

Pauses the current playback.

Returns & Example

Returnsboolean — Whether the pause was successful

player.pause();

resume

resumemethod

Resume Playback

Resumes paused playback.

Returns & Example

Returnsboolean — Whether the resume was successful

player.resume();

stop

stopmethod

Stop Playback

Stops the current playback.

Parameters
optionsObject
Stop options
options.destroyboolean
Whether to destroy the player

Returns & Example

Returnsboolean — Whether the stop was successful

player.stop({ destroy: true });

skip

skipmethod

Skip Track

Skips to the next track or a specific position in the queue. Skips blacklisted tracks.

Parameters
positionnumber
Queue position to skip to (0-based).

Returns & Example

ReturnsPromise<boolean> — Whether the skip was successful

await player.skip(2); // Skip to third track

skipChapter

skipChaptermethod

Skip Chapter

Skips to a specific chapter in the current track. Requires chapter information to be available on the track.

Parameters
valuenumber
1
The target chapter index (0-based) or the number of chapters to skip.
type'index' | 'count'
'count'
Whether value refers to a direct index or a count of chapters to skip from the current one.

Returns & Example

ReturnsPromise<boolean> — Whether the chapter skip was successful.

// Skip to the next chapter
await player.skipChapter();

// Skip to the third chapter (index 2)
await player.skipChapter(2, 'index');

seek

seekmethod

Seek Position

Seeks to a position in the current track.

Parameters
positionrequirednumber
Position in milliseconds

Returns & Example

Returnsboolean — Whether the seek was successful

player.seek(30000); // Seek to 30 seconds

shuffle

shufflemethod

Shuffle Queue

Shuffles the current queue. Requires at least 2 tracks in the queue.

Returns & Example

Returnsboolean — Whether the shuffle was successful

// Only works if queue.size >= 2
player.shuffle();

setVolume

setVolumemethod

Set Volume

Sets the player volume.

Parameters
volumerequirednumber
Volume level (0-1000)

Returns & Example

Returnsboolean — Whether the volume was set successfully

player.setVolume(50); // Set to 50%

setLoop

setLoopmethod

Set Loop Mode

Sets the loop mode.

Parameters
looprequiredTPlayerLoop
Loop mode ("off" | "track" | "queue")
countnumber
Optional: Number of times to loop. Only applicable for "track" or "queue" modes. Set to 0 for infinite loop.

Returns & Example

Returnsboolean — Whether the loop mode was set successfully

player.setLoop('track'); // Loop current track indefinitely
player.setLoop('queue', 5); // Loop queue 5 times
player.setLoop('off'); // Disable loop

setAutoPlay

setAutoPlaymethod

Set Auto Play

Sets auto-play behavior.

Parameters
autoPlayrequiredboolean
Whether to enable auto-play

Returns & Example

Returnsboolean — Whether auto-play was set successfully

player.setAutoPlay(true);

setAutoLeave

setAutoLeavemethod

Set Auto Leave

Sets auto-leave behavior.

Parameters
autoLeaverequiredboolean
Whether to enable auto-leave

Returns & Example

Returnsboolean — Whether auto-leave was set successfully

player.setAutoLeave(true);

setVoiceChannelId

setVoiceChannelIdmethod

Set Voice Channel

Changes the voice channel.

Parameters
channelIdrequiredstring
New voice channel ID

Returns & Example

Returnsboolean — Whether the channel was set successfully

player.setVoiceChannelId('123456789');

setTextChannelId

setTextChannelIdmethod

Set Text Channel

Changes the text channel.

Parameters
channelIdrequiredstring
New text channel ID

Returns & Example

Returnsboolean — Whether the channel was set successfully

player.setTextChannelId('123456789');

set

setmethod

Set Custom Data

Stores custom data in the player.

Parameters
keyrequiredstring
Data key
valuerequiredunknown
Data value

Returns & Example

Returnsvoid

player.set('customKey', 'customValue');

get

getmethod

Get Custom Data

Retrieves custom data from the player.

Parameters
keyrequiredstring
Data key

Returns & Example

ReturnsT — The stored value

const value = player.get('customKey');

has

hasmethod

Has Custom Data

Checks if custom data exists in the player.

Parameters
keyrequiredstring
Data key

Returns & Example

Returnsboolean — Whether the data exists

const exists = player.has('customKey');

delete

deletemethod

Delete Custom Data

Deletes custom data from the player.

Parameters
keyrequiredstring
Data key

Returns & Example

Returnsboolean — Whether the deletion was successful

player.delete('customKey');

getSponsorBlockCategories

getSponsorBlockCategoriesmethod

Get SponsorBlock Categories

Retrieves the currently configured SponsorBlock categories for a guild.

Parameters

This method takes no parameters.

Returns & Example

ReturnsPromise<string[]> — An array of category strings.

const categories = await player.getSponsorBlockCategories();
console.log('SponsorBlock Categories:', categories);

setSponsorBlockCategories

setSponsorBlockCategoriesmethod

Set SponsorBlock Categories

Sets the SponsorBlock categories for a guild.

Parameters
categoriesrequiredstring[]
An array of category strings to set.

Returns & Example

ReturnsPromise<void>

await player.setSponsorBlockCategories(['sponsor', 'selfpromo']);

clearSponsorBlockCategories

clearSponsorBlockCategoriesmethod

Clear SponsorBlock Categories

Clears all configured SponsorBlock categories for a guild.

Parameters

This method takes no parameters.

Returns & Example

ReturnsPromise<void>

await player.clearSponsorBlockCategories();

getHistory

getHistorymethod

Get History

Retrieves the player's track history.

Parameters
limitnumber
Optional: The maximum number of tracks to retrieve from the history.

Returns & Example

ReturnsTrack[] — An array of previously played tracks.

const history = player.getHistory();
const lastFive = player.getHistory(5);

getLyrics

getLyricsmethod

Get Lyrics

Fetches lyrics for the current track or a specific encoded track using available lyrics plugins.

Parameters
encodedTrackstring
Optional: Base64 encoded track string to fetch lyrics for.
skipTrackSourceboolean
Optional: Whether to skip the track's original source when searching for lyrics.
provider'lavalyrics' | 'lyrics'
Optional: Specific lyrics provider to use.

Returns & Example

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

const lyrics = await player.getLyrics();
const specificLyrics = await player.getLyrics('base64encodedtrack');

subscribeLyrics

subscribeLyricsmethod

Subscribe to Live Lyrics

Subscribes to live lyrics updates for the player's guild. The provided callback will be invoked with each new lyrics line.

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

Returns & Example

ReturnsPromise<void>

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

unsubscribeLyrics

unsubscribeLyricsmethod

Unsubscribe from Live Lyrics

Unsubscribes from live lyrics updates for the player's guild.

Parameters
provider'lavalyrics' | 'lyrics'
Optional: Specific lyrics provider to unsubscribe from.

Returns & Example

ReturnsPromise<void>

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

searchLyrics

searchLyricsmethod

Search Lyrics

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

Parameters
queryrequiredstring
The search query (e.g., song title and artist).
provider'lavalyrics' | 'lyrics'
Optional: Specific lyrics provider to use.

Returns & Example

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

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

destroy

destroymethod

Destroy Player

Destroys the player and cleans up resources.

Parameters
reasonstring
Optional reason for destroying the player.

Returns & Example

Returnsboolean — Whether the destruction was successful

player.destroy();