Pools

Client pools for multiple clients.

Client pools work exactly like the other clients, but internally they use more than one client (preferably to multiple Andesite nodes).

RegionGuildComparator (Callable[[int, Optional[str]], int]

(Type alias) Function which takes a guild id and the node region of an Andesite node and returns an integer to indicate how well the guild is suited for the region.

PoolScoringFunction

(Type alias) Function which takes ScoringData as its only argument and returns a comparable object. The function may also be a coroutine. The return value is only compared to return values of the same function and the comparisons are bigger than (>) and less than (<). Equality (==) is implied if something is neither bigger nor smaller than the other value. A bigger return value (by comparison) implies that the ScoringData is better (ex: more suitable for the given guild).

Type

Callable[[ScoringData], Union[Any, Awaitable[Any]]]

NodeDetails

(Type alias) Tuple containing the uri and the password of an Andesite node.

Type

Tuple[Union[str, yarl.URL], Optional[str]]

exception PoolException(pool)[source]

Pool exceptions.

pool

Pool which raised the error

Type

ClientPool

with_traceback()

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

exception PoolEmptyError(pool)[source]

Raised when a pool is empty but shouldn’t be.

with_traceback()

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

class PoolClientAddEvent(pool, client)[source]

Event for when a new client is added to a pool.

pool

Pool the client was added to

Type

ClientPool

client

Client that was added to the pool

Type

CT

class PoolClientRemoveEvent(pool, client)[source]

Event for when a client is removed from a pool.

pool

Pool the client was added to

Type

ClientPool

client

Client that was added to the pool

Type

CT

class ClientPool(events=None)[source]

Andesite client pool.

property closed

Check whether all clients in the pool are closed.

Return type

bool

async close()[source]

Close all clients in the pool.

Return type

None

async reset()[source]

Reset all 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

abstract add_client(client)[source]

Add a new client to the pool.

Parameters

client (~CT) – Client to add.

Raises

ValueError – If the client is already in the pool

Dispatches the PoolClientAddEvent event.

Return type

None

abstract remove_client(client)[source]

Remove a client from the pool.

Parameters

client (~CT) – Client to remove.

Raises

ValueError – If the client isn’t in the pool

Dispatches the PoolClientRemoveEvent event.

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

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.

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.

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

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.

class HTTPPoolBase(clients, *, timeout=None, max_penalties=5, penalty_time_frame=60)[source]

Andesite HTTP client pool.

Parameters

The pool uses a circular buffer which is rotated after every request.

timeout

Time in seconds to wait before starting the request on the next client. Note that the previous request isn’t cancelled, if it succeeds after the next attempt has been started it is still accepted and returned.

max_penalties

Max number of penalties a client may receive in the penalty_time_frame before being removed from the pool. A penalty is added to a client each time it raises an unexpected error.

penalty_time_frame

Number of seconds before a penalty expires and no long counts toward a client’s total number of penalties.

add_client(client)[source]

Add a new client to the pool.

Parameters

client (AbstractHTTP) – Client to add.

Raises

ValueError – If the client is already in the pool

Return type

None

remove_client(client)[source]

Remove a client from the pool.

Parameters

client (AbstractHTTP) – Client to remove.

Raises

ValueError – If the client isn’t in the pool

Return type

None

get_current_client()[source]

Get the current http client.

Return type

Optional[AbstractHTTP]

Returns

The current client or None if there are no clients.

get_next_client()[source]

Move to the next http client and return it.

In reality this returns the next client that seems to be working. (i.e. not closed)

Return type

Optional[AbstractHTTP]

Returns

Next available client. None if no clients are available.

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

Perform a request on the one of the clients.

See also

AbstractHTTP.request for the documentation.

Raises

PoolEmptyError – If no clients are available

Return type

Any

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 all clients in the pool.

Return type

None

property closed

Check whether all clients in the pool are closed.

Return type

bool

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.

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.

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 reset()

Reset all 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

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.

class HTTPPool(clients, *, timeout=None, max_penalties=5, penalty_time_frame=60)[source]

Andesite HTTP client pool.

This is just a wrapper around HTTPPoolBase which adds the HTTPInterface methods.

Please see the documentation of HTTPPoolBase for more details.

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

add_client(client)

Add a new client to the pool.

Parameters

client (AbstractHTTP) – Client to add.

Raises

ValueError – If the client is already in the pool

Return type

None

async close()

Close all clients in the pool.

Return type

None

property closed

Check whether all clients in the pool are closed.

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.

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.

get_current_client()

Get the current http client.

Return type

Optional[AbstractHTTP]

Returns

The current client or None if there are no clients.

get_next_client()

Move to the next http client and return it.

In reality this returns the next client that seems to be working. (i.e. not closed)

Return type

Optional[AbstractHTTP]

Returns

Next available client. None if no clients are available.

async get_stats()

Get the node’s statistics.

Raises

HTTPError – If Andesite returns an error.

Return type

Stats

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_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

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

remove_client(client)

Remove a client from the pool.

Parameters

client (AbstractHTTP) – Client to remove.

Raises

ValueError – If the client isn’t in the pool

Return type

None

async request(method, path, **kwargs)

Perform a request on the one of the clients.

See also

AbstractHTTP.request for the documentation.

Raises

PoolEmptyError – If no clients are available

Return type

Any

async reset()

Reset all 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

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.

class ScoringData(pool, client, node_region, region_comparator, guild_ids, guild_id)[source]

Data passed to the web socket scoring scoring function.

pool
Type

WebSocketPoolBase

client

Client to be evaluated

Type

AbstractWebSocket

node_region

Node region reported by the Andesite client.

Type

Optional[str]

region_comparator

Function to compare node region with guild id.

Type

Optional[RegionGuildComparator]

guild_ids

Guild ids which are already assigned to the client

Type

Set[int]

guild_id

Guild id which the client should be evaluated for

Type

int

default_scoring_function(data)[source]

Calculate the default score.

Return type

Tuple[int, int, int]

Returns

3-tuple with the first element representing the connection status -1 for closed, 0 for disconnected, and 1 for connected. If the client doesn’t have a connected attribute it is still set to 1.

The second element is the result of the region comparator or 0 if no region comparator was passed.

The third element is the amount of guilds negative. So it will favour clients with less guilds.

class WebSocketPoolBase(clients, *, state=None, scoring_function=None, region_comparator=None)[source]

Base implementation of a web socket pool.

Parameters

The pool uses different clients on a guild to guild level.

If the pool uses a state, all clients within the pool are forced to use the same state as well. Trying to add a client with a state to a pool with a state will result in an error.

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 scoring_function

Scoring function used by the pool.

Return type

Callable[[ScoringData], Union[Any, Awaitable[Any]]]

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 all clients in the pool.

Return type

None

property closed

Check whether all clients in the pool are closed.

Return type

bool

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

property region_comparator

Region comparator used to compare guild region with Andesite node region.

Return type

Optional[Callable[[int, Optional[str]], int]]

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 all 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 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.

add_client(client)[source]

Add a new client to the pool.

Parameters

client (AbstractWebSocket) – Client to add.

Raises

ValueError – If the client is already in the pool or if the client has a state and the pool also has a different state.

Return type

None

remove_client(client)[source]

Remove a web socket client from the pool.

Parameters

client (AbstractWebSocket) – WebSocket client to remove

Raises

ValueError – If the client isn’t in the pool

Notes

This method removes the client without performing node migration. If you want to properly remove a client use the pull_client method.

Return type

None

async pull_client(client)[source]

Remove a client from the pool and migrate its state to another node.

Parameters

client (AbstractWebSocket) – WebSocket client to remove

Raises

ValueError – If the client isn’t in the pool

Return type

None

get_client(guild_id)[source]

Get the andesite web socket client which is used for the given guild.

Return type

Optional[AbstractWebSocket]

iter_client_guild_ids()[source]

Iterate over all clients with their assigned guild ids.

Return type

Iterator[Tuple[AbstractWebSocket, Set[int]]]

async calculate_score(data)[source]

Calculate the score using the scoring function.

Return type

Any

async find_best_client(guild_id)[source]

Determine the best client for the given guild.

If there are multiple clients with the same score, a random one is returned.

Return type

Optional[AbstractWebSocket]

async assign_client(guild_id)[source]

Assign a client to the given guild.

If the guild already has a client, it is simply returned.

Return type

Optional[AbstractWebSocket]

get_guild_ids(client)[source]

Get the guild ids which the client is assigned to.

Parameters

client (AbstractWebSocket) – Client to get guild ids for.

Return type

Set[int]

Returns

Guild ids set which are assigned to the client. Mutating the returned set won’t affect the internal state, the returned set is a shallow copy of the internal one.

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 WebSocketPool(clients, *, state=None, scoring_function=None, region_comparator=None)[source]

Pool of Andesite web socket connections.

Please refer to WebSocketPoolBase for the documentation.

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

add_client(client)

Add a new client to the pool.

Parameters

client (AbstractWebSocket) – Client to add.

Raises

ValueError – If the client is already in the pool or if the client has a state and the pool also has a different state.

Return type

None

async assign_client(guild_id)

Assign a client to the given guild.

If the guild already has a client, it is simply returned.

Return type

Optional[AbstractWebSocket]

async calculate_score(data)

Calculate the score using the scoring function.

Return type

Any

async close()

Close all clients in the pool.

Return type

None

property closed

Check whether all clients in the pool are closed.

Return type

bool

async destroy(guild_id)

Destroy a player.

Parameters

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

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 find_best_client(guild_id)

Determine the best client for the given guild.

If there are multiple clients with the same score, a random one is returned.

Return type

Optional[AbstractWebSocket]

get_client(guild_id)

Get the andesite web socket client which is used for the given guild.

Return type

Optional[AbstractWebSocket]

get_guild_ids(client)

Get the guild ids which the client is assigned to.

Parameters

client (AbstractWebSocket) – Client to get guild ids for.

Return type

Set[int]

Returns

Guild ids set which are assigned to the client. Mutating the returned set won’t affect the internal state, the returned set is a shallow copy of the internal one.

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.

iter_client_guild_ids()

Iterate over all clients with their assigned guild ids.

Return type

Iterator[Tuple[AbstractWebSocket, Set[int]]]

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

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

async pull_client(client)

Remove a client from the pool and migrate its state to another node.

Parameters

client (AbstractWebSocket) – WebSocket client to remove

Raises

ValueError – If the client isn’t in the pool

Return type

None

property region_comparator

Region comparator used to compare guild region with Andesite node region.

Return type

Optional[Callable[[int, Optional[str]], int]]

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

remove_client(client)

Remove a web socket client from the pool.

Parameters

client (AbstractWebSocket) – WebSocket client to remove

Raises

ValueError – If the client isn’t in the pool

Notes

This method removes the client without performing node migration. If you want to properly remove a client use the pull_client method.

Return type

None

async reset()

Reset all 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

property scoring_function

Scoring function used by the pool.

Return type

Callable[[ScoringData], Union[Any, Awaitable[Any]]]

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

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_pool(http_nodes, web_socket_nodes, *, user_id, state=None, http_pool_kwargs=None, web_socket_pool_kwargs=None)[source]

Create an Client with client pools.

Uses HTTPBase and WebSocketBase which are contained in HTTPPoolBase and WebSocketPoolBase pools respectively.

Parameters
  • http_nodes (Iterable[Tuple[Union[str, URL], Optional[str]]]) – Tuples of [uri, password] for each REST node to connect to.

  • web_socket_nodes (Iterable[Tuple[Union[str, URL], Optional[str]]]) – Tuples of [uri, password] for each WebSocket node to connect to.

  • user_id (int) – Bot’s user id.

  • state (Union[AbstractState, bool, None]) – State handler to use for the pools. Defaults to State, because a state handler is required for node migration to work. You can pass False to disable state handling though.

  • http_pool_kwargs (Optional[Mapping[str, Any]]) – Additional keyword arguments to pass to the http pool constructor.

  • web_socket_pool_kwargs (Optional[Mapping[str, Any]]) – Additional keyword arguments to pass to the web socket pool constructor.

Return type

Client

Returns

A combined Andesite client operation on an http pool and a web socket pool.