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()
.
events (Event
) – The events to listen for. Leave this empty to listen for all events.
Represents the BasePlayer all players must be inherited from.
The ID of the voice channel the player is connected to.
This could be None
if the player isn’t connected.
Optional[int
]
The currently playing track.
Optional[AudioTrack
]
This function is a coroutine.
Handles an Event
received directly from the websocket.
event (Event
) – The event that will be handled.
This function is a coroutine.
Updates this player’s state with the state object received from the server.
state (Dict[str
, Any]) – The player state.
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
.
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.
The updated player object, or None
if a request wasn’t made due to an empty payload.
Optional[Dict[str
, Any]]
This function is a coroutine.
Destroys the current player instance.
Shortcut for PlayerManager.destroy()
.
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.
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.
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.
This function is a coroutine.
Loads a track with the given query.
A LoadResult, or None
if there were no matches for the provided query.
Optional[LoadResult
]
Represents a Lavalink client used to manage nodes and connections.
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.
The node manager, used for storing and managing all registered Lavalink nodes.
The player manager, used for storing and managing all players.
Convenience shortcut for NodeManager.nodes
.
Convenience shortcut for PlayerManager.players
.
This function is a coroutine.
Closes all active connections and frees any resources in use.
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()
.
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.
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()
.
cls (Any) – An instance of a class containing event hook methods.
Removes the given hooks from the event hook registry.
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.
Registers a Source
that Lavalink.py will use for looking up tracks.
source (Source
) – The source to register.
Shortcut for NodeManager.add_node()
.
Adds a node to Lavalink’s node manager.
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.
The created Node instance.
This function is a coroutine.
Searches sources
registered to this client for the given query.
query (str
) – The query to perform a search for.
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!
This function is a coroutine.
Decodes a base64-encoded track string into a dict.
This function is a coroutine.
Decodes a list of base64-encoded track strings into a list of AudioTrack
.
A list of decoded AudioTrack
.
List[AudioTrack
]
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')
data (Dict[str, Any]) – The payload received from Discord.
Reads an optional UTF string from the stream.
Internally, this just reads a bool and then a string if the bool is True
.
utfm (bool
) – Whether to read the string as modified UTF.
Optional[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.
Writes a single byte to the stream.
byte (Any) – This can be anything BytesIO.write()
accepts.
Writes a bool to the stream.
boolean (bool
) – The bool to write.
Writes an unsigned short to the stream.
short (int
) – The unsigned short to write.
Writes an int to the stream.
integer (int
) – The integer to write.
Writes a long to the stream.
long_value (int
) – The long to write.
Writes an optional string to the stream.
utf_string (Optional[str
]) – The optional string to write.
Raised when something goes wrong within the client.
Raised when a request fails due to invalid authentication.
Raised when an invalid track was passed.
Raised when a track fails to load. E.g. if a DeferredAudioTrack fails to find an equivalent.
All Events are derived from Event
The base for all Lavalink events.
This event is emitted when a track begins playing (e.g. via player.play())
The player that started to play a track.
The track that started playing.
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.
The player associated with the stuck track.
The stuck track.
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.
The player that had the exception occur while playing a track.
The track that had the exception while playing.
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.
The player that finished playing a track.
The track that finished playing.
This could be None
if Lavalink fails to encode the track.
Optional[AudioTrack
]
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.
The player responsible for playing the track.
The track that failed to produce a playable track.
This is a custom event, emitted by the DefaultPlayer
when
there are no more tracks in the queue.
The player that has no more songs in queue.
This event is emitted when a player’s progress changes.
The player that’s progress was updated.
This is a custom event, emitted when a connection to a Lavalink node is successfully established.
This is a custom event, emitted when the connection to a Lavalink node drops and becomes unavailable.
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.
The player whose node was changed.
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.
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.
The player whose audio websocket was closed.
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.
The received JSON-formatted data from the websocket.
Union[Dict[Any, Any], List[Any]]
Raised when an error occurs within a BasePlayer
.
The player in which the error occurred.
All custom filters must derive from Filter
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’.
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
Allows for isolating a frequency range (commonly, the vocal range). Useful for karaoke/sing-along.
Allows speeding up/slowing down the audio, adjusting the pitch and playback rate.
Note
The limits are:
0.1 ≤ speed
0.1 ≤ pitch
0.1 ≤ rate
Applies a ‘tremble’ effect to the audio.
Applies a ‘wobble’ effect to the audio.
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.
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.
Allows passing the audio from one channel to the other, or isolating individual channels.
Note
The limits are:
0 ≤ leftToLeft ≤ 1.0
0 ≤ leftToRight ≤ 1.0
0 ≤ rightToLeft ≤ 1.0
0 ≤ rightToRight ≤ 1.0
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.
Adjusts the audio output volume.
All custom players must derive from BasePlayer
The player that Lavalink.py uses by default.
This should be sufficient for most use-cases.
Class attribute. Enables looping for a single (usually currently playing) track only.
Class attribute. Enables looping for the entire queue. When a track finishes playing, it’ll be added to the end of the queue.
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!')
Literal[0, 1, 2]
A list of AudioTracks to play.
List[AudioTrack
]
The track that is playing currently, if any.
Optional[AudioTrack
]
Returns the track’s elapsed playback time in milliseconds, adjusted for Lavalink stat interval.
Retrieves the related value from the stored user data.
key (object
) – The key to fetch.
default (Optional[any
]) – The object that should be returned if the key doesn’t exist. Defaults to None
.
Optional[any
]
Adds a track to the queue.
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
.
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
.
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.
ValueError – If invalid values were provided for start_time
or end_time
.
TypeError – If wrong types were provided for no_replace
, volume
or pause
.
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
.
Sets whether the player loops between a single track, queue or none.
0 = off, 1 = single track, 2 = queue.
loop (Literal[0, 1, 2]) – The loop setting. 0 = off, 1 = single track, 2 = queue.
Sets the player’s shuffle state.
shuffle (bool
) – Whether to shuffle the player or not.
This function is a coroutine.
Sets the player’s paused state.
pause (bool
) – Whether to pause the player or not.
This function is a coroutine.
Sets the player’s volume
Note
A limit of 1000 is imposed by Lavalink.
vol (int
) – The new volume level.
This function is a coroutine.
Seeks to a given position in the track.
position (int
) – The new position to seek to in milliseconds.
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.
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)
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"
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')
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.
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')
Handles the given event as necessary.
event (Event
) – The event to handle.
Updates the position of the player.
state (dict
) – The state that is given to update.
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.
Represents an AudioTrack.
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.
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
.
Optional[str
]
The track’s id. For example, a youtube track’s identifier will look like dQw4w9WgXcQ
.
The playback position of the track, in milliseconds. This is a read-only property; setting it won’t have any effect.
An enumeration.
Valid values are as follows:
The Enum
and its members also have the following methods:
An enumeration.
Valid values are as follows:
An enumeration.
Valid values are as follows:
The tracks in this result.
List[Union[AudioTrack
, DeferredAudioTrack
]]
The playlist metadata for this result.
The PlaylistInfo
could contain empty/false data if the LoadType
is not LoadType.PLAYLIST
.
The error associated with this LoadResult
.
This will be None
if load_type
is not LoadType.ERROR
.
Optional[LoadResultError
]
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.
Optional[AudioTrack
]
Represents a Node connection with Lavalink.
Note
To construct a node, you should use Client.add_node()
instead.
The session ID for this node.
Could be None
if a ready event has not yet been received from the server.
Returns whether the node has a websocket connection. The node could probably still be used for HTTP requests even without a WS connection.
Returns a list of all players on this node.
List[BasePlayer
]
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.
The latency, in milliseconds. -1
if an error occurred during the request (e.g. node is unreachable),
otherwise, a positive number.
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.
force (bool
) – Whether to close any existing WebSocket connections and re-establish a connection to
the node.
The WebSocket connection task, or None
if a WebSocket connection already exists and force
is False
.
Optional[asyncio.Task
]
This function is a coroutine.
Destroys the transport and any underlying connections for this node. This will also cleanly close the websocket.
This function is a coroutine.
Retrieves a list of results pertaining to the provided query.
query (str
) – The query to perform a search for.
This function is a coroutine.
Decodes a base64-encoded track string into an AudioTrack
object.
track (str
) – The base64-encoded track string to decode.
This function is a coroutine.
Decodes a list of base64-encoded track strings into a list of AudioTrack
.
tracks (List[str
]) – A list of base64-encoded track
strings.
A list of decoded AudioTracks.
List[AudioTrack
]
This function is a coroutine.
Retrieves the status of the target node’s routeplanner.
A dict representing the routeplanner information.
Dict[str, Any]
This function is a coroutine.
Frees up the provided IP address in the target node’s routeplanner.
This function is a coroutine.
Frees up all IP addresses in the target node that have been marked as failing.
True if all failing addresses were freed, False otherwise.
This function is a coroutine.
Retrieves information about this node.
A raw response containing information about the node.
Dict[str, Any]
This function is a coroutine.
Retrieves statistics about this node.
A raw response containing information about the node.
Dict[str, Any]
This function is a coroutine.
Retrieves the version of this node.
The version of this Lavalink server.
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()
.
A raw player object.
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
.
A list of raw player objects.
List[Dict[str, Any]]
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!
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.
The raw player update response object, or None
, if a request wasn’t made due to an
empty payload.
Optional[Dict[str, Any]]
This function is a coroutine.
Destroys a player on the node.
It’s recommended that you use PlayerManager.destroy()
to destroy a player.
Whether the player was destroyed.
This function is a coroutine.
Update the session for this node.
A raw response from the node containing the current session configuration, or None
if a request wasn’t made due to an empty payload.
Optional[Dict[str, Any]]
This function is a coroutine.
Makes a HTTP request to this node. Useful for implementing functionality offered by plugins on the server.
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.
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.
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.
Represents the node manager that contains all lavalink nodes.
Returns the total number of nodes.
Returns an iterator of all the stored nodes.
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.
Adds a node to this node manager.
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.
The created Node instance.
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()
.
node (Node
) – The node to remove from the list.
Removes a node.
Make sure you have called Node.destroy()
to close any resources used by this Node.
node (Node
) – The node to remove from the list.
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.
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.
A list of nodes. Could be empty if no nodes were found with the specified region key.
List[Node
]
Returns a Lavalink.py-friendly region from a Discord voice server address.
Represents the player manager that contains all the players.
Returns the total number of stored players.
Returns an iterator of all the stored players.
Cache of all the players that Lavalink has created.
Dict[int, BasePlayer
]
Returns a list of players that match the given predicate.
predicate (Optional[Callable[[:class:BasePlayer], bool]]) – A predicate to return specific players. Defaults to None
.
This could be a DefaultPlayer
if no custom player implementation
was provided.
List[BasePlayer
]
Gets a player from cache.
guild_id (int
) – The guild_id associated with the player to get.
This could be a DefaultPlayer
if no custom player implementation
was provided.
Optional[BasePlayer
]
Removes a player from the internal cache.
guild_id (int
) – The player to remove from cache.
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.
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.
ValueError – If the provided cls
is not a valid subclass of BasePlayer
.
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.
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
.
guild_id (int) – The guild_id associated with the player to remove.
Encapsulates the ‘Statistics’ emitted by Lavalink, usually every minute.
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.
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).
The CPU load generated by Lavalink This is a number between 0-1, but can be multiplied by 100 for the percentage (0-100).
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.
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.
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'))
Parses the given time into days, hours, minutes and seconds. Useful for formatting time yourself.
Decodes a base64 track string into an AudioTrack object.
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.
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.
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.
InvalidTrack – If the track has unexpected, or missing keys, possibly due to an incompatible version or another reason.
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...')
.