Documentation

lavalink.listener(*events: Type[Event])

Marks this function as an event listener for Lavalink.py. This must be used on class methods, and you must ensure that you register decorated methods by using Client.add_event_hooks().

Example

@listener()
async def on_lavalink_event(self, event):  # Event can be ANY Lavalink event
    ...

@listener(TrackStartEvent)
async def on_track_start(self, event: TrackStartEvent):
    ...

Note

Track event dispatch order is not guaranteed! For example, this means you could receive a TrackStartEvent before you receive a TrackEndEvent when executing operations such as skip().

Parameters:

events (Event) – The events to listen for. Leave this empty to listen for all events.

ABC

class lavalink.BasePlayer(guild_id: int, node: Node)

Represents the BasePlayer all players must be inherited from.

client

The Lavalink client instance.

Type:

Client

guild_id

The guild id of the player.

Type:

int

node

The node that the player is connected to.

Type:

Node

channel_id

The ID of the voice channel the player is connected to. This could be None if the player isn’t connected.

Type:

Optional[int]

current

The currently playing track.

Type:

Optional[AudioTrack]

abstract async handle_event(event: Event)

This function is a coroutine.

Handles an Event received directly from the websocket.

Parameters:

event (Event) – The event that will be handled.

abstract async update_state(state: Dict[str, Any])

This function is a coroutine.

Updates this player’s state with the state object received from the server.

Parameters:

state (Dict[str, Any]) – The player state.

async play_track(track: AudioTrack | DeferredAudioTrack, start_time: int = ..., end_time: int = ..., no_replace: bool = ..., volume: int = ..., pause: bool = ..., **kwargs) Dict[str, Any] | None

This function is a coroutine.

Plays the given track.

Warning

Multiple calls to this method within a short timeframe could cause issues with the player’s internal state, which can cause errors when processing a TrackStartEvent.

Parameters:
  • track (Union[AudioTrack, DeferredAudioTrack]) – The track to play.

  • start_time (int) – The number of milliseconds to offset the track by. If left unspecified or None is provided, the track will start from the beginning.

  • end_time (int) – The position at which the track should stop playing. This is an absolute position, so if you want the track to stop at 1 minute, you would pass 60000. The default behaviour is to play until no more data is received from the remote server. If left unspecified or None is provided, the default behaviour is exhibited.

  • no_replace (bool) – If set to true, operation will be ignored if a track is already playing or paused. The default behaviour is to always replace. If left unspecified or None is provided, the default behaviour is exhibited.

  • volume (int) – The initial volume to set. This is useful for changing the volume between tracks etc. If left unspecified or None is provided, the volume will remain at its current setting.

  • pause (bool) – Whether to immediately pause the track after loading it. The default behaviour is to never pause. If left unspecified or None is provided, the default behaviour is exhibited.

  • **kwargs (Any) – The kwargs to use when playing. You can specify any extra parameters that may be used by plugins, which offer extra features not supported out-of-the-box by Lavalink.py.

Returns:

The updated player object, or None if a request wasn’t made due to an empty payload.

Return type:

Optional[Dict[str, Any]]

async destroy()

This function is a coroutine.

Destroys the current player instance.

Shortcut for PlayerManager.destroy().

abstract async node_unavailable()

This function is a coroutine.

Called when a player’s node becomes unavailable. Useful for changing player state before it’s moved to another node.

abstract async change_node(node: Node)

This function is a coroutine.

Called when a node change is requested for the current player instance.

Parameters:

node (Node) – The new node to switch to.

class lavalink.DeferredAudioTrack(data: dict, requester: int = 0, **extra)

Similar to an AudioTrack, however this track only stores metadata up until it’s played, at which time load() is called to retrieve a base64 string which is then used for playing.

Note

For implementation: The track field need not be populated as this is done later via the load() method. You can optionally set self.track to the result of load() during implementation, as a means of caching the base64 string to avoid fetching it again later. This should serve the purpose of speeding up subsequent play calls in the event of repeat being enabled, for example.

abstract async load(client: Client) str | None

This function is a coroutine.

Retrieves a base64 string that’s playable by Lavalink. For example, you can use this method to search Lavalink for an identical track from other sources, which you can then use the base64 string of to play the track on Lavalink.

Parameters:

client (Client) – This will be an instance of the Lavalink client ‘linked’ to this track.

Returns:

A Lavalink-compatible base64-encoded string containing track metadata. If a track string cannot be returned, you may return None or throw a LoadError.

Return type:

Optional[str]

class lavalink.Source(name: str)
abstract async load_item(client: Client, query: str) LoadResult | None

This function is a coroutine.

Loads a track with the given query.

Parameters:
  • client (Client) – The Lavalink client. This could be useful for performing a Lavalink search for an identical track from other sources, if needed.

  • query (str) – The search query that was provided.

Returns:

A LoadResult, or None if there were no matches for the provided query.

Return type:

Optional[LoadResult]

class lavalink.Filter(values: FilterValueT, plugin_filter: bool = False)

A class representing a Lavalink audio filter.

Parameters:
  • values (Union[Dict[str, Any], List[Union[float, int]], float]) – The values for this filter.

  • plugin_filter (bool) – Whether this filter is part of a Lavalink plugin. Typically, this will be True when creating your own filters.

values

The values for this filter.

Type:

Union[Dict[str, Any], List[Union[float, int]], float]

plugin_filter

Whether this filter is part of a Lavalink plugin.

Type:

bool

abstract update(**kwargs)

Updates the internal values to match those provided.

abstract serialize() Dict[str, FilterValueT]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}

Client

class lavalink.Client(user_id: int | str, player: ~typing.Type[~lavalink.client.PlayerT] = <class 'lavalink.player.DefaultPlayer'>, regions: ~typing.Dict[str, ~typing.Tuple[str]] | None = None, connect_back: bool = False)

Represents a Lavalink client used to manage nodes and connections.

Parameters:
  • user_id (Union[int, str]) – The user id of the bot.

  • player (Type[BasePlayer]) – The class that should be used for the player. Defaults to DefaultPlayer. Do not change this unless you know what you are doing!

  • regions (Optional[Dict[str, Tuple[str]]]) –

    A mapping of continent -> Discord RTC regions. The key should be an identifier used when instantiating an node. The values should be a list of RTC regions that will be handled by the associated identifying key.

    Example: {"us": ("us-central", "us-east", "us-south", "us-west", "brazil")}

    You should only change this if you know what you’re doing and want more control over region groups. Defaults to None.

  • connect_back (Optional[bool]) –

    A boolean that determines if a player will connect back to the node it was originally connected to. This is not recommended to do since the player will most likely be performing better in the new node. Defaults to False.

    Warning

    If this option is enabled and the player’s node is changed through Player.change_node after the player was moved via the failover mechanism, the player will still move back to the original node when it becomes available. This behaviour can be avoided in custom player implementations by setting self._original_node to None in the BasePlayer.change_node() function.

node_manager

The node manager, used for storing and managing all registered Lavalink nodes.

Type:

NodeManager

player_manager

The player manager, used for storing and managing all players.

Type:

PlayerManager

sources

The custom sources registered to this client.

Type:

Set[Source]

property nodes: List[Node]

Convenience shortcut for NodeManager.nodes.

property players: Dict[int, PlayerT]

Convenience shortcut for PlayerManager.players.

async close()

This function is a coroutine.

Closes all active connections and frees any resources in use.

add_event_hook(*hooks, event: Type[EventT] | None = None)

Adds one or more event hooks to be dispatched on an event.

Note

Track event dispatch order is not guaranteed! For example, this means you could receive a TrackStartEvent before you receive a TrackEndEvent when executing operations such as skip().

Parameters:
  • hooks (function) – The hooks to register for the given event type. If event parameter is left empty, then it will run when any event is dispatched.

  • event (Optional[Type[Event]]) – The event the hooks belong to. They will be called when that specific event type is dispatched. Defaults to None which means the hook is dispatched on all events.

add_event_hooks(cls: Any)

Scans the provided class cls for functions decorated with listener(), and sets them up to process Lavalink events.

Example

# Inside a class __init__ method
self.client = lavalink.Client(...)
self.client.add_event_hooks(self)

Note

Track event dispatch order is not guaranteed! For example, this means you could receive a TrackStartEvent before you receive a TrackEndEvent when executing operations such as skip().

Parameters:

cls (Any) – An instance of a class containing event hook methods.

remove_event_hooks(*, events: Sequence[EventT] | None = None, hooks: Sequence[Callable])

Removes the given hooks from the event hook registry.

Parameters:
  • events (Sequence[Event]) – The events to remove the hooks from. This parameter can be omitted, and the events registered on the function via listener() will be used instead, if applicable. Otherwise, a default value of Generic is used instead.

  • hooks (Sequence[Callable]) – A list of hook methods to remove.

register_source(source: Source)

Registers a Source that Lavalink.py will use for looking up tracks.

Parameters:

source (Source) – The source to register.

get_source(source_name: str) Source | None

Gets a registered source by the given name.

Parameters:

source_name (str) – The name of the source to get.

Returns:

The source with the matching name. May be None if the name didn’t match any of those in the registered sources.

Return type:

Optional[Source]

add_node(host: str, port: int, password: str, region: str, name: str | None = None, ssl: bool = False, session_id: str | None = None, connect: bool = True) Node

Shortcut for NodeManager.add_node().

Adds a node to Lavalink’s node manager.

Parameters:
  • host (str) – The address of the Lavalink node.

  • port (int) – The port to use for websocket and REST connections.

  • password (str) – The password used for authentication.

  • region (str) – The region to assign this node to.

  • name (Optional[str]) – An identifier for the node that will show in logs. Defaults to None.

  • ssl (bool) – Whether to use SSL for the node. SSL will use wss and https, instead of ws and http, respectively. Your node should support SSL if you intend to enable this, either via reverse proxy or other methods. Only enable this if you know what you’re doing.

  • session_id (Optional[str]) – The ID of the session to resume. Defaults to None. Only specify this if you have the ID of the session you want to resume.

  • connect (bool) – Whether to immediately connect to the node after creating it. If False, you must call Node.connect() if you require WebSocket functionality.

Returns:

The created Node instance.

Return type:

Node

async get_local_tracks(query: str) LoadResult

This function is a coroutine.

Searches sources registered to this client for the given query.

Parameters:

query (str) – The query to perform a search for.

Return type:

LoadResult

async get_tracks(query: str, node: Node | None = None, check_local: bool = False) LoadResult

This function is a coroutine.

Retrieves a list of results pertaining to the provided query.

If check_local is set to True and any of the sources return a LoadResult then that result will be returned, and Lavalink will not be queried.

Warning

Avoid setting check_local to True if you call this method from a custom Source to avoid recursion issues!

Parameters:
  • query (str) – The query to perform a search for.

  • node (Optional[Node]) – The node to use for track lookup. Leave this blank to use a random node. Defaults to None which is a random node.

  • check_local (bool) – Whether to also search the query on sources registered with this Lavalink client.

Return type:

LoadResult

async decode_track(track: str, node: Node | None = None) AudioTrack

This function is a coroutine.

Decodes a base64-encoded track string into a dict.

Parameters:
  • track (str) – The base64-encoded track string.

  • node (Optional[Node]) – The node to use for the query. Defaults to None which is a random node.

Return type:

AudioTrack

async decode_tracks(tracks: List[str], node: Node | None = None) List[AudioTrack]

This function is a coroutine.

Decodes a list of base64-encoded track strings into a list of AudioTrack.

Parameters:
  • tracks (List[str]) – A list of base64-encoded track strings.

  • node (Optional[Node]) – The node to use for the query. Defaults to None which is a random node.

Returns:

A list of decoded AudioTrack.

Return type:

List[AudioTrack]

async voice_update_handler(data: Dict[str, Any])

This function is a coroutine.

This function intercepts websocket data from your Discord library and forwards the relevant information on to Lavalink, which is used to establish a websocket connection and send audio packets to Discord.

Example

bot.add_listener(lavalink_client.voice_update_handler, 'on_socket_response')
Parameters:

data (Dict[str, Any]) – The payload received from Discord.

has_listeners(event: Type[Event]) bool

Check whether the client has any listeners for a specific event type.

DataIO

class lavalink.DataReader(base64_str: str)
property remaining: int

The amount of bytes left to be read.

read_byte() bytes

Reads a single byte from the stream.

Return type:

bytes

read_boolean() bool

Reads a bool from the stream.

Return type:

bool

read_unsigned_short() int

Reads an unsigned short from the stream.

Return type:

int

read_int() int

Reads an int from the stream.

Return type:

int

read_long() int

Reads a long from the stream.

Return type:

int

read_nullable_utf(utfm: bool = False) str | None

Reads an optional UTF string from the stream.

Internally, this just reads a bool and then a string if the bool is True.

Parameters:

utfm (bool) – Whether to read the string as modified UTF.

Return type:

Optional[str]

read_utf() bytes

Reads a UTF string from the stream.

Return type:

bytes

read_utfm() str

Reads a UTF string from the stream.

This method is different to read_utf() as it accounts for different encoding methods utilised by Java’s streams, which uses modified UTF for character encoding.

Return type:

str

class lavalink.DataWriter
write_byte(byte)

Writes a single byte to the stream.

Parameters:

byte (Any) – This can be anything BytesIO.write() accepts.

write_boolean(boolean: bool)

Writes a bool to the stream.

Parameters:

boolean (bool) – The bool to write.

write_unsigned_short(short: int)

Writes an unsigned short to the stream.

Parameters:

short (int) – The unsigned short to write.

write_int(integer: int)

Writes an int to the stream.

Parameters:

integer (int) – The integer to write.

write_long(long_value: int)

Writes a long to the stream.

Parameters:

long_value (int) – The long to write.

write_nullable_utf(utf_string: str | None)

Writes an optional string to the stream.

Parameters:

utf_string (Optional[str]) – The optional string to write.

write_utf(utf_string: str)

Writes a utf string to the stream.

Parameters:

utf_string (str) – The string to write.

finish() bytes

Finalizes the stream by writing the necessary flags, byte length etc.

Returns:

The finalized stream.

Return type:

bytes

Errors

class lavalink.ClientError

Raised when something goes wrong within the client.

class lavalink.AuthenticationError

Raised when a request fails due to invalid authentication.

class lavalink.InvalidTrack

Raised when an invalid track was passed.

class lavalink.LoadError

Raised when a track fails to load. E.g. if a DeferredAudioTrack fails to find an equivalent.

class lavalink.RequestError(message, status: int, response: dict, params: Dict[str, Any])

Raised when a request to the Lavalink server fails.

status

The HTTP status code returned by the server.

Type:

int

timestamp

The epoch timestamp in milliseconds, at which the error occurred.

Type:

int

error

The HTTP status code message.

Type:

str

message

The error message.

Type:

str

path

The request path.

Type:

str

trace

The stack trace of the error. This will only be present if trace=true was provided in the query parameters of the request.

Type:

Optional[str]

params

The parameters passed to the request that errored.

Type:

Dict[str, Any]

Events

All Events are derived from Event

class lavalink.Event

The base for all Lavalink events.

class lavalink.TrackStartEvent(player: BasePlayer, track: AudioTrack)

This event is emitted when a track begins playing (e.g. via player.play())

player

The player that started to play a track.

Type:

BasePlayer

track

The track that started playing.

Type:

AudioTrack

class lavalink.TrackStuckEvent(player: BasePlayer, track: AudioTrack, threshold: int)

This event is emitted when the currently playing track is stuck (i.e. has not provided any audio). This is typically a fault of the track’s underlying audio stream, and not Lavalink itself.

Note

You do not need to manually trigger the start of the next track in the queue within this event when using the DefaultPlayer. This is handled for you.

player

The player associated with the stuck track.

Type:

BasePlayer

track

The stuck track.

Type:

AudioTrack

threshold

The configured threshold, in milliseconds, after which a track is considered to be stuck when no audio frames were provided.

Type:

int

class lavalink.TrackExceptionEvent(player: BasePlayer, track: AudioTrack, message: str | None, severity: Severity, cause: str)

This event is emitted when a track encounters an exception during playback.

Note

You do not need to manually trigger the start of the next track in the queue within this event when using the DefaultPlayer. This is handled for you.

player

The player that had the exception occur while playing a track.

Type:

BasePlayer

track

The track that had the exception while playing.

Type:

AudioTrack

message

The exception message.

Type:

Optional[str]

severity

The severity of the exception.

Type:

Severity

cause

The cause of the exception.

Type:

str

class lavalink.TrackEndEvent(player: BasePlayer, track: AudioTrack | None, reason: EndReason)

This event is emitted when the player finished playing a track.

Note

You do not need to manually trigger the start of the next track in the queue within this event when using the DefaultPlayer. This is handled for you.

player

The player that finished playing a track.

Type:

BasePlayer

track

The track that finished playing. This could be None if Lavalink fails to encode the track.

Type:

Optional[AudioTrack]

reason

The reason why the track stopped playing.

Type:

EndReason

class lavalink.TrackLoadFailedEvent(player: BasePlayer, track: DeferredAudioTrack, original: Exception | None)

This is a custom event, emitted when a deferred audio track fails to produce a playable track. The player will not do anything by itself, so it is up to you to skip the broken track.

Note

This event will not automatically trigger the start of the next track in the queue, so you must ensure that you do this if you want the player to continue playing from the queue.

player

The player responsible for playing the track.

Type:

BasePlayer

track

The track that failed to produce a playable track.

Type:

DeferredAudioTrack

original

The original error, emitted by the track. This may be None if the track did not raise an error, but rather returned None in place of a playable track.

Type:

Optional[Exception]

class lavalink.QueueEndEvent(player: BasePlayer)

This is a custom event, emitted by the DefaultPlayer when there are no more tracks in the queue.

player

The player that has no more songs in queue.

Type:

BasePlayer

class lavalink.PlayerUpdateEvent(player: BasePlayer, raw_state)

This event is emitted when a player’s progress changes.

player

The player that’s progress was updated.

Type:

BasePlayer

position

The track’s elapsed playback time in milliseconds.

Type:

int

timestamp

The track’s elapsed playback time as an epoch timestamp in milliseconds.

Type:

int

connected

Whether or not the player is connected to the voice gateway.

Type:

bool

ping

The player’s voice connection ping. This is calculated from the delay between heartbeat & heartbeat ack. This will be -1 when the player doesn’t have a voice connection.

Type:

int

class lavalink.NodeConnectedEvent(node: Node)

This is a custom event, emitted when a connection to a Lavalink node is successfully established.

node

The node that was successfully connected to.

Type:

Node

class lavalink.NodeDisconnectedEvent(node: Node, code: int | None, reason: str | None)

This is a custom event, emitted when the connection to a Lavalink node drops and becomes unavailable.

node

The node that was disconnected from.

Type:

Node

code

The status code of the event.

Type:

Optional[int]

reason

The reason of why the node was disconnected.

Type:

Optional[str]

class lavalink.NodeChangedEvent(player: BasePlayer, old_node: Node, new_node: Node)

This is a custom event, emitted when a player changes to another Lavalink node. Keep in mind this event can be emitted multiple times if a node disconnects and the load balancer moves players to a new node.

player

The player whose node was changed.

Type:

BasePlayer

old_node

The node the player was moved from.

Type:

Node

new_node

The node the player was moved to.

Type:

Node

class lavalink.NodeReadyEvent(node: Node, session_id: str, resumed: bool)

This is a custom event, emitted when a node becomes ready. A node is considered ready once it receives the “ready” event from the Lavalink server.

node

The node that became ready.

Type:

Node

session_id

The ID of the session.

Type:

str

resumed

Whether the session was resumed. This will be false if a brand new session was created.

Type:

bool

class lavalink.WebSocketClosedEvent(player: BasePlayer, code: int, reason: str, by_remote: bool)

This event is emitted when an audio websocket to Discord is closed. This can happen happen for various reasons, an example being when a channel is deleted.

Refer to the Discord Developer docs for a list of close codes and what they mean. This event primarily exists for debug purposes, and no special handling of voice connections should take place unless it is absolutely necessary.

player

The player whose audio websocket was closed.

Type:

BasePlayer

code

The node the player was moved from.

Type:

int

reason

The node the player was moved to.

Type:

str

by_remote

If the websocket was closed remotely.

Type:

bool

class lavalink.IncomingWebSocketMessage(data, node: Node)

This event is emitted whenever the client receives a websocket message from the Lavalink server.

You can use this to extend the functionality of the client, particularly useful when used with Lavalink server plugins that can add new HTTP routes or websocket messages.

data

The received JSON-formatted data from the websocket.

Type:

Union[Dict[Any, Any], List[Any]]

node

The node responsible for this websocket message.

Type:

Node

class lavalink.PlayerErrorEvent(player, original)

Raised when an error occurs within a BasePlayer.

player

The player in which the error occurred.

Type:

BasePlayer

original

The original error.

Type:

Exception

Filters

All custom filters must derive from Filter

class lavalink.Equalizer

Allows modifying the gain of 15 bands, to boost or reduce the volume of specific frequency ranges. For example, this could be used to boost the low (bass) frequencies to act as a ‘bass boost’.

update(*, bands: List[Tuple[int, float]])
update(*, band: int, gain: int)

Modifies the gain of each specified band. There are 15 total bands (indexes 0 to 14) that can be modified. The meaningful range of each band is -0.25 (muted) to 1.0. A gain of 0.25 doubles the frequency. The default gain is 0.0. Modifying the gain could alter the volume of output.

The frequencies of each band are as follows: 25 Hz, 40 Hz, 63 Hz, 100 Hz, 160 Hz, 250 Hz, 400 Hz, 630 Hz, 1k Hz, 1.6k Hz, 2.5k Hz, 4k Hz, 6.3k Hz, 10k Hz, 16k Hz Leftmost frequency represents band 0, rightmost frequency represents band 14.

Note

You can provide either bands OR band and gain for the parameters.

The limits are:

0 ≤ band ≤ 14

-0.25 ≤ gain ≤ 1.0

Parameters:
  • bands (List[Tuple[int, float]]) – The bands to modify, and their respective gains.

  • band (int) – The band to modify.

  • gain (float) – The new gain of the band.

Raises:

ValueError

serialize() Dict[str, Any]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}
class lavalink.Karaoke

Allows for isolating a frequency range (commonly, the vocal range). Useful for karaoke/sing-along.

update(*, level: float)
update(*, mono_level: float)
update(*, filter_width: float)
update(*, level: float, mono_level: float)
update(*, level: float, filter_width: float)
update(*, mono_level: float, filter_width: float)
update(*, level: float, mono_level: float, filter_width: float)
Parameters:
  • level (float) – The level of the Karaoke effect.

  • mono_level (float) – The mono level of the Karaoke effect.

  • filter_band (float) – The frequency of the band to filter.

  • filter_width (float) – The width of the filter.

Raises:

ValueError

serialize() Dict[str, Dict[str, float]]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}
class lavalink.Timescale

Allows speeding up/slowing down the audio, adjusting the pitch and playback rate.

update(*, speed: float)
update(*, pitch: float)
update(*, rate: float)
update(*, speed: float, pitch: float)
update(*, speed: float, rate: float)
update(*, rate: float, pitch: float)
update(*, speed: float, rate: float, pitch: float)

Note

The limits are:

0.1 ≤ speed

0.1 ≤ pitch

0.1 ≤ rate

Parameters:
  • speed (float) – The playback speed.

  • pitch (float) – The pitch of the audio.

  • rate (float) – The playback rate.

Raises:

ValueError

serialize() Dict[str, Dict[str, float]]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}
class lavalink.Tremolo

Applies a ‘tremble’ effect to the audio.

update(*, frequency: float)
update(*, depth: float)
update(*, frequency: float, depth: float)

Note

The limits are:

0 < frequency

0 < depth ≤ 1

Parameters:
  • frequency (float) – How frequently the effect should occur.

  • depth (float) – The “strength” of the effect.

Raises:

ValueError

serialize() Dict[str, Dict[str, float]]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}
class lavalink.Vibrato

Applies a ‘wobble’ effect to the audio.

update(*, frequency: float)
update(*, depth: float)
update(*, frequency: float, depth: float)

Note

The limits are:

0 < frequency ≤ 14

0 < depth ≤ 1

Parameters:
  • frequency (float) – How frequently the effect should occur.

  • depth (float) – The “strength” of the effect.

Raises:

ValueError

serialize() Dict[str, Dict[str, float]]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}
class lavalink.Rotation

Phases the audio in and out of the left and right channels in an alternating manner. This is commonly used to create the 8D effect.

update(*, rotation_hz: float)

Note

The limits are:

0 ≤ rotation_hz

Parameters:

rotation_hz (float) – How frequently the effect should occur.

Raises:

ValueError

serialize() Dict[str, Dict[str, float]]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}
class lavalink.LowPass

Applies a low-pass effect to the audio, whereby only low frequencies can pass, effectively cutting off high frequencies meaning more emphasis is put on lower frequencies.

update(*, smoothing: float)

Note

The limits are:

1 < smoothing

Parameters:

smoothing (float) – The strength of the effect.

Raises:

ValueError

serialize() Dict[str, Dict[str, float]]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}
class lavalink.ChannelMix

Allows passing the audio from one channel to the other, or isolating individual channels.

update(**kwargs)

Note

The limits are:

0 ≤ leftToLeft ≤ 1.0

0 ≤ leftToRight ≤ 1.0

0 ≤ rightToLeft ≤ 1.0

0 ≤ rightToRight ≤ 1.0

Parameters:
  • left_to_left (float) – The volume level of the audio going from the “Left” channel to the “Left” channel.

  • left_to_right (float) – The volume level of the audio going from the “Left” channel to the “Right” channel.

  • right_to_left (float) – The volume level of the audio going from the “Right” channel to the “Left” channel.

  • right_to_right (float) – The volume level of the audio going from the “Right” channel to the “Left” channel.

Raises:

ValueError

serialize() Dict[str, Dict[str, float]]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}
class lavalink.Volume

Adjusts the audio output volume.

update(*, volume: float)

Modifies the player volume. This uses LavaDSP’s volume filter, rather than Lavaplayer’s native volume changer.

Note

The limits are:

0 ≤ volume ≤ 5

Parameters:

volume (float) – The new volume of the player. 1.0 means 100%/default.

serialize() Dict[str, float]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}
class lavalink.Distortion

As the name suggests, this distorts the audio.

update(**kwargs)
Parameters:
  • sin_offset (float) – The sin offset.

  • sin_scale (float) – The sin scale.

  • cos_offset (float) – The sin offset.

  • cos_scale (float) – The sin scale.

  • tan_offset (float) – The sin offset.

  • tan_scale (float) – The sin scale.

  • offset (float) – The sin offset.

  • scale (float) – The sin scale.

Raises:

ValueError

serialize() Dict[str, Dict[str, float]]

Transforms the internal values into a dict matching the structure Lavalink expects.

Example

return {"yourCustomFilter": {"gain": 5}}

Player

All custom players must derive from BasePlayer

class lavalink.DefaultPlayer(guild_id: int, node: Node)

The player that Lavalink.py uses by default.

This should be sufficient for most use-cases.

LOOP_NONE

Class attribute. Disables looping entirely.

Type:

int

LOOP_SINGLE

Class attribute. Enables looping for a single (usually currently playing) track only.

Type:

int

LOOP_QUEUE

Class attribute. Enables looping for the entire queue. When a track finishes playing, it’ll be added to the end of the queue.

Type:

int

guild_id

The guild id of the player.

Type:

int

node

The node that the player is connected to.

Type:

Node

paused

Whether or not a player is paused.

Type:

bool

position_timestamp

Returns the track’s elapsed playback time as an epoch timestamp.

Type:

int

volume

The volume at which the player is playing at.

Type:

int

shuffle

Whether or not to mix the queue up in a random playing order.

Type:

bool

loop

Whether loop is enabled, and the type of looping. This is an integer as loop supports multiple states.

0 = Loop off.

1 = Loop track.

2 = Loop queue.

Example

if player.loop == player.LOOP_NONE:
    await ctx.send('Not looping.')
elif player.loop == player.LOOP_SINGLE:
    await ctx.send(f'{player.current.title} is looping.')
elif player.loop == player.LOOP_QUEUE:
    await ctx.send('This queue never ends!')
Type:

Literal[0, 1, 2]

filters

A mapping of str to Filter, representing currently active filters.

Type:

Dict[str, Filter]

queue

A list of AudioTracks to play.

Type:

List[AudioTrack]

current

The track that is playing currently, if any.

Type:

Optional[AudioTrack]

property is_playing: bool

Returns the player’s track state.

property is_connected: bool

Returns whether the player is connected to a voicechannel or not.

property position: int

Returns the track’s elapsed playback time in milliseconds, adjusted for Lavalink stat interval.

store(key: object, value: object)

Stores custom user data.

Parameters:
  • key (object) – The key of the object to store.

  • value (object) – The object to associate with the key.

fetch(key: object, default=None)

Retrieves the related value from the stored user data.

Parameters:
  • key (object) – The key to fetch.

  • default (Optional[any]) – The object that should be returned if the key doesn’t exist. Defaults to None.

Return type:

Optional[any]

delete(key: object)

Removes an item from the the stored user data.

Parameters:

key (object) – The key to delete.

Raises:

KeyError – If the key doesn’t exist.

add(track: AudioTrack | DeferredAudioTrack | Dict[str, str | None | bool | int], requester: int = 0, index: int | None = None)

Adds a track to the queue.

Parameters:
  • track (Union[AudioTrack, DeferredAudioTrack, Dict[str, Union[Optional[str], bool, int]]]) – The track to add. Accepts either an AudioTrack or a dict representing a track returned from Lavalink.

  • requester (int) – The ID of the user who requested the track.

  • index (Optional[int]) – The index at which to add the track. If index is left unspecified, the default behaviour is to append the track. Defaults to None.

async play(track: AudioTrack | DeferredAudioTrack | Dict[str, str | None | bool | int] | None = None, start_time: int = ..., end_time: int = ..., no_replace: bool = ..., volume: int = ..., pause: bool = ..., **kwargs)

This function is a coroutine.

Plays the given track.

This method differs from BasePlayer.play_track() in that it contains additional logic to handle certain attributes, such as loop, shuffle, and loading a base64 string from DeferredAudioTrack.

Warning

Multiple calls to this method within a short timeframe could cause issues with the player’s internal state, which can cause errors when processing a TrackStartEvent.

Parameters:
  • track (Optional[Union[DeferredAudioTrack, AudioTrack, Dict[str, Union[Optional[str], bool, int]]]]) – The track to play. If left unspecified, this will default to the first track in the queue. Defaults to None which plays the next song in queue. Accepts either an AudioTrack or a dict representing a track returned from Lavalink.

  • start_time (int) – The number of milliseconds to offset the track by. If left unspecified, the track will start from the beginning.

  • end_time (int) – The position at which the track should stop playing. This is an absolute position, so if you want the track to stop at 1 minute, you would pass 60000. If left unspecified, the track will play through to the end.

  • no_replace (bool) – If set to true, operation will be ignored if the player already has a current track. If left unspecified, the currently playing track will always be replaced.

  • volume (int) – The initial volume to set. This is useful for changing the volume between tracks etc. If left unspecified, the volume will remain at its current setting.

  • pause (bool) – Whether to immediately pause the track after loading it. Defaults to False.

  • **kwargs (Any) – The kwargs to use when playing. You can specify any extra parameters that may be used by plugins, which offer extra features not supported out-of-the-box by Lavalink.py.

Raises:
  • ValueError – If invalid values were provided for start_time or end_time.

  • TypeError – If wrong types were provided for no_replace, volume or pause.

async stop()

This function is a coroutine.

Stops the player.

async skip()

This function is a coroutine.

Plays the next track in the queue, if any.

Warning

Multiple calls to this method within a short timeframe could cause issues with the player’s internal state, which can cause errors when processing a TrackStartEvent.

set_loop(loop: int)

Sets whether the player loops between a single track, queue or none.

0 = off, 1 = single track, 2 = queue.

Parameters:

loop (Literal[0, 1, 2]) – The loop setting. 0 = off, 1 = single track, 2 = queue.

set_shuffle(shuffle: bool)

Sets the player’s shuffle state.

Parameters:

shuffle (bool) – Whether to shuffle the player or not.

async set_pause(pause: bool)

This function is a coroutine.

Sets the player’s paused state.

Parameters:

pause (bool) – Whether to pause the player or not.

async set_volume(vol: int)

This function is a coroutine.

Sets the player’s volume

Note

A limit of 1000 is imposed by Lavalink.

Parameters:

vol (int) – The new volume level.

async seek(position: int)

This function is a coroutine.

Seeks to a given position in the track.

Parameters:

position (int) – The new position to seek to in milliseconds.

async set_filters(*filters: Filter)

This function is a coroutine.

This sets multiple filters at once.

Applies the corresponding filters within Lavalink. This will overwrite any identical filters that are already applied.

Parameters:

*filters (Filter) – The filters to apply.

Raises:

TypeError – If any of the provided filters is not of type Filter.

async set_filter(_filter: Filter)

This function is a coroutine.

Applies the corresponding filter within Lavalink. This will overwrite the filter if it’s already applied.

Example

equalizer = Equalizer()
equalizer.update(bands=[(0, 0.2), (1, 0.3), (2, 0.17)])
player.set_filter(equalizer)
Parameters:

_filter (Filter) – The filter instance to set.

Raises:

TypeError – If the provided _filter is not of type Filter.

async update_filter(_filter: Type[FilterT], **kwargs)

This function is a coroutine.

Updates a filter using the upsert method; if the filter exists within the player, its values will be updated; if the filter does not exist, it will be created with the provided values.

This will not overwrite any values that have not been provided.

Example

player.update_filter(Timescale, speed=1.5)
# This means that, if the Timescale filter is already applied
# and it already has set values of "speed=1, pitch=1.2", pitch will remain
# the same, however speed will be changed to 1.5 so the result is
# "speed=1.5, pitch=1.2"
Parameters:
  • _filter (Type[Filter]) – The filter class (not an instance of, see above example) to upsert.

  • **kwargs (Any) – The kwargs to pass to the filter.

Raises:

TypeError – If the provided _filter is not of type Filter.

get_filter(_filter: Type[FilterT] | str)

Returns the corresponding filter, if it’s enabled.

Example

from lavalink.filters import Timescale
timescale = player.get_filter(Timescale)
# or
timescale = player.get_filter('timescale')
Parameters:

_filter (Union[Type[Filter], str]) – The filter name, or filter class (not an instance of, see above example), to get.

Return type:

Optional[Filter]

async remove_filters(*filters: Type[FilterT] | str)

This function is a coroutine.

Removes multiple filters from the player, undoing any effects applied to the audio. This is similar to remove_filter() but instead allows you to remove multiple filters with one call.

Parameters:

filters (Union[Type[Filter], str]) – The filters to remove. Can be filter name, or filter class (not an instance of).

async remove_filter(_filter: Type[FilterT] | str)

This function is a coroutine.

Removes a filter from the player, undoing any effects applied to the audio.

Example

player.remove_filter(Timescale)
# or
player.remove_filter('timescale')
Parameters:

_filter (Union[Type[Filter], str]) – The filter name, or filter class (not an instance of, see above example), to remove.

async clear_filters()

This function is a coroutine.

Clears all currently-enabled filters.

async handle_event(event)

Handles the given event as necessary.

Parameters:

event (Event) – The event to handle.

async update_state(state: dict)

Updates the position of the player.

Parameters:

state (dict) – The state that is given to update.

async node_unavailable()

This function is a coroutine.

Called when a player’s node becomes unavailable. Useful for changing player state before it’s moved to another node.

async change_node(node: Node)

This function is a coroutine.

Changes the player’s node

Parameters:

node (Node) – The node the player is changed to.

Server

class lavalink.AudioTrack(data: dict, requester: int = 0, **extra)

Represents an AudioTrack.

Parameters:
  • data (Union[Dict[str, Union[Optional[str], bool, int]], AudioTrack]) – The data to initialise an AudioTrack from.

  • requester (any) – The requester of the track.

  • extra (Dict[Any, Any]) – Any extra information to store in this AudioTrack.

track

The base64-encoded string representing a Lavalink-readable AudioTrack. This is marked optional as it could be None when it’s not set by a custom Source, which is expected behaviour when the subclass is a DeferredAudioTrack.

Type:

Optional[str]

identifier

The track’s id. For example, a youtube track’s identifier will look like dQw4w9WgXcQ.

Type:

str

is_seekable

Whether the track supports seeking.

Type:

bool

author

The track’s uploader.

Type:

str

duration

The duration of the track, in milliseconds.

Type:

int

is_stream

Whether the track is a live-stream.

Type:

bool

title

The title of the track.

Type:

str

uri

The full URL of track.

Type:

str

artwork_url

A URL pointing to the track’s artwork, if applicable.

Type:

Optional[str]

isrc

The ISRC for the track, if applicable.

Type:

Optional[str]

position

The playback position of the track, in milliseconds. This is a read-only property; setting it won’t have any effect.

Type:

int

source_name

The name of the source that this track was created by.

Type:

str

requester

The ID of the user that requested this track.

Type:

int

plugin_info

Addition track info provided by plugins.

Type:

Optional[Dict[str, Any]]

user_data

The user data that was attached to the track, if any.

Type:

Optional[Dict[str, Any]]

extra

Any extra properties given to this AudioTrack will be stored here.

Type:

Dict[str, Any]

property stream: bool

Property indicating whether this track is a stream.

Deprecated since version 5.3.0: To be consistent with attribute naming, this property has been deprecated in favour of is_stream.

enum lavalink.EndReason(value)

An enumeration.

Valid values are as follows:

FINISHED = <EndReason.FINISHED: 'finished'>
LOAD_FAILED = <EndReason.LOAD_FAILED: 'loadFailed'>
STOPPED = <EndReason.STOPPED: 'stopped'>
REPLACED = <EndReason.REPLACED: 'replaced'>
CLEANUP = <EndReason.CLEANUP: 'cleanup'>

The Enum and its members also have the following methods:

may_start_next() bool

Returns whether the next track may be started from this event.

This is mostly used as a hint to determine whether the track_end_event should be responsible for playing the next track.

Returns:

Whether the next track may be started.

Return type:

bool

enum lavalink.LoadType(value)

An enumeration.

Valid values are as follows:

TRACK = <LoadType.TRACK: 'track'>
PLAYLIST = <LoadType.PLAYLIST: 'playlist'>
SEARCH = <LoadType.SEARCH: 'search'>
EMPTY = <LoadType.EMPTY: 'empty'>
ERROR = <LoadType.ERROR: 'error'>
enum lavalink.Severity(value)

An enumeration.

Valid values are as follows:

COMMON = <Severity.COMMON: 'common'>
SUSPICIOUS = <Severity.SUSPICIOUS: 'suspicious'>
FAULT = <Severity.FAULT: 'fault'>
class lavalink.PlaylistInfo(name: str, selected_track: int = -1)
name

The name of the playlist.

Type:

str

selected_track

The index of the selected/highlighted track. This will be -1 if there is no selected track.

Type:

int

class lavalink.LoadResultError(error: Dict[str, Any])
message

The error message.

Type:

str

severity

The severity of the error.

Type:

Severity

cause

The cause of the error.

Type:

str

class lavalink.LoadResult(load_type: ~lavalink.server.LoadType, tracks: ~typing.List[~lavalink.server.AudioTrack | DeferredAudioTrack], playlist_info: ~lavalink.server.PlaylistInfo = <PlaylistInfo name= selected_track=-1>, plugin_info: ~typing.Dict[str, ~typing.Any] | None = None, error: ~lavalink.server.LoadResultError | None = None)
load_type

The load type of this result.

Type:

LoadType

tracks

The tracks in this result.

Type:

List[Union[AudioTrack, DeferredAudioTrack]]

playlist_info

The playlist metadata for this result. The PlaylistInfo could contain empty/false data if the LoadType is not LoadType.PLAYLIST.

Type:

PlaylistInfo

plugin_info

Additional playlist info provided by plugins.

Type:

Optional[Dict[str, Any]]

error

The error associated with this LoadResult. This will be None if load_type is not LoadType.ERROR.

Type:

Optional[LoadResultError]

property selected_track: AudioTrack | None

Convenience method for returning the selected track using PlaylistInfo.selected_track.

This could be None if playlist_info is None, or PlaylistInfo.selected_track is an invalid number.

Return type:

Optional[AudioTrack]

class lavalink.Plugin(data: Dict[str, Any])

Represents a Lavalink server plugin.

Parameters:

data (Dict[str, Any]) – The data to initialise a Plugin from.

name

The name of the plugin.

Type:

str

version

The version of the plugin.

Type:

str

Node

class lavalink.Node(manager, host: str, port: int, password: str, region: str, name: str | None = None, ssl: bool = False, session_id: str | None = None, connect: bool = True)

Represents a Node connection with Lavalink.

Note

To construct a node, you should use Client.add_node() instead.

client

The Lavalink client.

Type:

Client

region

The region to assign this node to.

Type:

str

name

The name the Node is identified by.

Type:

str

stats

The statistics of how the Node is performing.

Type:

Stats

property session_id: str | None

The session ID for this node. Could be None if a ready event has not yet been received from the server.

property available: bool

Returns whether the node has a websocket connection. The node could probably still be used for HTTP requests even without a WS connection.

property players: List[BasePlayer]

Returns a list of all players on this node.

Return type:

List[BasePlayer]

property penalty: float

Returns the load-balancing penalty for this node.

async get_rest_latency() float

This function is a coroutine.

Measures the REST latency for this node. This simply calls get_version() but measures the time between when the request was made, and when a response was received.

Returns:

The latency, in milliseconds. -1 if an error occurred during the request (e.g. node is unreachable), otherwise, a positive number.

Return type:

float

async connect(force: bool = False) Task | None

This function is a coroutine.

Initiates a WebSocket connection to this node. If a connection already exists, and force is False, this will not do anything.

Parameters:

force (bool) – Whether to close any existing WebSocket connections and re-establish a connection to the node.

Returns:

The WebSocket connection task, or None if a WebSocket connection already exists and force is False.

Return type:

Optional[asyncio.Task]

async destroy()

This function is a coroutine.

Destroys the transport and any underlying connections for this node. This will also cleanly close the websocket.

async get_tracks(query: str) LoadResult

This function is a coroutine.

Retrieves a list of results pertaining to the provided query.

Parameters:

query (str) – The query to perform a search for.

Return type:

LoadResult

async decode_track(track: str) AudioTrack

This function is a coroutine.

Decodes a base64-encoded track string into an AudioTrack object.

Parameters:

track (str) – The base64-encoded track string to decode.

Return type:

AudioTrack

async decode_tracks(tracks: List[str]) List[AudioTrack]

This function is a coroutine.

Decodes a list of base64-encoded track strings into a list of AudioTrack.

Parameters:

tracks (List[str]) – A list of base64-encoded track strings.

Returns:

A list of decoded AudioTracks.

Return type:

List[AudioTrack]

async get_routeplanner_status() Dict[str, Any]

This function is a coroutine.

Retrieves the status of the target node’s routeplanner.

Returns:

A dict representing the routeplanner information.

Return type:

Dict[str, Any]

async routeplanner_free_address(address: str) bool

This function is a coroutine.

Frees up the provided IP address in the target node’s routeplanner.

Parameters:

address (str) – The address to free.

Returns:

True if the address was freed, False otherwise.

Return type:

bool

async routeplanner_free_all_failing() bool

This function is a coroutine.

Frees up all IP addresses in the target node that have been marked as failing.

Returns:

True if all failing addresses were freed, False otherwise.

Return type:

bool

async get_info() Dict[str, Any]

This function is a coroutine.

Retrieves information about this node.

Returns:

A raw response containing information about the node.

Return type:

Dict[str, Any]

async get_stats() Dict[str, Any]

This function is a coroutine.

Retrieves statistics about this node.

Returns:

A raw response containing information about the node.

Return type:

Dict[str, Any]

async get_version() str

This function is a coroutine.

Retrieves the version of this node.

Returns:

The version of this Lavalink server.

Return type:

str

async get_player(guild_id: str | int) Dict[str, Any]

This function is a coroutine.

Retrieves a player from the node. This returns raw data, to retrieve a player you can interact with, use PlayerManager.get().

Returns:

A raw player object.

Return type:

Dict[str, Any]

async get_players() List[Dict[str, Any]]

This function is a coroutine.

Retrieves a list of players from the node. This returns raw data, to retrieve players you can interact with, use players.

Returns:

A list of raw player objects.

Return type:

List[Dict[str, Any]]

async update_player(*, guild_id: str | int, encoded_track: str | None = ..., no_replace: bool = ..., position: int = ..., end_time: int = ..., volume: int = ..., paused: bool = ..., filters: List[Filter] | None = ..., voice_state: Dict[str, Any] = ..., user_data: Dict[str, Any] = ..., **kwargs) Dict[str, Any] | None
async update_player(*, guild_id: str | int, identifier: str = ..., no_replace: bool = ..., position: int = ..., end_time: int = ..., volume: int = ..., paused: bool = ..., filters: List[Filter] | None = ..., voice_state: Dict[str, Any] = ..., user_data: Dict[str, Any] = ..., **kwargs) Dict[str, Any] | None
async update_player(*, guild_id: str | int, no_replace: bool = ..., position: int = ..., end_time: int = ..., volume: int = ..., paused: bool = ..., filters: List[Filter] | None = ..., voice_state: Dict[str, Any] = ..., user_data: Dict[str, Any] = ..., **kwargs) Dict[str, Any] | None

This function is a coroutine.

Update the state of a player.

Warning

If this function is called directly, rather than through, e.g. a player, the internal state is not guaranteed! This means that any attributes accessible through other classes may not correspond with those stored in, or provided by the server. Use with caution!

Parameters:
  • guild_id (Union[str, int]) – The guild ID of the player to update.

  • encoded_track (Optional[str]) –

    The base64-encoded track string to play. You may provide None to stop the player.

    Warning

    This option is mutually exclusive with identifier. You cannot provide both options.

  • identifier (str) –

    The identifier of the track to play. This can be a track ID or URL. It may not be a search query or playlist link. If it yields a search, playlist, or no track, a RequestError will be raised.

    Warning

    This option is mutually exclusive with encoded_track. You cannot provide both options.

  • no_replace (bool) – Whether to replace the currently playing track (if one exists) with the new track. Only takes effect if identifier or encoded_track is provided. This parameter will only take effect when a track is provided.

  • position (int) – The track position in milliseconds. This can be used to seek.

  • end_time (int) – The position, in milliseconds, to end the track at.

  • volume (int) – The new volume of the player. This must be within the range of 0 to 1000.

  • paused (bool) – Whether to pause the player.

  • filters (Optional[List[Filter]]) – The filters to apply to the player. Specify None or [] to clear.

  • voice_state (Dict[str, Any]) – The new voice state of the player.

  • user_data (Dict[str, Any]) – The user data to attach to the track, if one is provided. This parameter will only take effect when a track is provided.

  • **kwargs (Any) – The kwargs to use when updating the player. You can specify any extra parameters that may be used by plugins, which offer extra features not supported out-of-the-box by Lavalink.py.

Returns:

The raw player update response object, or None , if a request wasn’t made due to an empty payload.

Return type:

Optional[Dict[str, Any]]

async destroy_player(guild_id: str | int) bool

This function is a coroutine.

Destroys a player on the node. It’s recommended that you use PlayerManager.destroy() to destroy a player.

Returns:

Whether the player was destroyed.

Return type:

bool

async update_session(resuming: bool = ..., timeout: int = ...) Dict[str, Any] | None

This function is a coroutine.

Update the session for this node.

Parameters:
  • resuming (bool) – Whether to enable resuming for this session.

  • timeout (int) – How long the node will wait for the session to resume before destroying it, in seconds.

Returns:

A raw response from the node containing the current session configuration, or None if a request wasn’t made due to an empty payload.

Return type:

Optional[Dict[str, Any]]

async request(method: str, path: str, *, to: Type[str], trace: bool = False, versioned: bool = True, **kwargs) str
async request(method: str, path: str, *, to: Type[T], trace: bool = False, versioned: bool = True, **kwargs) T
async request(method: str, path: str, *, trace: bool = False, versioned: bool = True, **kwargs) Dict[Any, Any] | List[Any] | bool

This function is a coroutine.

Makes a HTTP request to this node. Useful for implementing functionality offered by plugins on the server.

Parameters:
  • method (str) – The HTTP method for this request.

  • path (str) – The path for this request. E.g. sessions/{session_id}/players/{guild_id}.

  • to (Optional[Type[T]]) –

    The class to deserialize the response into.

    Warning

    The provided class MUST implement a classmethod called from_dict that accepts a dict or list object!

    Example:

    @classmethod
    def from_dict(cls, res: Union[Dict[Any, Any], List[Any]]):
        return cls(res)
    

  • trace (bool) – Whether to enable trace logging for this request. This will return a more detailed error if the request fails, but could bloat log files and reduce performance if left enabled.

  • versioned (bool) – Whether this request should target a versioned route. For the majority of requests, this should be set to True. This will prepend the route with the latest API version this client supports, e.g. v4/.

  • **kwargs (Any) – Any additional arguments that should be passed to aiohttp. This could be parameters like json, params etc.

Raises:
  • AuthenticationError – If the provided authorization was invalid.

  • RequestError – If the request was unsuccessful.

  • ClientError – If there were any intermediate issues, such as trying to establish a connection but the server is unreachable.

Returns:

  • T or str if the to parameter was specified and either value provided.

  • The raw JSON response (Dict[Any, Any] or List[Any]) if to was not provided.

  • A bool, if the returned status code was 204. A value of True should typically mean the request was successful.

Return type:

Union[T, str, bool, Dict[Any, Any], List[Any]]

Node Manager

class lavalink.NodeManager(client, regions: Dict[str, Tuple[str]] | None, connect_back: bool)

Represents the node manager that contains all lavalink nodes.

len(x):

Returns the total number of nodes.

iter(x):

Returns an iterator of all the stored nodes.

client

The Lavalink client.

Type:

Client

nodes

Cache of all the nodes that Lavalink has created.

Type:

List[Node]

regions

A mapping of continent -> Discord RTC regions.

Type:

Dict[str, Tuple[str]]

property available_nodes: List[Node]

Returns a list of available nodes.

Deprecated since version 5.0.0: As of Lavalink server 4.0.0, a WebSocket connection is no longer required to operate a node. As a result, this property is no longer considered useful as all nodes are considered available.

add_node(host: str, port: int, password: str, region: str, name: str | None = None, ssl: bool = False, session_id: str | None = None, connect: bool = True) Node

Adds a node to this node manager.

Parameters:
  • host (str) – The address of the Lavalink node.

  • port (int) – The port to use for websocket and REST connections.

  • password (str) – The password used for authentication.

  • region (str) – The region to assign this node to.

  • name (Optional[str]) – An identifier for the node that will show in logs. Defaults to None.

  • ssl (bool) – Whether to use SSL for the node. SSL will use wss and https, instead of ws and http, respectively. Your node should support SSL if you intend to enable this, either via reverse proxy or other methods. Only enable this if you know what you’re doing.

  • session_id (Optional[str]) – The ID of the session to resume. Defaults to None. Only specify this if you have the ID of the session you want to resume.

  • connect (bool) – Whether to immediately connect to the node after creating it. If False, you must call Node.connect() if you require WebSocket functionality.

Returns:

The created Node instance.

Return type:

Node

remove_node(node: Node)

Removes a node.

Make sure you have called Node.destroy() to close any resources used by this Node.

Deprecated since version 5.2.0: To be consistent with function naming, this method has been deprecated in favour of remove().

Parameters:

node (Node) – The node to remove from the list.

remove(node: Node)

Removes a node.

Make sure you have called Node.destroy() to close any resources used by this Node.

Parameters:

node (Node) – The node to remove from the list.

get_nodes_by_region(region_key: str) List[Node]

Get a list of nodes by their region. This does not account for node availability, so the nodes returned could be either available or unavailable.

Parameters:

region_key (str) – The region key. If you haven’t specified your own regions, this will be one of asia, eu or us, otherwise, it’ll be one of the keys within the dict you provided.

Returns:

A list of nodes. Could be empty if no nodes were found with the specified region key.

Return type:

List[Node]

get_region(endpoint: str) str | None

Returns a Lavalink.py-friendly region from a Discord voice server address.

Parameters:

endpoint (str) – The address of the Discord voice server.

Return type:

Optional[str]

find_ideal_node(region: str | None = None, exclude: List[Node] | None = None) Node | None

Finds the best (least used) node in the given region, if applicable.

Parameters:
  • region (Optional[str]) – The region to find a node in. Defaults to None.

  • exclude (Optional[List[Node]]) – A list of nodes to exclude from the choice.

Return type:

Optional[Node]

Player Manager

class lavalink.PlayerManager(client, player: Type[PlayerT])

Represents the player manager that contains all the players.

len(x):

Returns the total number of stored players.

iter(x):

Returns an iterator of all the stored players.

client

The Lavalink client.

Type:

Client

players

Cache of all the players that Lavalink has created.

Type:

Dict[int, BasePlayer]

values() Iterator[PlayerT]

Returns an iterator that yields only values.

find_all(predicate: Callable[[PlayerT], bool] | None = None)

Returns a list of players that match the given predicate.

Parameters:

predicate (Optional[Callable[[:class:BasePlayer], bool]]) – A predicate to return specific players. Defaults to None.

Returns:

This could be a DefaultPlayer if no custom player implementation was provided.

Return type:

List[BasePlayer]

get(guild_id: int) PlayerT | None

Gets a player from cache.

Parameters:

guild_id (int) – The guild_id associated with the player to get.

Returns:

This could be a DefaultPlayer if no custom player implementation was provided.

Return type:

Optional[BasePlayer]

remove(guild_id: int)

Removes a player from the internal cache.

Parameters:

guild_id (int) – The player to remove from cache.

create(guild_id: int, *, region: str | None = None, endpoint: str | None = None, node: Node | None = None) PlayerT
create(guild_id: int, *, region: str | None = None, endpoint: str | None = None, node: Node | None = None, cls: Type[CustomPlayerT]) CustomPlayerT

Creates a player if one doesn’t exist with the given information.

If node is provided, a player will be created on that node. If region is provided, a player will be created on a node in the given region. If endpoint is provided, Lavalink.py will attempt to parse the region from the endpoint and return a node in the parsed region.

If node, region and endpoint are left unspecified, or region/endpoint selection fails, Lavalink.py will fall back to the node with the lowest penalty.

Region can be omitted if node is specified and vice-versa.

Parameters:
  • guild_id (int) – The guild_id to associate with the player.

  • region (Optional[str]) – The region to use when selecting a Lavalink node. Defaults to None.

  • endpoint (Optional[str]) – The address of the Discord voice server. Defaults to None.

  • node (Optional[Node]) – The node to put the player on. Defaults to None, which selects the node with the lowest penalty.

  • cls (Optional[Type[BasePlayer]]) –

    The player class to use when instantiating a new player. Defaults to None which uses the player class provided to Client. If no class was provided, this will typically be DefaultPlayer.

    Warning

    This function could return a player of a different type to that specified in cls, if a player was created before with a different class type.

Raises:

ValueError – If the provided cls is not a valid subclass of BasePlayer.

Returns:

A class that inherits BasePlayer. By default, the actual class returned will be DefaultPlayer, however if you have specified a custom player implementation, then this will be different.

Return type:

BasePlayer

async destroy(guild_id: int)

This function is a coroutine.

Removes a player from cache, and also Lavalink if applicable. Ensure you have disconnected the given guild_id from the voicechannel first, if connected.

Warning

This should only be used if you know what you’re doing. Players should never be destroyed unless they have been moved to another Node.

Parameters:

guild_id (int) – The guild_id associated with the player to remove.

Stats

class lavalink.Stats(node, data)

Encapsulates the ‘Statistics’ emitted by Lavalink, usually every minute.

is_fake

Whether or not the stats are accurate. This should only be True when the node has not yet received any statistics from the Lavalink server.

Type:

bool

uptime

How long the node has been running for, in milliseconds.

Type:

int

players

The number of players connected to the node.

Type:

int

playing_players

The number of players that are playing in the node.

Type:

int

memory_free

The amount of memory free to the node, in bytes.

Type:

int

memory_used

The amount of memory that is used by the node, in bytes.

Type:

int

memory_allocated

The amount of memory allocated to the node, in bytes.

Type:

int

memory_reservable

The amount of memory reservable to the node, in bytes.

Type:

int

cpu_cores

The amount of cpu cores the system of the node has.

Type:

int

system_load

The overall CPU load of the system. This is a number between 0-1, but can be multiplied by 100 for the percentage (0-100).

Type:

float

The CPU load generated by Lavalink This is a number between 0-1, but can be multiplied by 100 for the percentage (0-100).

Type:

float

frames_sent

The number of frames sent to Discord.

Warning

Given that audio packets are sent via UDP, this number may not be 100% accurate due to packets dropped in transit.

Type:

int

frames_nulled

The number of frames that yielded null, rather than actual data.

Type:

int

frames_deficit

The number of missing frames. Lavalink generates this figure by calculating how many packets to expect per minute, and deducting frames_sent. Deficit frames could mean the CPU is overloaded, and isn’t generating frames as quickly as it should be.

Type:

int

penalty
Type:

Penalty

class lavalink.Penalty(stats)

Represents the penalty of the stats of a Node.

player_penalty

The number of playing players. 1 player = 1 penalty point.

Type:

int

cpu_penalty

The penalty incurred from system CPU usage.

Type:

float

null_frame_penalty

The penalty incurred from the average number of null frames per minute.

Type:

float

deficit_frame_penalty

The penalty incurred from the average number of deficit frames per minute.

Type:

float

total

The overall penalty, as a sum of all other penalties.

Type:

float

Utilities

lavalink.timestamp_to_millis(timestamp: str) int

Converts a timestamp such as 03:28 or 02:15:53 to milliseconds.

Example

await player.play(track, start_time=timestamp_to_millis('01:13'))
Parameters:

timestamp (str) – The timestamp to convert into milliseconds.

Returns:

The millisecond value of the timestamp.

Return type:

int

lavalink.format_time(time: int) str

Formats the given time into HH:MM:SS.

Parameters:

time (int) – The time in milliseconds.

Return type:

str

lavalink.parse_time(time: int) Tuple[float, float, float, float]

Parses the given time into days, hours, minutes and seconds. Useful for formatting time yourself.

Parameters:

time (int) – The time in milliseconds.

Return type:

Tuple[float, float, float, float]

lavalink.decode_track(track: str, source_decoders: Mapping[str, Callable[[DataReader], Mapping[str, Any]]] = ...) AudioTrack

Decodes a base64 track string into an AudioTrack object.

Parameters:
  • track (str) – The base64 track string.

  • source_decoders (Mapping[str, Callable[[DataReader], Dict[str, Any]]]) –

    A mapping of source-specific decoders to use. Some Lavaplayer sources have additional fields encoded on a per-source manager basis, so you can specify a mapping of decoders that will handle decoding these additional fields. You can find some example decoders within the source_decoders file. This isn’t required for all sources, so ensure that you need them before specifying.

    To overwrite library-provided decoders, just specify them within the mapping and the new decoders will be used.

Return type:

AudioTrack

lavalink.encode_track(track: Dict[str, Any], source_encoders: Mapping[str, Callable[[DataWriter, Dict[str, Any]], None]] = ...) Tuple[int, str]

Encodes a track dict into a base64 string, readable by the Lavalink server.

A track should have at least the following keys: title, author, length, identifier, isStream, uri, sourceName and position.

If the track is a v3 track, it should have the following additional fields: artworkUrl and isrc. isrc can be None if not applicable.

Parameters:
  • track (Dict[str, Union[Optional[str], int, bool]]) – The track dict to serialize.

  • source_encoders (Mapping[str, Callable[[DataWriter]]) –

    A mapping of source-specific encoders to use. Some Lavaplayer sources have additional fields encoded on a per-source manager basis, so you can specify a mapping of encoders that will handle encoding these additional fields. This isn’t required for all sources, so ensure that you need them before specifying.

    The mapping must be in the format of something like {'http': http_encoder_function}, where the key str is the name of the source. These functions will only be called if track’s sourceName field matches.

Raises:

InvalidTrack – If the track has unexpected, or missing keys, possibly due to an incompatible version or another reason.

Returns:

A tuple containing (track_version, encoded_track). For example, if a track was encoded as version 3, the return value will be (3, '...really long track string...').

Return type:

Tuple[int, str]