Andesite clients

Combined client

Combined client for Andesite.

This client combines the WebSocket and HTTP clients.

There is the ClientBase which is simply the implementation of AbstractWebSocket and AbstractHTTP and then there is the actual client Client.

You can use the combined client for everything that implements the abstract methods. This means that you can use the combined client for ClientPool clients!

class ClientBase(http_client, web_socket_client)[source]

Implementation of AbstractWebSocket and AbstractHTTP.

Parameters
  • http_client (AbstractHTTP) – Client to use for the http endpoints.

  • web_socket_client (AbstractWebSocket) – Client to use for the web socket communication.

The event_target of the web socket client is set to the combined client.

This class implements AbstractWebSocketClient if the underlying web socket client is an instance of it. However, an isinstance check will always return False. If the underlying client is not an instance of AbstractWebSocketClient, all related methods will return None.

http

HTTP client which is used for the AbstractAndesiteHTTP methods.

Type

AbstractHTTP

web_socket

WebSocket client which is used for the AbstractAndesiteWebSocket methods.

Type

AbstractWebSocket

property closed

Whether this client is closed and can no longer be used.

This is True if either of the underlying clients is closed.

Return type

bool

property state

State handler for the client.

You may manually set this value to a different state handler which implements the AbstractState. You can also disable state handling by setting it to False. Note that this won’t apply the state to the client! You can use the load_player_state method do load individual player states.

If not state is set the getter either returns the current instance, if it happens to implement AbstractState, otherwise it returns None.

Return type

Optional[AbstractState]

property connected

Whether the web socket client is connected and usable.

This method returns None if the web socket client isn’t a AbstractWebSocketClient.

Return type

Optional[bool]

property connection_id

Connection id of the web socket client.

This method returns None if the web socket client isn’t a AbstractWebSocketClient.

Return type

Optional[str]

async connect(*, max_attempts=None)[source]

Connect the underlying web socket client.

Parameters

max_attempts (Optional[int]) – Amount of connection attempts to perform before aborting. If None, unlimited attempts will be performed.

This method doesn’t do anything if the web socket client isn’t a AbstractWebSocketClient.

Return type

None

async disconnect()[source]

Disconnect the underlying web socket client.

This method doesn’t do anything if the web socket client isn’t a AbstractWebSocketClient.

Return type

None

async send(guild_id, op, payload)[source]

Send a message using the web socket client.

See also

Refer to AbstractWebSocket.send for the documentation.

Return type

None

add_child(emitter)

Add a child emitter.

Parameters

emitter (ChildEmitterABC[~T]) – Child emitter to add.

Raises

ValueError – If the child emitter already is a child of this emitter, or the emitter is a child of the child emitter. The second case is only possible if the child emitter is itself an instance of EmitterABC.

Return type

None

async close()[source]

Close the underlying clients.

This closes both the http and the web socket client. Since the close method shouldn’t raise an exception anyway, all exceptions are suppressed. This ensures that both clients’ close methods are called.

Return type

None

emit(event)

Emit an event to all observers.

The order in which the observers receive the events isn’t defined and shouldn’t be depended upon.

If a listener raises an error, a ListenerError event is emitted. If an error occurs while handling the ListenerError event, it is ignored.

event

Event object to emit

Return type

Awaitable[None]

Returns

asyncio.Future which resolves to None after all observers have handled the event.

property event_target

Event target to send events to.

If no event target is set, but the instance is itself an event target, self is set as the new event target and returned, otherwise a new event target is created.

Return type

Observable[~T]

has_child(emitter)

Check whether the child emitter is a child of the emitter.

Parameters

emitter (ChildEmitterABC[~T]) – Emitter to check.

Return type

bool

Returns

Whether or not the given emitter is either a direct, or an indirect (child of a child) child of this emitter. Note that every emitter is a child of itself.

async load_player_state(player_state)

Load a player state.

Parameters

player_state (AbstractPlayerState) – State to load.

Return type

None

off(event=None, callback=None)

Disable an event listener or remove all listeners from an event.

This can also be used to disable a listener that was added using once before it is called.

To remove all listeners from an event, pass the event selector to the event keyword argument:

class MyEvent:
    ...

observable.off(event=MyEvent)

To remove a listener which is listening to all events, pass the listener to the callback keyword argument:

def on_any_event(event):
    print(event)

observable.off(callback=on_any_event)
Parameters
  • event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. This can be the type of a single event or a tuple of multiple events to remove the listeners for.

  • callback (Optional[Callable[[~T], Union[None, Awaitable[None]]]]) – Event listener. This is the same callable that was passed to on or once.

Return type

None

on(event=None, callback=None)

Add a listener to the given event(s).

If you want to listen to all events you can pass the callback to the callback keyword argument:

def on_any_event(event):
    print(event)

observable.on(callback=on_any_event)
Parameters
  • event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. This can be the type of a single event or a tuple of multiple events to listen for. The latter case is equivalent to calling on for each event separately.

  • callback (Optional[Callable[[~T], Union[None, Awaitable[None]]]]) – Callable to call when the selected events are emitted. It is called with the event instance as its only argument. If it returns an Awaitable (or is a coroutine) it is awaited before the emission “completes” (See ChildEmitterABC.emit).

Return type

None

once(event=None, callback=None)

Add a listener which is only called once.

This is basically the same as adding the listener using on and then calling off once the listener has been called.

Parameters
  • event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. This can be the type of a single event or a tuple of multiple events to listen for.

  • callback (Optional[Callable[[~T], Union[None, Awaitable[None]]]]) – Callable to call when the selected events are emitted. It is called with the event instance as its only argument. If it returns an Awaitable (or is a coroutine) it is awaited before the emission “completes” (See ChildEmitterABC.emit).

Return type

None

remove_child(emitter)

Remove a child emitter.

Parameters

emitter (ChildEmitterABC[~T]) – Child emitter to remove.

Raises

ValueError – If the emitter isn’t a direct child.

Return type

None

async send_operation(guild_id, operation)

Send a SendOperation.

Parameters
  • guild_id (int) – Target guild id

  • operation (SendOperation) – Operation to send

Notes

Using SendOperation instances to send messages is slightly less efficient than calling the respective WebSocket methods directly.

Return type

None

subscribe(event=None)

Subscribe to the given event(s).

Parameters

event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. Event type or multiple event types to subscribe to. Can be None which will subscribe to all events.

Return type

SubscriptionABC[~T]

Returns

A subscription which is subscribed to the selected events.

async reset()[source]

Reset the underlying clients so they may be used again.

This has the opposite effect of the close method making the clients usable again.

Return type

None

async request(method, path, **kwargs)[source]

Perform a request on the http client.

See also

Refer to AbstractHTTP.request for the documentation.

Return type

Any

class Client(http_client, web_socket_client)[source]

Andesite client which combines the web socket with the http client.

Parameters
  • http_client (AbstractHTTP) – Client to use for the http endpoints.

  • web_socket_client (AbstractWebSocket) – Client to use for the web socket communication.

This class implements AbstractWebSocketClient if the underlying web socket client is an instance of it. However, an isinstance check will always return False. If the underlying client is not an instance of AbstractWebSocketClient, all related methods will return None.

http

HTTP client which is used for the AbstractHTTP methods.

Type

AbstractHTTP

web_socket

WebSocket client which is used for the AbstractWebSocket methods.

Type

AbstractWebSocket

add_child(emitter)

Add a child emitter.

Parameters

emitter (ChildEmitterABC[~T]) – Child emitter to add.

Raises

ValueError – If the child emitter already is a child of this emitter, or the emitter is a child of the child emitter. The second case is only possible if the child emitter is itself an instance of EmitterABC.

Return type

None

async close()

Close the underlying clients.

This closes both the http and the web socket client. Since the close method shouldn’t raise an exception anyway, all exceptions are suppressed. This ensures that both clients’ close methods are called.

Return type

None

property closed

Whether this client is closed and can no longer be used.

This is True if either of the underlying clients is closed.

Return type

bool

async connect(*, max_attempts=None)

Connect the underlying web socket client.

Parameters

max_attempts (Optional[int]) – Amount of connection attempts to perform before aborting. If None, unlimited attempts will be performed.

This method doesn’t do anything if the web socket client isn’t a AbstractWebSocketClient.

Return type

None

property connected

Whether the web socket client is connected and usable.

This method returns None if the web socket client isn’t a AbstractWebSocketClient.

Return type

Optional[bool]

property connection_id

Connection id of the web socket client.

This method returns None if the web socket client isn’t a AbstractWebSocketClient.

Return type

Optional[str]

async decode_track(track)

Get the TrackInfo from the encoded track data.

Notes

If you find yourself using this method a lot, you might want to use lptrack which can decode and encode the track data locally.

Parameters

track (str) – base 64 encoded track data to decode.

Return type

Optional[TrackInfo]

Returns

TrackInfo of the provided data, None if the data is invalid. Note that this method doesn’t raise HTTPError! If you need the HTTPError to be raised, use decode_tracks.

See also

Please use decode_tracks if you need to decode multiple encoded strings at once!

async decode_tracks(tracks)

Get the TrackInfo from multiple encoded track data strings.

Parameters

tracks (Iterable[str]) – Iterable of base 64 encoded track data to decode.

Return type

List[TrackInfo]

Returns

List of TrackInfo in order of the provided tracks.

Raises

HTTPError – If Andesite returns an error.

async destroy(guild_id)

Destroy a player.

Parameters

guild_id (int) – ID of the guild for which to destroy the player

Return type

None

async disconnect()

Disconnect the underlying web socket client.

This method doesn’t do anything if the web socket client isn’t a AbstractWebSocketClient.

Return type

None

emit(event)

Emit an event to all observers.

The order in which the observers receive the events isn’t defined and shouldn’t be depended upon.

If a listener raises an error, a ListenerError event is emitted. If an error occurs while handling the ListenerError event, it is ignored.

event

Event object to emit

Return type

Awaitable[None]

Returns

asyncio.Future which resolves to None after all observers have handled the event.

property event_target

Event target to send events to.

If no event target is set, but the instance is itself an event target, self is set as the new event target and returned, otherwise a new event target is created.

Return type

Observable[~T]

async filters(guild_id, filter_update=None, *, equalizer=None, karaoke=None, timescale=None, tremolo=None, vibrato=None, volume=None, **custom_filters)

Configure the filters of a player.

Parameters
  • guild_id (int) – ID of the guild for which to configure the filters

  • filter_update (Optional[FilterMap]) – Instead of specifying the other keyword arguments you may provide a FilterMap operation which will be used instead.

  • equalizer (Optional[Equalizer]) – Equalizer filter settings

  • karaoke (Optional[Karaoke]) – Karaoke filter settings

  • timescale (Optional[Timescale]) – Timescale filter settings

  • tremolo (Optional[Tremolo]) – Tremolo filter settings

  • vibrato (Optional[Vibrato]) – Vibrato filter settings

  • volume (Optional[VolumeFilter]) – Volume filter settings

  • **custom_filters – Ability to specify additional filters that aren’t supported by the library.

Return type

None

async get_player(guild_id)

Get the player.

Parameters

guild_id (int) – Target guild id

Return type

Optional[Player]

Returns

Player state for the guild. This may be None if no player is available yet.

async get_stats(guild_id)

Get the Andesite stats.

Parameters

guild_id (int) – Target guild id

Return type

Stats

Returns

Statistics for the node

has_child(emitter)

Check whether the child emitter is a child of the emitter.

Parameters

emitter (ChildEmitterABC[~T]) – Emitter to check.

Return type

bool

Returns

Whether or not the given emitter is either a direct, or an indirect (child of a child) child of this emitter. Note that every emitter is a child of itself.

async load_player_state(player_state)

Load a player state.

Parameters

player_state (AbstractPlayerState) – State to load.

Return type

None

async load_tracks(identifier)

Load tracks.

Parameters

identifier (str) – Identifier to load. The identifier isn’t handled in any way so it supports the search syntax for example.

Raises

HTTPError – If Andesite returns an error.

See also

search_tracks to search for a track using a query.

Return type

LoadedTrack

async load_tracks_safe(uri)

Load tracks from url.

This is different from load_tracks insofar that it ignores special markers such as “ytsearch:” and treats the given uri as nothing but that.

Parameters

uri (str) – URI to load

Raises

HTTPError – If Andesite returns an error.

See also

load_tracks to load a track using an identifier. search_tracks to search for a track using a query.

Return type

LoadedTrack

async mixer(guild_id, enable=None, **players)

Configure the mixer player.

Parameters
  • guild_id (int) – ID of the guild for which to configure the mixer

  • enable (Optional[bool]) – If present, controls whether or not the mixer should be used

  • **players – Map of player id to Play / Update payloads for each mixer source

Return type

None

off(event=None, callback=None)

Disable an event listener or remove all listeners from an event.

This can also be used to disable a listener that was added using once before it is called.

To remove all listeners from an event, pass the event selector to the event keyword argument:

class MyEvent:
    ...

observable.off(event=MyEvent)

To remove a listener which is listening to all events, pass the listener to the callback keyword argument:

def on_any_event(event):
    print(event)

observable.off(callback=on_any_event)
Parameters
  • event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. This can be the type of a single event or a tuple of multiple events to remove the listeners for.

  • callback (Optional[Callable[[~T], Union[None, Awaitable[None]]]]) – Event listener. This is the same callable that was passed to on or once.

Return type

None

on(event=None, callback=None)

Add a listener to the given event(s).

If you want to listen to all events you can pass the callback to the callback keyword argument:

def on_any_event(event):
    print(event)

observable.on(callback=on_any_event)
Parameters
  • event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. This can be the type of a single event or a tuple of multiple events to listen for. The latter case is equivalent to calling on for each event separately.

  • callback (Optional[Callable[[~T], Union[None, Awaitable[None]]]]) – Callable to call when the selected events are emitted. It is called with the event instance as its only argument. If it returns an Awaitable (or is a coroutine) it is awaited before the emission “completes” (See ChildEmitterABC.emit).

Return type

None

once(event=None, callback=None)

Add a listener which is only called once.

This is basically the same as adding the listener using on and then calling off once the listener has been called.

Parameters
  • event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. This can be the type of a single event or a tuple of multiple events to listen for.

  • callback (Optional[Callable[[~T], Union[None, Awaitable[None]]]]) – Callable to call when the selected events are emitted. It is called with the event instance as its only argument. If it returns an Awaitable (or is a coroutine) it is awaited before the emission “completes” (See ChildEmitterABC.emit).

Return type

None

async pause(guild_id, pause)

Pause a player.

If the player is already paused or unpaused, this is a no-op.

Parameters
  • guild_id (int) – ID of the guild for which to pause

  • pause (bool) – True to pause, False to unpause

Return type

None

async ping(guild_id)

Ping the Andesite server.

Parameters

guild_id (int) – Target guild id

Return type

float

Returns

Amount of seconds it took for the response to be received. Note: This is not necessarily an accurate reflection of the actual latency.

async play(guild_id, track, *, start=None, end=None, pause=None, volume=None, no_replace=False)

Play a track on the guild.

Instead of providing all the fields you can also pass a Play operation.

Parameters
  • guild_id (int) – ID of the guild for which to play

  • track (Union[str, Play]) – Either a Play operation or a base64 encoded lavaplayer track. If you pass a Play operation you must not set any of the keyword arguments.

  • start (Optional[float]) – timestamp, in seconds, to start the track

  • end (Optional[float]) – timestamp, in seconds, to end the track

  • pause (Optional[bool]) – whether or not to pause the player

  • volume (Optional[float]) – volume to set on the player

  • no_replace (bool) – if True and a track is already playing/paused, this command is ignored (Default: False)

Return type

None

remove_child(emitter)

Remove a child emitter.

Parameters

emitter (ChildEmitterABC[~T]) – Child emitter to remove.

Raises

ValueError – If the emitter isn’t a direct child.

Return type

None

async request(method, path, **kwargs)

Perform a request on the http client.

See also

Refer to AbstractHTTP.request for the documentation.

Return type

Any

async reset()

Reset the underlying clients so they may be used again.

This has the opposite effect of the close method making the clients usable again.

Return type

None

async search_tracks(query, *, searcher=<Searcher.YOUTUBE: 'ytsearch'>)

Search tracks.

Parameters
  • query (str) – Search query to search for

  • searcher (Union[Searcher, str]) – Specify the searcher to use. Defaults to YouTube. See Searcher for the supported searchers.

Raises

HTTPError – If Andesite returns an error.

Notes

This is a utility method for the load_tracks method. A search query is just an identifier with the format “<searcher>:<query>”.

Return type

LoadedTrack

async seek(guild_id, position)

Seek to a position.

Parameters
  • guild_id (int) – ID of the guild for which to seek

  • position (float) – Timestamp, in seconds, to seek to

Return type

None

async send(guild_id, op, payload)

Send a message using the web socket client.

See also

Refer to AbstractWebSocket.send for the documentation.

Return type

None

async send_operation(guild_id, operation)

Send a SendOperation.

Parameters
  • guild_id (int) – Target guild id

  • operation (SendOperation) – Operation to send

Notes

Using SendOperation instances to send messages is slightly less efficient than calling the respective WebSocket methods directly.

Return type

None

property state

State handler for the client.

You may manually set this value to a different state handler which implements the AbstractState. You can also disable state handling by setting it to False. Note that this won’t apply the state to the client! You can use the load_player_state method do load individual player states.

If not state is set the getter either returns the current instance, if it happens to implement AbstractState, otherwise it returns None.

Return type

Optional[AbstractState]

async stop(guild_id)

Stop a player.

Parameters

guild_id (int) – ID of the guild for which to stop

Return type

None

subscribe(event=None)

Subscribe to the given event(s).

Parameters

event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. Event type or multiple event types to subscribe to. Can be None which will subscribe to all events.

Return type

SubscriptionABC[~T]

Returns

A subscription which is subscribed to the selected events.

async update(guild_id, update=None, *, pause=None, position=None, volume=None, filters=None)

Send an update.

You may either provide the given keyword arguments, or pass an Update operation which will be used instead.

Parameters
Return type

None

async voice_server_update(guild_id, session_id, event)

Provide a voice server update.

Parameters
  • guild_id (int) – ID of the guild of the voice server update

  • session_id (str) – session id

  • event (Dict[str, Any]) – voice server update event as sent by Discord

Notes

If you wish to send a VoiceServerUpdate operation, please use the send_operation method directly.

Return type

None

async volume(guild_id, volume)

Set a player’s volume.

Parameters
  • guild_id (int) – ID of the guild for which to set the volume

  • volume (float) – Volume to set

Return type

None

create_client(http_uri, web_socket_uri, password, user_id, *, state=None)[source]

Create a new combined Andesite client.

Parameters
  • http_uri (Union[str, URL]) – URI for the http endpoint

  • web_socket_uri (Union[str, URL]) – URI for the web socket endpoint

  • password (Optional[str]) – Andesite password for authorization

  • user_id (int) – User ID

  • state (Union[AbstractState, bool, None]) – State handler to use. Defaults to in-memory State. You can pass False to disable state handling.

Return type

Client

Returns

A new combined client with HTTPBase and WebSocketBase as its clients.

HTTP client

Client for Andesite’s HTTP routes.

There are multiple client classes in this module. If you just want to use Andesite’s HTTP endpoints, use HTTP.

HTTPInterface contains the implementation of the endpoint methods. It’s an abstract base class, if you want to inherit its methods you need to implement AbstractHTTP.

Finally there is HTTPBase which is just the default implementation of AbstractHTTP. HTTP is just a combination of HTTPBase and HTTPInterface.

USER_AGENT

User agent used by the HTTP client.

Type

str

SearcherType

(Type alias) Types supported by get_searcher

Type

Union[Searcher, str]

exception HTTPError(code, message)[source]

Andesite error.

code

HTTP error code

Type

int

message

Message sent by Andesite

Type

str

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class Searcher[source]

Supported search engines for Andesite.

get_searcher(searcher)[source]

Get the Searcher for the given SearcherType.

Parameters

searcher (Union[Searcher, str]) – Searcher to resolve. If searcher happens to be of type Searcher already, it is simply returned.

This function can resolve the following Searcher specifications:

  • Searcher instance

  • Searcher id (i.e. “ytsearch”, “scsearch”)

  • Service name (i.e. “youtube”, “soundcloud”). Note that the casing doesn’t matter, as the provided names are converted to uppercase.

Raises
  • TypeError – Invalid searcher type passed.

  • ValueError – If searcher is a string but doesn’t resolve to a valid searcher.

Return type

Searcher

class AbstractHTTP[source]

Abstract base class which requires a request method and a close method.

abstract property closed

Whether or not the client is closed.

If the client is closed it is no longer usable.

Return type

bool

abstract async close()[source]

Close the underlying connections and clean up.

This should be called when you no longer need the client.

Return type

None

abstract async reset()[source]

Reset the client so it may be used again.

This has the opposite effect of the close method making the client usable again.

Return type

None

abstract async request(method, path, **kwargs)[source]

Perform a request and return the JSON response.

Parameters
  • method (str) – HTTP method to use

  • path (str) – Path relative to the base url. Must not start with a slash!

  • **kwargs – Keyword arguments passed to the request

This method is used by all other methods to perform their respective task. You should use the provided methods whenever possible.

Raises

HTTPError – If Andesite returns an error.

Return type

Any

class HTTPInterface[source]

Abstract implementation of the endpoints.

This does not include the player routes, as they are already covered by the WebSocket. The client uses the user agent USER_AGENT for every request.

async get_stats()[source]

Get the node’s statistics.

Raises

HTTPError – If Andesite returns an error.

Return type

Stats

async load_tracks(identifier)[source]

Load tracks.

Parameters

identifier (str) – Identifier to load. The identifier isn’t handled in any way so it supports the search syntax for example.

Raises

HTTPError – If Andesite returns an error.

See also

search_tracks to search for a track using a query.

Return type

LoadedTrack

async load_tracks_safe(uri)[source]

Load tracks from url.

This is different from load_tracks insofar that it ignores special markers such as “ytsearch:” and treats the given uri as nothing but that.

Parameters

uri (str) – URI to load

Raises

HTTPError – If Andesite returns an error.

See also

load_tracks to load a track using an identifier. search_tracks to search for a track using a query.

Return type

LoadedTrack

async search_tracks(query, *, searcher=<Searcher.YOUTUBE: 'ytsearch'>)[source]

Search tracks.

Parameters
  • query (str) – Search query to search for

  • searcher (Union[Searcher, str]) – Specify the searcher to use. Defaults to YouTube. See Searcher for the supported searchers.

Raises

HTTPError – If Andesite returns an error.

Notes

This is a utility method for the load_tracks method. A search query is just an identifier with the format “<searcher>:<query>”.

Return type

LoadedTrack

async decode_track(track)[source]

Get the TrackInfo from the encoded track data.

Notes

If you find yourself using this method a lot, you might want to use lptrack which can decode and encode the track data locally.

Parameters

track (str) – base 64 encoded track data to decode.

Return type

Optional[TrackInfo]

Returns

TrackInfo of the provided data, None if the data is invalid. Note that this method doesn’t raise HTTPError! If you need the HTTPError to be raised, use decode_tracks.

See also

Please use decode_tracks if you need to decode multiple encoded strings at once!

async decode_tracks(tracks)[source]

Get the TrackInfo from multiple encoded track data strings.

Parameters

tracks (Iterable[str]) – Iterable of base 64 encoded track data to decode.

Return type

List[TrackInfo]

Returns

List of TrackInfo in order of the provided tracks.

Raises

HTTPError – If Andesite returns an error.

abstract async close()

Close the underlying connections and clean up.

This should be called when you no longer need the client.

Return type

None

abstract property closed

Whether or not the client is closed.

If the client is closed it is no longer usable.

Return type

bool

abstract async request(method, path, **kwargs)

Perform a request and return the JSON response.

Parameters
  • method (str) – HTTP method to use

  • path (str) – Path relative to the base url. Must not start with a slash!

  • **kwargs – Keyword arguments passed to the request

This method is used by all other methods to perform their respective task. You should use the provided methods whenever possible.

Raises

HTTPError – If Andesite returns an error.

Return type

Any

abstract async reset()

Reset the client so it may be used again.

This has the opposite effect of the close method making the client usable again.

Return type

None

class HTTPBase(uri, password)[source]

Standard implementation of AbstractHTTP.

Parameters

password (Optional[str]) – Password to use for authorization. Use None if the Andesite node does not have a password set.

See also

HTTP for the client which includes the

HTTPInterface methods.

property aiohttp_session

Client session used to make requests.

Return type

ClientSession

property closed

Whether or not the client is closed.

If the client is closed it is no longer usable.

Return type

bool

async close()[source]

Close the underlying connections and clean up.

This should be called when you no longer need the client.

Return type

None

async reset()[source]

Reset the client so it may be used again.

This has the opposite effect of the close method making the client usable again.

Return type

None

async request(method, path, **kwargs)[source]

Perform a request and return the JSON response.

Parameters
  • method (str) – HTTP method to use

  • path (str) – Path relative to the base url. Must not start with a slash!

  • **kwargs – Keyword arguments passed to the request

This method is used by all other methods to perform their respective task. You should use the provided methods whenever possible.

Raises

HTTPError – If Andesite returns an error.

Return type

Any

class HTTP(uri, password)[source]

Client for Andesite’s HTTP endpoints.

See also

HTTPBase for more details.

property aiohttp_session

Client session used to make requests.

Return type

ClientSession

async close()

Close the underlying connections and clean up.

This should be called when you no longer need the client.

Return type

None

property closed

Whether or not the client is closed.

If the client is closed it is no longer usable.

Return type

bool

async decode_track(track)

Get the TrackInfo from the encoded track data.

Notes

If you find yourself using this method a lot, you might want to use lptrack which can decode and encode the track data locally.

Parameters

track (str) – base 64 encoded track data to decode.

Return type

Optional[TrackInfo]

Returns

TrackInfo of the provided data, None if the data is invalid. Note that this method doesn’t raise HTTPError! If you need the HTTPError to be raised, use decode_tracks.

See also

Please use decode_tracks if you need to decode multiple encoded strings at once!

async decode_tracks(tracks)

Get the TrackInfo from multiple encoded track data strings.

Parameters

tracks (Iterable[str]) – Iterable of base 64 encoded track data to decode.

Return type

List[TrackInfo]

Returns

List of TrackInfo in order of the provided tracks.

Raises

HTTPError – If Andesite returns an error.

async get_stats()

Get the node’s statistics.

Raises

HTTPError – If Andesite returns an error.

Return type

Stats

async load_tracks(identifier)

Load tracks.

Parameters

identifier (str) – Identifier to load. The identifier isn’t handled in any way so it supports the search syntax for example.

Raises

HTTPError – If Andesite returns an error.

See also

search_tracks to search for a track using a query.

Return type

LoadedTrack

async load_tracks_safe(uri)

Load tracks from url.

This is different from load_tracks insofar that it ignores special markers such as “ytsearch:” and treats the given uri as nothing but that.

Parameters

uri (str) – URI to load

Raises

HTTPError – If Andesite returns an error.

See also

load_tracks to load a track using an identifier. search_tracks to search for a track using a query.

Return type

LoadedTrack

async request(method, path, **kwargs)

Perform a request and return the JSON response.

Parameters
  • method (str) – HTTP method to use

  • path (str) – Path relative to the base url. Must not start with a slash!

  • **kwargs – Keyword arguments passed to the request

This method is used by all other methods to perform their respective task. You should use the provided methods whenever possible.

Raises

HTTPError – If Andesite returns an error.

Return type

Any

async reset()

Reset the client so it may be used again.

This has the opposite effect of the close method making the client usable again.

Return type

None

async search_tracks(query, *, searcher=<Searcher.YOUTUBE: 'ytsearch'>)

Search tracks.

Parameters
  • query (str) – Search query to search for

  • searcher (Union[Searcher, str]) – Specify the searcher to use. Defaults to YouTube. See Searcher for the supported searchers.

Raises

HTTPError – If Andesite returns an error.

Notes

This is a utility method for the load_tracks method. A search query is just an identifier with the format “<searcher>:<query>”.

Return type

LoadedTrack

WebSocket client

Web socket client for Andesite.

Use WebSocket if you just want a client which connects to a single Andesite node.

async try_connect(uri, **kwargs)[source]

Connect to the given uri and return the client.

Catches exceptions which could potentially be solved by retrying.

Parameters
  • uri (str) – URI to connect to

  • **kwargs – keyword arguments to pass to the websockets.connect function.

Return type

Optional[WebSocketClientProtocol]

Returns

WebSocketClientProtocol if the connection succeeded, None otherwise.

class AbstractWebSocket[source]

Abstract base class for an Andesite web socket client.

This class is separate from AbstractWebSocketClient to support more complex clients which use more than one web socket connection (ex: Pools).

See also

AbstractWebSocketClient for the abstract base class for actual web socket clients.

Events
  • ws_connect (WebSocketConnectEvent): When the client connects

  • ws_disconnect (WebSocketDisconnectEvent): When the client disconnects

  • raw_msg_receive (RawMsgReceiveEvent): Whenever a message body is received. For this event to be dispatched, the received message needs to be valid JSON and an object.

  • raw_msg_send (RawMsgSendEvent): When sending a message. This event is dispatched regardless of whether the message was actually sent.

  • player_update (PlayerUpdate): When a PlayerUpdate is received.

  • track_start (TrackStartEvent)

  • track_end (TrackEndEvent)

  • track_exception (TrackExceptionEvent)

  • track_stuck (TrackStuckEvent)

  • unknown_andesite_event (UnknownAndesiteEvent): When an unknown event is received.

property event_target

Event target to send events to.

If no event target is set, but the instance is itself an event target, self is set as the new event target and returned, otherwise a new event target is created.

Return type

Observable[~T]

property state

State handler for the client.

You may manually set this value to a different state handler which implements the AbstractState. You can also disable state handling by setting it to False. Note that this won’t apply the state to the client! You can use the load_player_state method do load individual player states.

If not state is set the getter either returns the current instance, if it happens to implement AbstractState, otherwise it returns None.

Return type

Optional[AbstractState]

abstract property closed

Whether or not the client is closed.

If the client is closed it is no longer usable.

Return type

bool

abstract async close()[source]

Close the underlying connections and clean up.

This should be called when you no longer need the client.

Return type

None

abstract async reset()[source]

Reset the client so it may be used again.

This has the opposite effect of the close method making the client usable again.

Return type

None

abstract async send(guild_id, op, payload)[source]

Send a payload.

The guild_id and op are written to the payload before it is converted to JSON.

If sending the message fails because the connection is closed, the client attempts to connect and then sends the message again.

Regardless of whether the payload was actually sent or not a RawMsgSendEvent (raw_msg_send) event is dispatched.

Parameters
  • guild_id (int) – Target guild id

  • op (str) – Name of operation to perform

  • payload (Dict[str, Any]) – Additional data to be sent along with the data. The payload is mutated by the function.

Return type

None

async send_operation(guild_id, operation)[source]

Send a SendOperation.

Parameters
  • guild_id (int) – Target guild id

  • operation (SendOperation) – Operation to send

Notes

Using SendOperation instances to send messages is slightly less efficient than calling the respective WebSocket methods directly.

Return type

None

async load_player_state(player_state)[source]

Load a player state.

Parameters

player_state (AbstractPlayerState) – State to load.

Return type

None

class AbstractWebSocketClient[source]

Abstract base class for a singular web socket connection to Andesite.

If you’re creating a new client and it doesn’t use only one Andesite node, you should implement AbstractWebSocket instead.

See also

AbstractWebSocket for more details.

abstract property connected

Whether the client is connected and usable.

Return type

bool

abstract property connection_id

Andesite connection id.

This should be set after connecting to the node. The connection id can be used to resume connections.

This property is deletable. The consequence of which is that it won’t be sent the next time the client connects to a node.

Notes

The client already performs resuming automatically.

Return type

Optional[str]

abstract property node_region

Node region sent by the Andesite node.

This will be set after the connection is established.

Return type

Optional[str]

abstract property node_id

Node id sent by the Andesite node.

This will be set after the connection is established.

Return type

Optional[str]

abstract async connect(*, max_attempts=None)[source]

Connect to the web socket server.

Parameters

max_attempts (Optional[int]) – Amount of connection attempts to perform before aborting. If None, unlimited attempts will be performed.

If max_attempts is exceeded and the client gives up on connecting it is closed!

After successfully connecting all messages in the message queue are sent in the order they were added and a ws_connected event is dispatched.

Notes

This method doesn’t have to be called manually, it is called as soon as the first message needs to be sent. However, there are good reasons to call it anyway, such as the ability to check the validity of the URI, or to receive events from Andesite.

Return type

None

abstract async disconnect()[source]

Disconnect the web socket.

This will also stop the client from receiving events from Andesite.

This method is idempotent, it doesn’t do anything if the client isn’t connected.

Notes

This is different from close. Calling close disconnects the client and causes it to become unusable. This method only disconnects the client so it can be reconnected.

Return type

None

abstract async close()

Close the underlying connections and clean up.

This should be called when you no longer need the client.

Return type

None

abstract property closed

Whether or not the client is closed.

If the client is closed it is no longer usable.

Return type

bool

property event_target

Event target to send events to.

If no event target is set, but the instance is itself an event target, self is set as the new event target and returned, otherwise a new event target is created.

Return type

Observable[~T]

async load_player_state(player_state)

Load a player state.

Parameters

player_state (AbstractPlayerState) – State to load.

Return type

None

abstract async reset()

Reset the client so it may be used again.

This has the opposite effect of the close method making the client usable again.

Return type

None

abstract async send(guild_id, op, payload)

Send a payload.

The guild_id and op are written to the payload before it is converted to JSON.

If sending the message fails because the connection is closed, the client attempts to connect and then sends the message again.

Regardless of whether the payload was actually sent or not a RawMsgSendEvent (raw_msg_send) event is dispatched.

Parameters
  • guild_id (int) – Target guild id

  • op (str) – Name of operation to perform

  • payload (Dict[str, Any]) – Additional data to be sent along with the data. The payload is mutated by the function.

Return type

None

async send_operation(guild_id, operation)

Send a SendOperation.

Parameters
  • guild_id (int) – Target guild id

  • operation (SendOperation) – Operation to send

Notes

Using SendOperation instances to send messages is slightly less efficient than calling the respective WebSocket methods directly.

Return type

None

property state

State handler for the client.

You may manually set this value to a different state handler which implements the AbstractState. You can also disable state handling by setting it to False. Note that this won’t apply the state to the client! You can use the load_player_state method do load individual player states.

If not state is set the getter either returns the current instance, if it happens to implement AbstractState, otherwise it returns None.

Return type

Optional[AbstractState]

class WebSocketInterface[source]

Implementation of the web socket endpoints.

async play(guild_id, track, *, start=None, end=None, pause=None, volume=None, no_replace=False)[source]

Play a track on the guild.

Instead of providing all the fields you can also pass a Play operation.

Parameters
  • guild_id (int) – ID of the guild for which to play

  • track (Union[str, Play]) – Either a Play operation or a base64 encoded lavaplayer track. If you pass a Play operation you must not set any of the keyword arguments.

  • start (Optional[float]) – timestamp, in seconds, to start the track

  • end (Optional[float]) – timestamp, in seconds, to end the track

  • pause (Optional[bool]) – whether or not to pause the player

  • volume (Optional[float]) – volume to set on the player

  • no_replace (bool) – if True and a track is already playing/paused, this command is ignored (Default: False)

Return type

None

async pause(guild_id, pause)[source]

Pause a player.

If the player is already paused or unpaused, this is a no-op.

Parameters
  • guild_id (int) – ID of the guild for which to pause

  • pause (bool) – True to pause, False to unpause

Return type

None

async stop(guild_id)[source]

Stop a player.

Parameters

guild_id (int) – ID of the guild for which to stop

Return type

None

async seek(guild_id, position)[source]

Seek to a position.

Parameters
  • guild_id (int) – ID of the guild for which to seek

  • position (float) – Timestamp, in seconds, to seek to

Return type

None

async volume(guild_id, volume)[source]

Set a player’s volume.

Parameters
  • guild_id (int) – ID of the guild for which to set the volume

  • volume (float) – Volume to set

Return type

None

async update(guild_id, update=None, *, pause=None, position=None, volume=None, filters=None)[source]

Send an update.

You may either provide the given keyword arguments, or pass an Update operation which will be used instead.

Parameters
Return type

None

async destroy(guild_id)[source]

Destroy a player.

Parameters

guild_id (int) – ID of the guild for which to destroy the player

Return type

None

async mixer(guild_id, enable=None, **players)[source]

Configure the mixer player.

Parameters
  • guild_id (int) – ID of the guild for which to configure the mixer

  • enable (Optional[bool]) – If present, controls whether or not the mixer should be used

  • **players – Map of player id to Play / Update payloads for each mixer source

Return type

None

async filters(guild_id, filter_update=None, *, equalizer=None, karaoke=None, timescale=None, tremolo=None, vibrato=None, volume=None, **custom_filters)[source]

Configure the filters of a player.

Parameters
  • guild_id (int) – ID of the guild for which to configure the filters

  • filter_update (Optional[FilterMap]) – Instead of specifying the other keyword arguments you may provide a FilterMap operation which will be used instead.

  • equalizer (Optional[Equalizer]) – Equalizer filter settings

  • karaoke (Optional[Karaoke]) – Karaoke filter settings

  • timescale (Optional[Timescale]) – Timescale filter settings

  • tremolo (Optional[Tremolo]) – Tremolo filter settings

  • vibrato (Optional[Vibrato]) – Vibrato filter settings

  • volume (Optional[VolumeFilter]) – Volume filter settings

  • **custom_filters – Ability to specify additional filters that aren’t supported by the library.

Return type

None

async get_player(guild_id)[source]

Get the player.

Parameters

guild_id (int) – Target guild id

Return type

Optional[Player]

Returns

Player state for the guild. This may be None if no player is available yet.

async get_stats(guild_id)[source]

Get the Andesite stats.

Parameters

guild_id (int) – Target guild id

Return type

Stats

Returns

Statistics for the node

async ping(guild_id)[source]

Ping the Andesite server.

Parameters

guild_id (int) – Target guild id

Return type

float

Returns

Amount of seconds it took for the response to be received. Note: This is not necessarily an accurate reflection of the actual latency.

async voice_server_update(guild_id, session_id, event)[source]

Provide a voice server update.

Parameters
  • guild_id (int) – ID of the guild of the voice server update

  • session_id (str) – session id

  • event (Dict[str, Any]) – voice server update event as sent by Discord

Notes

If you wish to send a VoiceServerUpdate operation, please use the send_operation method directly.

Return type

None

abstract async close()

Close the underlying connections and clean up.

This should be called when you no longer need the client.

Return type

None

abstract property closed

Whether or not the client is closed.

If the client is closed it is no longer usable.

Return type

bool

property event_target

Event target to send events to.

If no event target is set, but the instance is itself an event target, self is set as the new event target and returned, otherwise a new event target is created.

Return type

Observable[~T]

async load_player_state(player_state)

Load a player state.

Parameters

player_state (AbstractPlayerState) – State to load.

Return type

None

abstract async reset()

Reset the client so it may be used again.

This has the opposite effect of the close method making the client usable again.

Return type

None

abstract async send(guild_id, op, payload)

Send a payload.

The guild_id and op are written to the payload before it is converted to JSON.

If sending the message fails because the connection is closed, the client attempts to connect and then sends the message again.

Regardless of whether the payload was actually sent or not a RawMsgSendEvent (raw_msg_send) event is dispatched.

Parameters
  • guild_id (int) – Target guild id

  • op (str) – Name of operation to perform

  • payload (Dict[str, Any]) – Additional data to be sent along with the data. The payload is mutated by the function.

Return type

None

async send_operation(guild_id, operation)

Send a SendOperation.

Parameters
  • guild_id (int) – Target guild id

  • operation (SendOperation) – Operation to send

Notes

Using SendOperation instances to send messages is slightly less efficient than calling the respective WebSocket methods directly.

Return type

None

property state

State handler for the client.

You may manually set this value to a different state handler which implements the AbstractState. You can also disable state handling by setting it to False. Note that this won’t apply the state to the client! You can use the load_player_state method do load individual player states.

If not state is set the getter either returns the current instance, if it happens to implement AbstractState, otherwise it returns None.

Return type

Optional[AbstractState]

class WebSocketBase(ws_uri, user_id, password, *, state=False, max_connect_attempts=None)[source]

Client for the Andesite WebSocket handler.

Parameters
  • ws_uri (Union[str, URL]) – Websocket endpoint to connect to.

  • user_id (Optional[int]) – Bot’s user id. If at the time of creation this is unknown, you may pass None, but then it needs to be set before connecting for the first time.

  • password (Optional[str]) – Authorization for the Andesite node. Set to None if the node doesn’t have a password.

  • state (Union[AbstractState, bool, None]) – State handler to use. If False state handling is disabled. None to use the default state handler (State).

  • max_connect_attempts (Optional[int]) – See the max_connect_attempts attribute.

The client automatically keeps track of the current connection id and resumes the previous connection when calling connect, if there is any. You can delete the connection_id property to disable this.

See also

AbstractWebSocketClient for more details including a list of events that are dispatched.

max_connect_attempts

Max amount of connection attempts to start before giving up. If None, there is no upper limit. This value can be overwritten when calling connect manually.

Type

Optional[int]

web_socket_client

Web socket client which is used. This attribute will be set once connect is called. Don’t use the presence of this attribute to check whether the client is connected, use the connected property.

Type

Optional[WebSocketClientProtocol]

property state

State handler for the client.

You may manually set this value to a different state handler which implements the AbstractState. You can also disable state handling by setting it to False. Note that this won’t apply the state to the client! You can use the load_player_state method do load individual player states.

If not state is set the getter either returns the current instance, if it happens to implement AbstractState, otherwise it returns None.

Return type

Optional[AbstractState]

property event_target

Event target to send events to.

If no event target is set, but the instance is itself an event target, self is set as the new event target and returned, otherwise a new event target is created.

Return type

Observable[~T]

async load_player_state(player_state)

Load a player state.

Parameters

player_state (AbstractPlayerState) – State to load.

Return type

None

async send_operation(guild_id, operation)

Send a SendOperation.

Parameters
  • guild_id (int) – Target guild id

  • operation (SendOperation) – Operation to send

Notes

Using SendOperation instances to send messages is slightly less efficient than calling the respective WebSocket methods directly.

Return type

None

property user_id

User id.

This is only None if it wasn’t passed to the constructor.

You can set this property to a new user id.

Return type

Optional[int]

property closed

Whether or not the client is closed.

If the client is closed it is no longer usable.

Return type

bool

property connected

Whether the client is connected and usable.

Return type

bool

property connection_id

Andesite connection id.

This should be set after connecting to the node. The connection id can be used to resume connections.

This property is deletable. The consequence of which is that it won’t be sent the next time the client connects to a node.

Notes

The client already performs resuming automatically.

Return type

Optional[str]

property node_region

Node region sent by the Andesite node.

This will be set after the connection is established.

Return type

Optional[str]

property node_id

Node id sent by the Andesite node.

This will be set after the connection is established.

Return type

Optional[str]

async connect(*, max_attempts=None)[source]

Connect to the web socket server.

Parameters

max_attempts (Optional[int]) – Amount of connection attempts to perform before aborting. If None, unlimited attempts will be performed.

If max_attempts is exceeded and the client gives up on connecting it is closed!

After successfully connecting all messages in the message queue are sent in the order they were added and a ws_connected event is dispatched.

Notes

This method doesn’t have to be called manually, it is called as soon as the first message needs to be sent. However, there are good reasons to call it anyway, such as the ability to check the validity of the URI, or to receive events from Andesite.

Return type

None

async disconnect()[source]

Disconnect the web socket.

This will also stop the client from receiving events from Andesite.

This method is idempotent, it doesn’t do anything if the client isn’t connected.

Notes

This is different from close. Calling close disconnects the client and causes it to become unusable. This method only disconnects the client so it can be reconnected.

Return type

None

async reset()[source]

Reset the client so it may be used again.

This has the opposite effect of the close method making the client usable again.

Return type

None

async close()[source]

Close the underlying connections and clean up.

This should be called when you no longer need the client.

Return type

None

async send(guild_id, op, payload)[source]

Send a payload.

The guild_id and op are written to the payload before it is converted to JSON.

If sending the message fails because the connection is closed, the client attempts to connect and then sends the message again.

Regardless of whether the payload was actually sent or not a RawMsgSendEvent (raw_msg_send) event is dispatched.

Parameters
  • guild_id (int) – Target guild id

  • op (str) – Name of operation to perform

  • payload (Dict[str, Any]) – Additional data to be sent along with the data. The payload is mutated by the function.

Return type

None

class WebSocket(ws_uri, user_id, password, *, state=False, max_connect_attempts=None)[source]
add_child(emitter)

Add a child emitter.

Parameters

emitter (ChildEmitterABC[~T]) – Child emitter to add.

Raises

ValueError – If the child emitter already is a child of this emitter, or the emitter is a child of the child emitter. The second case is only possible if the child emitter is itself an instance of EmitterABC.

Return type

None

async close()

Close the underlying connections and clean up.

This should be called when you no longer need the client.

Return type

None

property closed

Whether or not the client is closed.

If the client is closed it is no longer usable.

Return type

bool

async connect(*, max_attempts=None)

Connect to the web socket server.

Parameters

max_attempts (Optional[int]) – Amount of connection attempts to perform before aborting. If None, unlimited attempts will be performed.

If max_attempts is exceeded and the client gives up on connecting it is closed!

After successfully connecting all messages in the message queue are sent in the order they were added and a ws_connected event is dispatched.

Notes

This method doesn’t have to be called manually, it is called as soon as the first message needs to be sent. However, there are good reasons to call it anyway, such as the ability to check the validity of the URI, or to receive events from Andesite.

Return type

None

property connected

Whether the client is connected and usable.

Return type

bool

property connection_id

Andesite connection id.

This should be set after connecting to the node. The connection id can be used to resume connections.

This property is deletable. The consequence of which is that it won’t be sent the next time the client connects to a node.

Notes

The client already performs resuming automatically.

Return type

Optional[str]

async destroy(guild_id)

Destroy a player.

Parameters

guild_id (int) – ID of the guild for which to destroy the player

Return type

None

async disconnect()

Disconnect the web socket.

This will also stop the client from receiving events from Andesite.

This method is idempotent, it doesn’t do anything if the client isn’t connected.

Notes

This is different from close. Calling close disconnects the client and causes it to become unusable. This method only disconnects the client so it can be reconnected.

Return type

None

emit(event)

Emit an event to all observers.

The order in which the observers receive the events isn’t defined and shouldn’t be depended upon.

If a listener raises an error, a ListenerError event is emitted. If an error occurs while handling the ListenerError event, it is ignored.

event

Event object to emit

Return type

Awaitable[None]

Returns

asyncio.Future which resolves to None after all observers have handled the event.

property event_target

Event target to send events to.

If no event target is set, but the instance is itself an event target, self is set as the new event target and returned, otherwise a new event target is created.

Return type

Observable[~T]

async filters(guild_id, filter_update=None, *, equalizer=None, karaoke=None, timescale=None, tremolo=None, vibrato=None, volume=None, **custom_filters)

Configure the filters of a player.

Parameters
  • guild_id (int) – ID of the guild for which to configure the filters

  • filter_update (Optional[FilterMap]) – Instead of specifying the other keyword arguments you may provide a FilterMap operation which will be used instead.

  • equalizer (Optional[Equalizer]) – Equalizer filter settings

  • karaoke (Optional[Karaoke]) – Karaoke filter settings

  • timescale (Optional[Timescale]) – Timescale filter settings

  • tremolo (Optional[Tremolo]) – Tremolo filter settings

  • vibrato (Optional[Vibrato]) – Vibrato filter settings

  • volume (Optional[VolumeFilter]) – Volume filter settings

  • **custom_filters – Ability to specify additional filters that aren’t supported by the library.

Return type

None

async get_player(guild_id)

Get the player.

Parameters

guild_id (int) – Target guild id

Return type

Optional[Player]

Returns

Player state for the guild. This may be None if no player is available yet.

async get_stats(guild_id)

Get the Andesite stats.

Parameters

guild_id (int) – Target guild id

Return type

Stats

Returns

Statistics for the node

has_child(emitter)

Check whether the child emitter is a child of the emitter.

Parameters

emitter (ChildEmitterABC[~T]) – Emitter to check.

Return type

bool

Returns

Whether or not the given emitter is either a direct, or an indirect (child of a child) child of this emitter. Note that every emitter is a child of itself.

async load_player_state(player_state)

Load a player state.

Parameters

player_state (AbstractPlayerState) – State to load.

Return type

None

async mixer(guild_id, enable=None, **players)

Configure the mixer player.

Parameters
  • guild_id (int) – ID of the guild for which to configure the mixer

  • enable (Optional[bool]) – If present, controls whether or not the mixer should be used

  • **players – Map of player id to Play / Update payloads for each mixer source

Return type

None

property node_id

Node id sent by the Andesite node.

This will be set after the connection is established.

Return type

Optional[str]

property node_region

Node region sent by the Andesite node.

This will be set after the connection is established.

Return type

Optional[str]

off(event=None, callback=None)

Disable an event listener or remove all listeners from an event.

This can also be used to disable a listener that was added using once before it is called.

To remove all listeners from an event, pass the event selector to the event keyword argument:

class MyEvent:
    ...

observable.off(event=MyEvent)

To remove a listener which is listening to all events, pass the listener to the callback keyword argument:

def on_any_event(event):
    print(event)

observable.off(callback=on_any_event)
Parameters
  • event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. This can be the type of a single event or a tuple of multiple events to remove the listeners for.

  • callback (Optional[Callable[[~T], Union[None, Awaitable[None]]]]) – Event listener. This is the same callable that was passed to on or once.

Return type

None

on(event=None, callback=None)

Add a listener to the given event(s).

If you want to listen to all events you can pass the callback to the callback keyword argument:

def on_any_event(event):
    print(event)

observable.on(callback=on_any_event)
Parameters
  • event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. This can be the type of a single event or a tuple of multiple events to listen for. The latter case is equivalent to calling on for each event separately.

  • callback (Optional[Callable[[~T], Union[None, Awaitable[None]]]]) – Callable to call when the selected events are emitted. It is called with the event instance as its only argument. If it returns an Awaitable (or is a coroutine) it is awaited before the emission “completes” (See ChildEmitterABC.emit).

Return type

None

once(event=None, callback=None)

Add a listener which is only called once.

This is basically the same as adding the listener using on and then calling off once the listener has been called.

Parameters
  • event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. This can be the type of a single event or a tuple of multiple events to listen for.

  • callback (Optional[Callable[[~T], Union[None, Awaitable[None]]]]) – Callable to call when the selected events are emitted. It is called with the event instance as its only argument. If it returns an Awaitable (or is a coroutine) it is awaited before the emission “completes” (See ChildEmitterABC.emit).

Return type

None

async pause(guild_id, pause)

Pause a player.

If the player is already paused or unpaused, this is a no-op.

Parameters
  • guild_id (int) – ID of the guild for which to pause

  • pause (bool) – True to pause, False to unpause

Return type

None

async ping(guild_id)

Ping the Andesite server.

Parameters

guild_id (int) – Target guild id

Return type

float

Returns

Amount of seconds it took for the response to be received. Note: This is not necessarily an accurate reflection of the actual latency.

async play(guild_id, track, *, start=None, end=None, pause=None, volume=None, no_replace=False)

Play a track on the guild.

Instead of providing all the fields you can also pass a Play operation.

Parameters
  • guild_id (int) – ID of the guild for which to play

  • track (Union[str, Play]) – Either a Play operation or a base64 encoded lavaplayer track. If you pass a Play operation you must not set any of the keyword arguments.

  • start (Optional[float]) – timestamp, in seconds, to start the track

  • end (Optional[float]) – timestamp, in seconds, to end the track

  • pause (Optional[bool]) – whether or not to pause the player

  • volume (Optional[float]) – volume to set on the player

  • no_replace (bool) – if True and a track is already playing/paused, this command is ignored (Default: False)

Return type

None

remove_child(emitter)

Remove a child emitter.

Parameters

emitter (ChildEmitterABC[~T]) – Child emitter to remove.

Raises

ValueError – If the emitter isn’t a direct child.

Return type

None

async reset()

Reset the client so it may be used again.

This has the opposite effect of the close method making the client usable again.

Return type

None

async seek(guild_id, position)

Seek to a position.

Parameters
  • guild_id (int) – ID of the guild for which to seek

  • position (float) – Timestamp, in seconds, to seek to

Return type

None

async send(guild_id, op, payload)

Send a payload.

The guild_id and op are written to the payload before it is converted to JSON.

If sending the message fails because the connection is closed, the client attempts to connect and then sends the message again.

Regardless of whether the payload was actually sent or not a RawMsgSendEvent (raw_msg_send) event is dispatched.

Parameters
  • guild_id (int) – Target guild id

  • op (str) – Name of operation to perform

  • payload (Dict[str, Any]) – Additional data to be sent along with the data. The payload is mutated by the function.

Return type

None

async send_operation(guild_id, operation)

Send a SendOperation.

Parameters
  • guild_id (int) – Target guild id

  • operation (SendOperation) – Operation to send

Notes

Using SendOperation instances to send messages is slightly less efficient than calling the respective WebSocket methods directly.

Return type

None

property state

State handler for the client.

You may manually set this value to a different state handler which implements the AbstractState. You can also disable state handling by setting it to False. Note that this won’t apply the state to the client! You can use the load_player_state method do load individual player states.

If not state is set the getter either returns the current instance, if it happens to implement AbstractState, otherwise it returns None.

Return type

Optional[AbstractState]

async stop(guild_id)

Stop a player.

Parameters

guild_id (int) – ID of the guild for which to stop

Return type

None

subscribe(event=None)

Subscribe to the given event(s).

Parameters

event (Union[Type[~T], Tuple[Type[~T], …], None]) – Event selector. Event type or multiple event types to subscribe to. Can be None which will subscribe to all events.

Return type

SubscriptionABC[~T]

Returns

A subscription which is subscribed to the selected events.

async update(guild_id, update=None, *, pause=None, position=None, volume=None, filters=None)

Send an update.

You may either provide the given keyword arguments, or pass an Update operation which will be used instead.

Parameters
Return type

None

property user_id

User id.

This is only None if it wasn’t passed to the constructor.

You can set this property to a new user id.

Return type

Optional[int]

async voice_server_update(guild_id, session_id, event)

Provide a voice server update.

Parameters
  • guild_id (int) – ID of the guild of the voice server update

  • session_id (str) – session id

  • event (Dict[str, Any]) – voice server update event as sent by Discord

Notes

If you wish to send a VoiceServerUpdate operation, please use the send_operation method directly.

Return type

None

async volume(guild_id, volume)

Set a player’s volume.

Parameters
  • guild_id (int) – ID of the guild for which to set the volume

  • volume (float) – Volume to set

Return type

None

Event models for the web socket client.

class WebSocketConnectEvent(client)[source]

Event dispatched when a connection has been established.

client

Web socket client which connected.

Type

AbstractWebSocketClient

class WebSocketDisconnectEvent(client, deliberate)[source]

Event dispatched when a client was disconnected.

client

Web socket client which connected.

Type

AbstractWebSocketClient

deliberate

Whether the disconnect was deliberate.

Type

bool

class RawMsgReceiveEvent(client, body)[source]

Event emitted when a web socket message is received.

client

Web socket client that received the message.

Type

AbstractWebSocket

body

Raw body of the received message. Note: The body isn’t manipulated in any way other than being loaded from the raw JSON string. For example, the names are still in dromedaryCase.

Type

Dict[str, Any]

class RawMsgSendEvent(client, guild_id, op, body)[source]

Event dispatched before a web socket message is sent.

It’s important to note that this is not a receipt of a message being sent, this event is dispatched even if the message fails to send.

client

Web socket client that received the message.

Type

AbstractWebSocketClient

guild_id

guild id

Type

int

op

Op-code to be executed

Type

str

body

Raw body of the message

Type

Dict[str, Any]