lavasnek_rs
lavasnek_rs
lavalink-rs bindings for Python
Cheat Sheet:
- Functions that return a
Result<T, E>
mean that it can raise an exception.T
is the type they return normally, andE
is a list of possible exceptions that can raise. - Functions that return an
Option<T>
mean that the value returned can beNone
, whereT
would be the type of the returned value if notNone
. - If something returns a
Future<T>
, it means that it returns this, and that function should be awaited to work. - / on arguments means the end of positional arguments.
- Self (with a capital S) means the type of self.
- A type prefixed with
impl
means it's a Class that implements that Trait type.
1# -*- coding: utf-8 -*- 2""" 3lavasnek_rs 4------------------- 5lavalink-rs bindings for Python 6 7Cheat Sheet: 8 9- Functions that return a `Result<T, E>` mean that it can raise an exception. `T` is the type they 10return normally, and `E` is a list of possible exceptions that can raise. 11- Functions that return an `Option<T>` mean that the value returned can be `None`, where `T` would be 12the type of the returned value if not `None`. 13- If something returns a `Future<T>`, it means that it returns 14[this](https://docs.python.org/3/library/asyncio-future.html?#asyncio.Future), 15and that function should be awaited to work. 16- / on arguments means the end of positional arguments. 17- Self (with a capital S) means the type of self. 18- A type prefixed with `impl` means it's a Class that implements that Trait type. 19""" 20 21from .lavasnek_rs import * 22 23__version__ = "0.1.0-alpha.5" 24__author__ = "vicky5124 <vickyf5124@gmail.com>" 25__license__ = "MPL-2.0" 26 27__all__ = [ 28 "rust_sleep", 29 "log_something", 30 "Lavalink", 31 "LavalinkBuilder", 32 "PlayBuilder", 33 "LavalinkEventHandler", 34 "ConnectionInfo", 35 "Track", 36 "Tracks", 37 "TrackQueue", 38 "Info", 39 "PlaylistInfo", 40 "Node", 41 "Band", 42 "Stats", 43 "PlayerUpdate", 44 "TrackStart", 45 "TrackFinish", 46 "TrackException", 47 "TrackStuck", 48 "WebSocketClosed", 49 "PlayerDestroyed", 50 "NoSessionPresent", 51 "NetworkError", 52]
Test function, do not use.
Test function, do not use.
Start the discord gateway, if it has stopped, or it never started because the client builder was configured that way.
If wait_time
is passed, it will override the previosuly configured wait time.
Positional Arguments:
wait_time
:Optional Unsigned 64 bit integer
-- seconds
Returns: Future<None>
Joins a guild's voice channel using the lavalink-rs discord gateway.
Returns information about the gateway connection, which can be used with create_session()
to connect lavalink to that voice connection.
lavalink: lavasnek_rs.Lavalink = ...
connection_info = await lavalink.join(guild_id, voice_channel_id)
await lavalink.create_session(connection_info)
await send_message(f"Joined <#{voice_channel_id}>")
Timing out means that there's either no permission to join the voice channel, or 5 seconds have happened since the function was called.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
channel_id
:Unsigned 64 bit integer
Returns: Future<Result<ConnectionInfo, builtins.TimeoutError>>
Leaves the current guild's voice channel using the lavalink-rs discord gateway.
Lavalink.destroy()
should be ran as well before this, to safely stop the lavalink session.
lavalink: lavasnek_rs.Lavalink = ...
await lavalink.destroy(guild_id)
await lavalink.leave(guild_id)
await send_message("Left voice channel")
Timing out means that 5 seconds have happened since the function was called.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Returns: Future<Result<None, builtins.TimeoutError>>
Creates a session in Lavalink with a voice connection. This also creates a Node and inserts it.
The node is not added to the loops unless PlayBuilder.queue()
is ran.
This can raise a TypeError if a necessary field of ConnectionInfo is missing.
Positional Arguments:
connection_info
:ConnectionInfo
(obtained fromLavalink.join()
)
Returns: Future<Result<None, builtins.TypeError>>
Stops the session in Lavalink of the guild. This also creates a Node and inserts it.
This method does not remove the guild from the running event loops, nor does it clear the Node, this allows for reconnecting without losing data. If you are having issues with disconnecting and reconnecting the bot to a voice channel, remove the guild from the running event loops and reset the nodes.
lavalink.remove_guild_node(guild_id)
lavalink.remove_guild_from_loops(guild_id)
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Returns the Play builder.
lavalink: lavasnek_rs.Lavalink = ...
query_information = await lavalink.auto_search_tracks(search_query_or_url)
if not query_information["tracks"]: # tracks is empty
await send_message("Could not find any video of the search query.")
return
try:
await lavalink.play(
guild_id, query_information["tracks"][0]
).requester(author_id).queue()
except lavasnek_rs.NoSessionPresent:
await send_message(f"Use `{PREFIX}join` first")
return
Positional Arguments:
guild_id
:Unsigned 64 bit integer
track
:Track
- From the track search methods, it's a value from the "tracks" field.
Returns: PlayBuilder
Returns the tracks from the URL or query provided.
This can raise an exception if a network error happens.
Positional Arguments:
query
:String
Returns: Future<Result<Tracks, lavasnek_rs.NetworkError>>
Will automatically search the query on youtube if it's not a valid URL.
This can raise an exception if a network error happens.
Positional Arguments:
query
:String
Returns: Future<Result<Tracks, lavasnek_rs.NetworkError>>
Returns tracks from the search query. Uses youtube to search.
This can raise an exception if a network error happens.
Positional Arguments:
query
:String
Returns: Future<Result<Tracks, lavasnek_rs.NetworkError>>
Returns information from a track.
This can raise an exception if a network error happens.
Positional Arguments:
track
:String
-- base 64
Returns: Future<Result<Info, lavasnek_rs.NetworkError>>
Stops the current player.
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Skips the current playing track to the next item on the queue.
If nothing is in the queue, the currently playing track will keep playing.
Check if the queue is empty and run stop()
if that's the case.
lavalink: lavasnek_rs.Lavalink = ...
skip = await lavalink.skip(guild_id)
node = await lavalink.get_guild_node(guild_id)
if not skip:
await send_message("Nothing to skip")
else:
if not node["queue"] and not node["now_playing"]:
await lavalink.stop(guild_id)
await send_message(f"Skipped: {skip['track']['info']['title']}"
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Returns: Future<Option<TrackQueue>>
Sets the pause status.
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
pause
:bool
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Jumps to a specific time in the currently playing track.
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
time
:Unsigned 64 bit integer
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Jumps to a specific time in the currently playing track.
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
time
:Unsigned 64 bit integer
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Sets the volume of the player. Max is 1000, min is 0
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Volume
:Unsigned 16 bit integer
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Sets all equalizer levels.
- There are 15 bands (0-14) that can be changed.
- The floating point value is the multiplier for the given band.
- The default value is 0.
- Valid values range from -0.25 to 1.0, where -0.25 means the given band is completely muted, and 0.25 means it is doubled.
- Modifying the gain could also change the volume of the output.
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
bands
:List<64 bit floating point>
-- Must be 15 in length
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Equalize a dynamic set of bands, rather than just one or all of them at once.
Unmentioned bands will remain unmodified.
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
bands
:List<64 bit floating point>
-- Must be 15 or less in length
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Equalizes a specific band.
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
band
:Band
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Resets all equalizer levels.
This can raise an exception if a network error happens.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Remove the guild from the queue loops.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Returns: Future<None>
Remove the guild node.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Returns: Future<None>
Get the current guild from the queue nodes.
This returns a clone of the node, so modifying it won't change the real node, for that you
will need to re-set the new node with set_guild_node()
.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Returns: Future<Option<Node>>
Set the node of a guild with a new one.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
node
:Node
Returns: Future<None>
Get the current guild from the queue nodes.
This returns a clone of the value, modifying it won't change it internally.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
Returns: Option<ConnectionInfo>
Waits until the ConnectionInfo is complete and returns it.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
event_count
:Unsigned 128 bit integer
defaults to 10
Returns: Future<ConnectionInfo>
Waits until the ConnectionInfo is removed.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
event_count
:Unsigned 128 bit integer
defaults to 10
Returns: Future<None>
Handles voice events to manage ConnectionInfo
internally. This one is for the
VOICE_SERVER_UPDATE event.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
endpint
:String
token
:String
Returns: Future<None>
Handles voice events to manage ConnectionInfo
internally. This one is for the
VOICE_STATE_UPDATE event.
Positional Arguments:
guild_id
:Unsigned 64 bit integer
user_id
:Unsigned 64 bit integer
session_id
:String
channel_id
:Optional Unsigned 64 bit integer
Returns: None
__new__()
All of the methods that return Self also modify Self, so you can chain them, or call the individually.
Positional Arguments:
bot_id
:Unsigned 64 bit integer
bot_token
:String
Returns: Self
Uses the Self data to build a Lavalink client and return it.
Can raise an exception if it's unable to connect to the lavalink server, discord server, or both.
Positional Arguments:
event_handler
:impl LavalinkEventHandler
Returns: Future<Result<Lavalink, builtins.ConnectionError>>
Sets the host. (Default to: 127.0.0.1)
Positional Arguments:
host
:String
Returns: Self
Sets the port. (Default to: 2333)
Positional Arguments:
port
:Unsigned 16 bit integer
Returns: Self
Sets the host and port from an address.
Can raise an exception if the address is an invalid IPv4 or IPv6.
Positional Arguments:
address
:String
Returns: Result<Self, ipaddress.AddressValueError>
Sets the lavalink password. (Default to: "youshallnotpass")
Positional Arguments:
password
:String
Returns: Self
Sets the number of shards. (Default to: 1)
Positional Arguments:
shard_count
:Unsigned 64 bit integer
Returns: Self
Sets the ID of the bot.
Positional Arguments:
bot_id
:Unsigned 64 bit integer
Returns: Self
Sets the token of the bot.
Positional Arguments:
bot_token
:String
Returns: Self
Sets if the lavalink server is behind SSL. (Default to: False)
Positional Arguments:
is_ssl
:bool
Returns: Self
Sets if the discord gateway for voice connections should start or not. (Default to: True)
Positional Arguments:
start_gateway
:bool
Returns: Self
Starts playing the track.
Returns: Future<Result<None, lavasnek_rs.NetworkError>>
Adds the track to the node queue.
If there's no queue loop running, this will start one up, and add it to the running loops
on Lavalink.loops()
Needs for `Lavalink.create_session() to be called first.
Returns: Future<Result<None, [lavasnek_rs.NoSessionPresent, lavasnek_rs.NetworkError]>>
Generates a TrackQueue from the builder.
Returns: TrackQueue
Sets the person that requested the song
Positional Arguments:
requester
:Unsigned 64 bit integer
(User ID)
Returns: Self
Sets if the current playing track should be replaced with this new one.
Positional Arguments:
replace
:bool
Returns: Self
Sets the time the track will start at in seconds.
Positional Arguments:
start
:Unsigned 64 bit integer
Returns: Self
Sets the time the track will finish at in seconds.
Positional Arguments:
finish
:Unsigned 64 bit integer
Returns: Self
Sets the time the track will start at in milliseconds.
Positional Arguments:
start
:Unsigned 64 bit integer
Returns: Self
The lavalink event handler. This is a trait, so it defines the structure a class should have.
Make a class with the methods and signatures this class defines, and add that class to
LavalinkBuilder.build()
If code inside any of the event raises an error, the traceback will be printed to stderr, and
the variables sys.last_type
, sys.last_value
and sys.last_traceback
will be set to the type, value
and traceback of the printed exception respectively.
Some examples:
# Just a single event
class EventHandler:
async def track_start(self, lava_client, event):
print(event)
lavalink_client = await client_builder.build(EventHandler)
# No events
class EventHandler:
pass
lavalink_client = await client_builder.build(EventHandler)
# Just a single event
class EventHandler:
async def stats(self, lava_client, event):
print(event)
async def player_update(self, lava_client, event):
print(event)
async def track_start(self, lava_client, event):
print(event)
async def track_finish(self, lava_client, event):
print(event)
async def track_exception(self, lava_client, event):
print(event)
async def track_stuck(self, lava_client, event):
print(event)
async def websocket_closed(self, lava_client, event):
print(event)
async def player_destroyed(self, lava_client, event):
print(event)
lavalink_client = await client_builder.build(EventHandler)
Event that triggers when a player updates.
Positional Arguments:
client
:Lavalink
event
:PlayerUpdate
Returns: Future<None>
Event that triggers when a track starts playing.
Positional Arguments:
client
:Lavalink
event
:TrackStart
Returns: Future<None>
Event that triggers when a track finishes playing.
Positional Arguments:
client
:Lavalink
event
:TrackFinish
Returns: Future<None>
Event that triggers when a track raises an exception on the Lavalink server.
Positional Arguments:
client
:Lavalink
event
:TrackException
Returns: Future<None>
Event that triggers when a track gets stuck while playing.
Positional Arguments:
client
:Lavalink
event
:TrackStuck
Returns: Future<None>
Event that triggers when the websocket connection to the voice channel closes.
Positional Arguments:
client
:Lavalink
event
:WebSocketClosed
Returns: Future<None>
Event that triggers when the player gets destroyed on a guild.
Positional Arguments:
client
:Lavalink
event
:PlayerDestroyed
Returns: Future<None>
If you use a 3rd party method of joining a voice channel, you can get the values
required for this from the VOICE_STATE_UPDATE
and
VOICE_SERVER_UPDATE
events, and use raw_handle_event_voice_state_update() +
raw_handle_event_voice_server_update() or manually build a dict with them, and use
ConnectionInfo({ ... })
With hikari:
@bot.listen()
async def voice_state_update(event: hikari.VoiceStateUpdateEvent) -> None:
await bot.data.lavalink.raw_handle_event_voice_state_update(
event.state.guild_id,
event.state.user_id,
event.state.session_id,
event.state.channel_id,
)
@bot.listen()
async def voice_server_update(event: hikari.VoiceServerUpdateEvent) -> None:
await bot.data.lavalink.raw_handle_event_voice_server_update(
event.guild_id, event.endpoint, event.token
)
Fields:
guild_id
:Unsigned 64 bit integer
channel_id
:Unsigned 64 bit integer
endpoint
:String
token
:String
session_id
:String
Information about the playlist.
Contains Option<PlaylistInfo>
The user id who requested the track if set by the PlayBuilder
Contains Option<Unsigned 64 bit integer>
__new__()
Arguments:
length
:Unsigned 64 bit integer
position
:Unsigned 64 bit integer
is_seekable
:bool
is_stream
:bool
identifier
:str
author
:str
title
:str
uri
:str
Returns: Self
Use this to get the currently stored data on the Node.
T
is whatever type you give to set_data
's data parameter, but if you call this method before it,
it will default to a Dict.
Returns T
See Lavalink.equalize_all
for more info.
band_num: int = 14 # 0 to 14
bain: float = 0.125 # -0.25 to 1.0
band = Band(band_num, gain)
Common base class for all non-exit exceptions.
Inherited Members
- builtins.Exception
- Exception
- builtins.BaseException
- with_traceback
- args
Common base class for all non-exit exceptions.
Inherited Members
- builtins.Exception
- Exception
- builtins.BaseException
- with_traceback
- args