Magmatic API Reference#

Magmatic provides a simple yet powerful interface around Lavalink.

Nodes#

NodePool#

class magmatic.NodePool#

Represents a pool of Lavalink nodes.

By default, a default node pool (DefaultNodePool) is created, however you can construct these yourself.

add_node(node, *, identifier=None)#

Adds an existing node to the pool.

Parameters
  • node (Node) – The node to add to the pool.

  • identifier (Optional[str]) – The identifier to use for the node. If not specified, the node’s identifier will be used.

create_node(*, bot, host='127.0.0.1', port=2333, password=None, region=None, identifier=None, session=None, loop=None, prefer_http=False, secure=False, resume=False, serializer=<json module>)#

Creates a new Node and adds it to the pool.

All parameters are keyword only.

Parameters
  • bot (discord.Client) – The discord.py client/bot instance that this node should be associated with.

  • host (str) – The host of the Lavalink process. In most cases this is an IP address. Defaults to '127.0.0.1'.

  • port (int) – The port the Lavalink process is listening on. Defaults to 2333.

  • password (str) – The password required to authenticate with Lavalink. Leave blank if no password was set.

  • region (str) – The voice region of the node. This is solely used to optimially balance nodes.

  • identifier (str) –

    The string identifier used to identify this node.

    A completely random identifier will be generated if this is left blank, unless if this is the first node in the pool. Then it will default to 'MAIN'.

  • session (aiohttp.ClientSession) – The aiohttp session to use for the node. Leave blank to generate one automatically.

  • loop (asyncio.AbstractEventLoop) –

    The event loop to use for the node.

    Leaving this blank will default to your bot’s event loop, and as a result this method will only work in async-contexts, e.g. in setup_hook.

  • prefer_http (bool) – Whether to connect to Lavalink’s WebSocket over an HTTP protocol over the standard ws protocol. Defaults to False.

  • secure (bool) –

    Whether to use a secure protocol when requesting/connecting to Lavalink. Only set this to True if the given host is remote.

    Defaults to False.

  • resume (bool) – Whether to resume the node after reconnection. Defaults to False.

  • serializer

    An object/module with two methods: loads and dumps which serializes and deserializes JSON data.

    Defaults to the standard json module.

Returns

The created node.

Return type

Node

Raises

NodeConflict – The node identifier is already in use.

async destroy()#

This function is a coroutine.

Clears all nodes from this pool, disconnecting each of them.

This is useful to be called in Client.close.

async destroy_node(node)#

This function is a coroutine.

Destroys the given node and removes it from this pool.

Parameters

node (Union[Node, str]) – The node to destroy, or its string identifier.

Raises

NoMatchesFound – No nodes in the pool match the given identifier.

get_node(identifier=None, *, region=None)#

Gets the least loaded node from this pool that has the given identifier and/or region.

Parameters
  • identifier (str) – The string identifier used to identify the node. Leave blank to allow all nodes.

  • region (str) – The voice region associated with the node. Leave blank to allow all voice regions.

Returns

The node that was found.

Return type

Node

Raises
  • NoAvailableNodes – There are no nodes on this node pool.

  • NoMatchingNodes – No nodes on this pool match the identifier and/or region.

get_player(guild, *, node=None, cls=<class 'magmatic.player.Player'>)#

Gets the player for the given guild.

If no player is found, one will be created automatically on the given node.

Parameters
  • guild (int) –

    The guild to get the player for.

    Could be a snowflake-like object, such as discord.Object, if you cannot resolve the full guild object yet.

  • node (Optional[Node]) –

    The node to get the player from.

    If left as None, the node will be determined automatically.

  • cls (Type[Player]) –

    The player subclass to use if you would like custom behavior. This must be a class that subclasses Player.

    Defaults to Player.

    Note

    The class passed will only be applied if a new player is created.

Returns

The player for the guild.

Return type

Player

property nodes#

A list of nodes in the pool.

Type

list[Node]

async start_node(*, bot, host='127.0.0.1', port=2333, password=None, region=None, identifier=None, session=None, loop=None, prefer_http=False, secure=False, resume=False, serializer=<json module>)#

This function is a coroutine.

Creates a new Node, adds it to the pool, and immediately starts the node.

All parameters are keyword only.

Parameters
  • bot (discord.Client) – The discord.py client/bot instance that this node should be associated with.

  • host (str) – The host of the Lavalink process. In most cases this is an IP address. Defaults to '127.0.0.1'.

  • port (int) – The port the Lavalink process is listening on. Defaults to 2333.

  • password (str) – The password required to authenticate with Lavalink. Leave blank if no password was set.

  • region (str) – The voice region of the node. This is solely used to optimially balance nodes.

  • identifier (str) –

    The string identifier used to identify this node.

    A completely random identifier will be generated if this is left blank, unless if this is the first node in the pool. Then it will default to 'MAIN'.

  • session (aiohttp.ClientSession) – The aiohttp session to use for the node. Leave blank to generate one automatically.

  • loop (asyncio.AbstractEventLoop) –

    The event loop to use for the node.

    Leaving this blank will default to your bot’s event loop, and as a result this method will only work in async-contexts, e.g. in setup_hook.

  • prefer_http (bool) – Whether to connect to Lavalink’s WebSocket over an HTTP protocol over the standard ws protocol. Defaults to False.

  • secure (bool) –

    Whether to use a secure protocol when requesting/connecting to Lavalink. Only set this to True if the given host is remote.

    Defaults to False.

  • resume (bool) – Whether to resume the node after reconnection. Defaults to False.

  • serializer

    An object/module with two methods: loads and dumps which serializes and deserializes JSON data.

    Defaults to the standard json module.

Returns

The created node.

Return type

Node

Raises

NodeConflict – The node identifier is already in use.

walk_nodes()#

Walks over all nodes in the pool.

Yields

Node – A node in the pool.

Top-level DefaultNodePool functions#

create_node#

magmatic.create_node(self, *, bot, host='127.0.0.1', port=2333, password=None, region=None, identifier=None, session=None, loop=None, prefer_http=False, secure=False, resume=False, serializer=<json module>)#

Creates a new Node and adds it to the pool.

All parameters are keyword only.

Parameters
  • bot (discord.Client) – The discord.py client/bot instance that this node should be associated with.

  • host (str) – The host of the Lavalink process. In most cases this is an IP address. Defaults to '127.0.0.1'.

  • port (int) – The port the Lavalink process is listening on. Defaults to 2333.

  • password (str) – The password required to authenticate with Lavalink. Leave blank if no password was set.

  • region (str) – The voice region of the node. This is solely used to optimially balance nodes.

  • identifier (str) –

    The string identifier used to identify this node.

    A completely random identifier will be generated if this is left blank, unless if this is the first node in the pool. Then it will default to 'MAIN'.

  • session (aiohttp.ClientSession) – The aiohttp session to use for the node. Leave blank to generate one automatically.

  • loop (asyncio.AbstractEventLoop) –

    The event loop to use for the node.

    Leaving this blank will default to your bot’s event loop, and as a result this method will only work in async-contexts, e.g. in setup_hook.

  • prefer_http (bool) – Whether to connect to Lavalink’s WebSocket over an HTTP protocol over the standard ws protocol. Defaults to False.

  • secure (bool) –

    Whether to use a secure protocol when requesting/connecting to Lavalink. Only set this to True if the given host is remote.

    Defaults to False.

  • resume (bool) – Whether to resume the node after reconnection. Defaults to False.

  • serializer

    An object/module with two methods: loads and dumps which serializes and deserializes JSON data.

    Defaults to the standard json module.

Returns

The created node.

Return type

Node

Raises

NodeConflict – The node identifier is already in use.

start_node#

magmatic.start_node(self, *, bot, host='127.0.0.1', port=2333, password=None, region=None, identifier=None, session=None, loop=None, prefer_http=False, secure=False, resume=False, serializer=<json module>)#

This function is a coroutine.

Creates a new Node, adds it to the pool, and immediately starts the node.

All parameters are keyword only.

Parameters
  • bot (discord.Client) – The discord.py client/bot instance that this node should be associated with.

  • host (str) – The host of the Lavalink process. In most cases this is an IP address. Defaults to '127.0.0.1'.

  • port (int) – The port the Lavalink process is listening on. Defaults to 2333.

  • password (str) – The password required to authenticate with Lavalink. Leave blank if no password was set.

  • region (str) – The voice region of the node. This is solely used to optimially balance nodes.

  • identifier (str) –

    The string identifier used to identify this node.

    A completely random identifier will be generated if this is left blank, unless if this is the first node in the pool. Then it will default to 'MAIN'.

  • session (aiohttp.ClientSession) – The aiohttp session to use for the node. Leave blank to generate one automatically.

  • loop (asyncio.AbstractEventLoop) –

    The event loop to use for the node.

    Leaving this blank will default to your bot’s event loop, and as a result this method will only work in async-contexts, e.g. in setup_hook.

  • prefer_http (bool) – Whether to connect to Lavalink’s WebSocket over an HTTP protocol over the standard ws protocol. Defaults to False.

  • secure (bool) –

    Whether to use a secure protocol when requesting/connecting to Lavalink. Only set this to True if the given host is remote.

    Defaults to False.

  • resume (bool) – Whether to resume the node after reconnection. Defaults to False.

  • serializer

    An object/module with two methods: loads and dumps which serializes and deserializes JSON data.

    Defaults to the standard json module.

Returns

The created node.

Return type

Node

Raises

NodeConflict – The node identifier is already in use.

add_node#

magmatic.add_node(self, node, *, identifier=None)#

Adds an existing node to the pool.

Parameters
  • node (Node) – The node to add to the pool.

  • identifier (Optional[str]) – The identifier to use for the node. If not specified, the node’s identifier will be used.

get_node#

magmatic.get_node(self, identifier=None, *, region=None)#

Gets the least loaded node from this pool that has the given identifier and/or region.

Parameters
  • identifier (str) – The string identifier used to identify the node. Leave blank to allow all nodes.

  • region (str) – The voice region associated with the node. Leave blank to allow all voice regions.

Returns

The node that was found.

Return type

Node

Raises
  • NoAvailableNodes – There are no nodes on this node pool.

  • NoMatchingNodes – No nodes on this pool match the identifier and/or region.

get_player#

magmatic.get_player(self, guild, *, node=None, cls=<class 'magmatic.player.Player'>)#

Gets the player for the given guild.

If no player is found, one will be created automatically on the given node.

Parameters
  • guild (int) –

    The guild to get the player for.

    Could be a snowflake-like object, such as discord.Object, if you cannot resolve the full guild object yet.

  • node (Optional[Node]) –

    The node to get the player from.

    If left as None, the node will be determined automatically.

  • cls (Type[Player]) –

    The player subclass to use if you would like custom behavior. This must be a class that subclasses Player.

    Defaults to Player.

    Note

    The class passed will only be applied if a new player is created.

Returns

The player for the guild.

Return type

Player

Node#

class magmatic.Node#

Represents a client which interfaces around a Lavalink node.

These are not to be constructed manually, rather they should be created via create_node() or start_node().

bot#

The discord.py client/bot instance associated with this node.

Type

discord.Client

identifier#

The identifier of this node.

Type

str

region#

The voice region of this node.

Type

Optional[str]

async connect()#

This function is a coroutine.

Connects this node with Lavalink by establishing a WebSocket connection.

Raises
  • AuthorizationFailure – Failed to authorize with Lavalink. Your password is likely incorrect.

  • HandshakeFailure – Failed the initial handshake with Lavalink’s websocket.

  • ConnectionFailure – Failed to connect to Lavalink.

See also

Node.start()

async connect_player(channel, *, self_mute=False, self_deaf=False, cls=<class 'magmatic.player.Player'>)#

This function is a coroutine.

Creates a player for the given voice channel on this node and establishes a voice connection with it.

Note

To disconnect the player, call Player.disconnect() on the player object, which will be returned by this function.

Node.disconnect() is different - it will disconnect the node.

Parameters
  • channel (Union[discord.VoiceChannel, discord.StageChannel]) – The voice channel to connect to.

  • self_mute (bool) – Whether to self-mute upon connecting. Defaults to False.

  • self_deaf (bool) – Whether to self-deafen upon connecting. Defaults to False.

  • cls (Type[Player]) –

    The player subclass to use if you would like custom behavior. This must be a class that subclasses Player.

    Defaults to Player.

    Note

    The class passed will only be applied if a new player is created.

Returns

The player associated with the given voice channel.

Return type

Player

property connection#

The ConnectionManager managing this node’s connection with Lavalink.

Type

ConnectionManager

async destroy()#

This function is a coroutine.

Disconnects and removes this node from its associated NodePool.

async disconnect(*, disconnect_players=True)#

This function is a coroutine.

Disconnects this node from Lavalink and clears any data associated with it.

Parameters

disconnect_players (bool) – Whether to disconnect all players on this node from their voice channels. Defaults to True.

async fetch_track(id, *, metadata=None)#

This function is a coroutine.

Fetches and resolves a track given its track ID.

Parameters
  • id (str) – The base 64 ID of the track to fetch.

  • metadata

    The metadata to associate with the fetched track.

    Could be useful for associating a requester with the track. This is optional and defaults to None.

Returns

The track that was fetched.

Return type

Track

Raises

NotFound – The track was not found.

async fetch_tracks(ids, *, atomic=False, metadata=None)#

This function is a coroutine.

Fetches and resolves multiple tracks given their IDs.

Parameters
  • ids (Iterable[str]) – An iterable (i.e. list) of strings, each string being a base 64 ID which represents a track to be fetched.

  • atomic (bool) – Whether to fetch each track individually. Defaults to False. This can ensure that if any track fails, other tracks will still be resolved.

  • metadata

    The metadata to associate with the fetched tracks.

    Could be useful for associating a requester with the tracks. This is optional and defaults to None.

Returns

The tracks that were fetched.

Return type

list[Track]

Raises

NotFound – One or more of the tracks were not found. This error will pass silently if atomic is True.

get_player(guild, *, cls=<class 'magmatic.player.Player'>, fail_if_not_exists=False)#

Returns the Player associated with the given guild.

If fail_if_not_exists is False and the player does not exist, one is created.

Parameters
  • guild (discord.abc.Snowflake) –

    The guild to get the player for.

    Could be a snowflake-like object, such as discord.Object, if you cannot resolve the full guild object yet.

  • cls (Type[Player]) –

    The player subclass to use if you would like custom behavior. This must be a class that subclasses Player.

    Defaults to Player.

    Note

    The class passed will only be applied if a new player is created.

  • fail_if_not_exists (bool) –

    Whether to raise an exception if the player does not exist.

    Defaults to False.

Returns

The player associated with the given guild.

Return type

Player

Raises

PlayerNotFoundfail_if_not_exists is True and the player does not exist.

property host#

The host origin of this node.

Type

str

property loop#

The event loop associated with this node.

Type

asyncio.AbstractEventLoop

property password#

The password used by this node to authenticate with Lavalink.

If no password was set, this will return None.

Type

Optional[str]

property player_count#

The number of players handled by this node.

Type

int

property players#

A list of the players handled by this node.

Type

list[Player]

property port#

The port this node is running on.

Type

int

async request(method, endpoint, *, data=None, **params)#

This function is a coroutine.

Sends a request to an endpoint on Lavalink’s REST API.

Parameters
  • method (str) – The HTTP request method to use, e.g. 'GET'.

  • endpoint (str) – The endpoint to send the request to.

  • data (dict`[:class:`str, Any]) – JSON data to send with the request.

  • **params (Any) – The URL query parameters to send with the request.

Returns

The JSON response from the request, serialized into a dict object.

Return type

dict[str, Any]

Raises

HTTPException – An HTTP error occurred while sending the request.

async search_track(query, *, source=None, strict=False, resolve_playlists=False, prefer_selected_track=True, metadata=None)#

This function is a coroutine.

Finds a track that matches the given query in the given source.

Parameters
  • query (str) – The search query.

  • source (Optional[Source]) – The source to search on. If no source is given then only URLs or specific identifiers can be passed as the query.

  • strict (bool) –

    If False (the default), this will automatically ignore the source if a URL is passed. This is usually what you want.

    If True, then the URL will be searched on the given source. This should only be used if you require the Track.source to be consistent every time.

  • resolve_playlists (bool) –

    Whether to return a track in the playlist if one was returned. If True, then the track returned will never be a Playlist object, however it will have the chance of returning None if no tracks are in the playlist.

    Else, if a playlist is found, this will still return the Playlist object.

    Defaults to False.

  • prefer_selected_track (bool) –

    If set to True and a playlist is returned, then the Playlist.selected_track will be returned. If there is no selected track, this will fall back to the first track in the playlist.

    Else, the first track will be returned.

    This parameter only works in conjunction with resolve_playlists set to True.

    Defaults to True.

  • metadata

    The metadata to associate with the tracks and/or playlist. Metadata associated with playlists will be passed down to their child tracks.

    Could be useful for associating a requester with the track or playlist. This is optional and defaults to None.

Returns

The track or playlist that matches the query.

Return type

Union[Playlist, Track, None]

Raises
  • NoMatches – No tracks were found with your query.

  • LoadFailed – The search query failed to load.

async search_tracks(query, *, source=None, strict=False, flatten_playlists=False, limit=None, metadata=None)#

This function is a coroutine.

Finds tracks that match the given query on the given source.

Parameters
  • query (str) – The search query.

  • source (Optional[Source]) – The source to search on. If no source is given then only URLs or specific identifiers can be passed as the query.

  • strict (bool) –

    If False (the default), this will automatically ignore the source if a URL is passed. This is usually what you want.

    If True, then the URL will be searched on the given source. This should only be used if you require the Track.source to be consistent every time.

  • flatten_playlists (bool) –

    Whether to just return a list of tracks if a playlist was found for your search query. When set to True, this method will always return a list, and never Playlist.

    Defaults to False.

  • limit (Optional[int]) –

    The maximum number of tracks to return. This is useful to limit the amount of Track objects that are created.

    For playlists, this will be ignored. Consider setting flatten_playlists to True if this circumstance matters.

    If None (the default), then all tracks will be returned.

  • metadata

    The metadata to associate with the tracks and/or playlist. Metadata associated with playlists will be passed down to their child tracks.

    Could be useful for associating a requester with the tracks or playlist. This is optional and defaults to None.

Returns

A list of tracks that matched your search query.

If a playlist was returned and flatten_playlists was set to True, a Playlist object will be returned instead.

Return type

Union[list[Track], Playlist]

Raises
  • NoMatches – No tracks were found with your query.

  • LoadFailed – The search query failed to load.

async start()#

This function is a coroutine.

Starts this node and connects it to Lavalink.

Raises
  • AuthorizationFailure – Failed to authorize with Lavalink. Your password is likely incorrect.

  • HandshakeFailure – Failed the initial handshake with Lavalink’s websocket.

  • ConnectionFailure – Failed to connect to Lavalink.

property stats#

Statistical information about this node, received from Lavalink.

Type

Optional[Stats]

async stop(*, disconnect_players=True)#

This function is a coroutine.

An alias to Node.disconnect(), see documentation for that instead.

Players#

Player#

class magmatic.Player(*, node, guild)#

Represents an audio player on a specific guild.

This class can be inherited to allow custom behaviors, although this class is not meant to be constructed manually.

See Node.get_player() or get_player() for retrieving the player object itself.

This class inherits from discord.VoiceProtocol. If this is directly constructed (likely using the cls kwarg in Connectable.connect), a node will be pulled from the DefaultNodePool and the player will be added to it.

If you would like this player to be on a specific node (which in consequence could also be in a sepcific NodePool), see Node.connect() (or the two get_player methods listed above if you don’t want to immediately connect).

node#

The node that the player is currently playing on.

Type

Node

guild#

The guild associated with this player.

Type

discord.abc.Snowflake

channel#

The current voice channel the player is in. None if the player is not connected to a voice channel.

Type

Optional[Union[discord.VoiceChannel, discord.StageChannel]]

async add_filters(*filters)#

This function is a coroutine.

Adds the given filters to the player’s FilterSink and applies them immediately.

This is the equivalent of calling Player.filters.add() and then Player.apply_filters() immediately.

Note

If you’re applying multiple operations simultaneously to the filter sink, consider modifying the sink directly and then running Player.apply_filters() to apply them all at once.

Parameters

*filters (BaseFilter) – The filters to add. Must inherit from BaseFilter.

async apply_filters()#

This function is a coroutine.

Applies the filters from Player.filters to the player.

property bot#

The discord.py client/bot object associated with this player.

Type

discord.Client

property channel_id#

The ID of the voice channel this player is connected to.

This is None if the player is not connected to a voice channel.

Type

Optional[int]

async clear_filters()#

This function is a coroutine.

Clears all filters from the player’s FilterSink and applies changes immediately.

This is the equivalent of calling Player.filters.clear() and then Player.apply_filters() immediately.

Note

If you’re applying multiple operations simultaneously to the filter sink, consider modifying the sink directly and then running Player.apply_filters() to apply them all at once.

async connect(channel=None, *, timeout=60.0, reconnect=False, self_mute=False, self_deaf=False)#

This function is a coroutine.

Connects to the voice channel associated with this player. This is usually called internally.

Parameters
  • channel (Optional[Union[discord.VoiceChannel, discord.StageChannel]]) – The voice channel to connect to.

  • timeout (float) – The timeout in seconds to wait for connection. Defaults to 60 seconds.

  • reconnect (bool) –

    Whether to automatically attempt reconnecting if a part of the handshake fails or the gateway goes down.

    Defaults to False.

  • self_mute (bool) – Whether to self-mute upon joining the channel. Defaults to False.

  • self_deaf (bool) – Whether to self-deafen upon connecting. Defaults to False.

Raises

RuntimeError – The given guild was not a complete discord.Guild object, and the guild could not be resolved upon connection. If this happens, try passing in the actual guild object instead, or enabling guild intents.

async destroy(*, disconnect=True)#

This function is a coroutine.

Destroys the player and cleans up any associated resources.

Parameters

disconnect (bool) – Whether to attempt to disconnect from voice. Defaults to True.

async disconnect(*, force=False, destroy=True)#

This function is a coroutine.

Disconnects from the voice channel associated with this player.

Parameters
  • force (bool) – Whether to force disconnection.

  • destroy (bool) –

    Whether to destroy the player. Defaults to True.

    If you would like the player state to persist after disconnection, set this to False.

Raises

RuntimeError – The given guild was not a complete discord.Guild object, and the guild could not be resolved upon connection. If this happens, try passing in the actual guild object instead, or enabling guild intents.

property equalizer#

The equalizer currently applied to the player’s FilterSink.

This shortcut exists for backwards compatibility purposes. This will be None if no equalizer is applied.

Additionally, note that any change in the equalizer made using this property will not be applied until Player.apply_filters() is called.

Type

Equalizer

event(coro, /)#

A decorator that registers a coroutine function as an event handler for the given event.

Parameters

coro (async (event: BaseEvent) -> Any) – The coroutine function to register.

property filters#

The filters currently applied to the player.

View documentation on FilterSink for more information on using filters.

Type

FilterSink

property guild_id#

The ID of the guild associated with this player.

Type

int

is_connected()#

bool: Returns whether the player is connected to a voice channel.

is_paused()#

bool: Returns whether the player is paused.

is_playing()#

bool: Returns whether the player is currently playing a track.

is_self_deafened()#

bool: Returns whether the player’s voice state is self-deafened.

is_self_muted()#

bool: Returns whether the player’s voice state is self-muted.

async move_to(channel)#

This function is a coroutine.

Moves the player to the given voice channel.

Parameters

channel (Union[discord.VoiceChannel, discord.StageChannel]) – The channel to move to.

Raises

RuntimeError – The given guild was not a complete discord.Guild object, and the guild could not be resolved upon connection. If this happens, try passing in the actual guild object instead, or enabling guild intents.

async on_voice_server_update(data)#

This function is a coroutine.

An abstract method that is called when initially connecting to voice. This corresponds to VOICE_SERVER_UPDATE.

Parameters

data (dict) –

The raw voice server update payload.

async on_voice_state_update(data)#

This function is a coroutine.

An abstract method that is called when the client’s voice state has changed. This corresponds to VOICE_STATE_UPDATE.

Parameters

data (dict) –

The raw voice state payload.

async overwrite_filters(*filters)#

This function is a coroutine.

Clears all filters in the player’s FilterSink, overwrites them with the given filters, and applies them immediately.

This is the equivalent of calling Player.filters.overwrite() and then Player.apply_filters() immediately.

Note

If you’re applying multiple operations simultaneously to the filter sink, consider modifying the sink directly and then running Player.apply_filters() to apply them all at once.

Parameters

*filters (BaseFilter) – The filters to overwrite. Must inherit from BaseFilter.

async pause()#

This function is a coroutine.

Sets the player’s paused state to True.

async play(track, *, start=None, end=None, volume=None, replace=True, pause=False)#

This function is a coroutine.

Starts playing the given track.

Parameters
  • track (Track) – The track to start playing.

  • start (Optional[float]) – The time at which to start playing the track in seconds. Leave blank to start playing the beginning of the track.

  • end (Optional[float]) – The time at which to stop playing the track in seconds. Leave blank to play the track through completely.

  • volume (Optional[int]) – The volume at which to play the track. Must be between 0 and 1000. Leave blank to play at the current volume.

  • replace (bool) –

    Whether to halt playing the current playing track is a track is currently playing. If set to False, this method will silently do nothing if there is already audio playnig.

    Defaults to True.

  • pause (bool) – Whether to pause the track upon playing. Defaults to False

Raises
  • NotConnected – The player is not connected to a voice channel.

  • ValueError

    • The given volume is not between 0 and 1000. - The given start time is below 0. - The given end time is less than the start time.

property position#

The seek position of the player in seconds.

In simpler terms, how many seconds the current track has been playing for.

Type

float

async reconnect()#

This function is a coroutine.

Disconnects and reconnects to the voice channel associated with this player.

This method takes no arguments as all this should do is reconnect the player to its original state.

async remove_filters(*filters)#

This function is a coroutine.

Removes the given filters from the player’s FilterSink and applies changes immediately.

All values passed must be class objects (that is - the classes themselves) that subclass BaseFilter. For example, if you wanted to remove the equalizer filter, you would pass in Equalizer itself - not the instance.

All given filters that are not in the player’s filter sink will pass silently.

This is the equivalent of calling Player.filters.remove() and then Player.apply_filters() immediately.

Note

If you’re applying multiple operations simultaneously to the filter sink, consider modifying the sink directly and then running Player.apply_filters() to apply them all at once.

Parameters

*filters (Type[BaseFilter]) – The classes filters to remove. Each must subclass BaseFilter.

async resume()#

This function is a coroutine.

Sets the player’s paused state to False.

async seek(position)#

This function is a coroutine.

Seeks to the given position (in seconds) in the current track.

Parameters

position (float) – The position, in seconds, of where to seek to.

async set_deafen(deafen)#

This function is a coroutine.

Sets the self-deafened state of the player’s voice state.

Parameters

deafen (bool) – Whether the player’s voice state should be deafened.

async set_mute(mute)#

This function is a coroutine.

Sets the self-muted state of the player’s voice state.

Parameters

mute (bool) – Whether the player’s voice state should be muted.

async set_pause(pause)#

This function is a coroutine.

Sets the paused state of the player.

Parameters

pause (bool) – The new paused state of the player. Set to True to pause; False to resume.

async set_volume(volume)#

This function is a coroutine.

Sets the volume of the player.

Parameters

volume (int) – The new volume of the player, in percent. Must be a whole number between 0 and 1000.

Raises

ValueError – The given volume was not between 0 and 1000.

async stop()#

This function is a coroutine.

Stops the current playing track.

async toggle_pause()#

This function is a coroutine.

Sets the paused state of the player to True if it is currently False, else False if it is currently True.

property track#

The currently playing track. None if no track is currently playing.

Type

Optional[Track]

property voice#

The voice state associated with this player.

This is None if the player is not connected to a voice channel. This is also None if discord.Intents.voice_states is not enabled.

Type

Optional[discord.VoiceState]

property volume#

The current volume of the player.

Type

int

Tracks#

Track#

class magmatic.Track#

Represents a playable track, usually retrieved by search.

See Node.search_track() and Node.search_tracks() for more information. These should not be constructed manually.

id#

The base 64 ID of the track.

You can use this to rebuild this track object; see Node.fetch_track() or Node.fetch_tracks() for information on how.

Type

int

title#

The title of the track.

Type

str

author#

The author of the track. None if the author is unknown.

Type

Optional[str]

uri#

The URI (or URL) which can be used to access this track. This may be None if the track is a local track.

Type

Optional[str]

identifier#

The identifier of this track. This can be None depending on the video’s source.

Type

Optional[str]

duration#

The duration of the track in seconds.

Type

float

position#

The current position of the track in seconds. If this isn’t applicable, this will be None.

Type

Optional[float]

playlist#

The playlist object this track belongs to.

This will be None if this track is not part of a playlist, or if the track was not loaded from a playlist.

Type

Optional[Playlist]

metadata#

The metadata manually provided with the track. This is always provided by you, the user. Could be useful for associating a requester with the track.

If no metadata was provided, this will be None.

is_seekable()#

bool: Returns True if this track is seekable.

is_stream()#

bool: Returns True if this track is a stream.

property source#

The load source of this track, e.g. YouTube.

This may be none if the track was manually loaded or your Lavalink version does not support it.

Type

Optional[LoadSource]

property thumbnail#

The URL to the thumbnail image for this track.

This only exists for certain audio sources.

Type

Optional[str]

Playlist#

class magmatic.Playlist#

Represents a playlist of tracks, usually retrieved by search.

See Node.search_track() and Node.search_tracks() for more information. These should not be constructed manually.

This implements collections.abc.Sequence.

name#

The name of the playlist.

Type

str

selected_track_index#

The index of the currently selected track. -1 if no track is selected.

Type

int

metadata#

The metadata manually provided with the playlist. This is always provided by you, the user. Could be useful for associating a requester with the playlist.

If no metadata was provided, this will be None.

property first#

Returns the first track in the playlist.

Type

Optional[Track]

is_empty()#

bool: Returns whether the playlist is empty.

seek(index)#

Seeks to the track of the given index.

This changes selected_track_index and in consequence selected_track.

Parameters

index (int) – The index of the track to seek to.

Returns

The track that was seeked to.

Return type

Track

property selected_track#

The currently selected track in the playlist.

None if no track is selected.

Type

Optional[Track]

property source#

The load source of this playlist.

This is retrieved from the first track in the playlist, so if this is an empty playlist this will be None.

See also

Track.source

Type

LoadSource

property tracks#

A list of the tracks in this playlist.

Type

list[Track]

Track Converters#

class magmatic.YoutubeTrack#

A subclass of Track solely used for conversion purposes.

This class when used as a discord.py Converter will search for the first track with the source set to Source.youtube.

class magmatic.YoutubeMusicTrack#

A subclass of Track solely used for conversion purposes.

This class when used as a discord.py Converter will search for the first track with the source set to Source.youtube_music.

class magmatic.SoundCloudTrack#

A subclass of Track solely used for conversion purposes.

This class when used as a discord.py Converter will search for the first track with the source set to Source.soundcloud.

class magmatic.SpotifyTrack#

A subclass of Track solely used for conversion purposes.

This class when used as a discord.py Converter will search for the first track with the source set to Source.spotify.

Filters#

FilterSink#

class magmatic.FilterSink#

Represents a sink of filters. All filters in the sink must inherit from BaseFilter.

These are unique for each Player instance.

Usage

player = ...  # retrieve your Player instance
sink = player.filters
sink.add(
    magmatic.VolumeFilter(volume=0.5),
    magmatic.Equalizer.pop(),
)
del sink.equalizer  # Removes the equalizer filter using del
sink.remove(magmatic.Equalizer)  # Removes the equalizer filter using FilterSink.remove
sink.clear()  # Removes all filters

# Once we're all done...
await player.update_filters()
add(*filters)#

Adds a filter (or multiple) to the sink.

All values passed must be instances of classes that inherit from BaseFilter.

Filter keys are determined by their class. Supplying multiple filters of the same class will overwrite the previous values.

Parameters

*filters (BaseFilter) – The filters to add to the sink.

Raises

TypeError – The values passed are not instances of BaseFilter.

clear()#

Clears all filters from the sink.

property equalizer#

The equalizer instance associated with this sink.

Returns

The equalizer instance. None if there is no equalizer.

Return type

Optional[Equalizer]

overwrite(*filters)#

Overwrites the sink’s filters with the given filters.

This is the equivalent of running FilterSink.clear() followed by FilterSink.add() with your filters.

Parameters

*filters (BaseFilter) – The filters to overwrite the sink with.

Raises

TypeError – The values passed are not instances of BaseFilter.

remove(*filters)#

Removes a filter (or multiple) from the sink.

All values passed must be class objects (that is - the classes themselves) that subclass BaseFilter. For example, if you wanted to remove the equalizer filter, you would pass in Equalizer itself - not the instance.

All given filters that are not in the sink will pass silently.

Parameters

*filters (Type[BaseFilter]) – The classes of the filters to remove from the sink.

Raises

TypeError – The values passed are not classes that subclass BaseFilter.

property rotation#

The rotation filter of this sink.

Returns

The rotation filter instance. None if there is no rotation filter.

Return type

Optional[RotationFilter]

property timescale#

The timescale filter of this sink.

Returns

The timescale filter instance. None if there is no timescale filter.

Return type

Optional[TimescaleFilter]

to_dict()#

Returns a JSON-serializable payload made of all filters in the sink.

This is used to send the filters to Lavalink.

Returns

The JSON-serializable payload for the filters.

Return type

dict[str, Any]

property tremolo#

The tremolo filter of this sink.

Returns

The tremolo filter instance. None if there is no tremolo filter.

Return type

Optional[TremoloFilter]

property vibrato#

The vibrato filter of this sink.

Returns

The vibrato filter instance. None if there is no vibrato filter.

Return type

Optional[VibratoFilter]

property volume#

The volume filter of this sink.

You can cast this to a float to retrieve the actual volume number.

Returns

The volume filter instance. None if there is no volume filter.

Return type

Optional[VolumeFilter]

BaseFilter#

class magmatic.BaseFilter#

The base class for which all filters must inherit from.

to_dict()#

Returns a JSON-serializable payload for the filter. This is used to send the filter to Lavalink.

Returns

The JSON-serializable payload for the filter.

Return type

Any

VolumeFilter#

class magmatic.VolumeFilter(volume=1.0)#

A filter that modifies the player’s volume.

Note

This should not be used with Player.set_volume() as the two will overwrite each other; they will not stack.

Additionally, Player.volume will return the volume on the player, not the volume on this filter.

Parameters

volume (float) –

The volume as a float between 0 and 5. If the volume is a percentage, divide by 100 first.

1.0 is the default volume (100%).

to_dict()#

Returns a JSON-serializable payload for the filter. This is used to send the filter to Lavalink.

Returns

The JSON-serializable payload for the filter.

Return type

Any

property volume#

The volume as a float between 0 and 5.

To retrieve the volume as a percentage, multiply this value by 100.

Type

float

Equalizer#

class magmatic.Equalizer(*gains, name=None)#

A filter that modifies the equalizer bands of the player.

name#

The identifying name for this equalizer. Useful for displaying which equalizer the user is using.

If no name is set, this will be None.

Type

Optional[str]

Parameters
  • *gains (float) –

    The band gains for this equalizer. There are a total of 15 bands. Each gain must be between -0.25 and +1.0.

    Either leave this blank or specify exactly 15 bands.

  • name (Optional[str]) – The identifying name for the equalizer. Useful for displaying which equalizer the user is using. Defaults to None.

Raises

ValueError – You did not specify exactly 0 or 15 bands

property bands#

A list of the gains for all 15 bands in this equalizer.

There will always be 15 items in the returned list.

You can retrieve an index-to-gain mapping by using a builtin function such as :py:function:`enumerate`.

Type

list[float]

classmethod boost()#

Returns an equalizer which puts an emphasis on punchy-bass and mid-high tones.

classmethod flat()#

Returns a flat equalizer with all bands set to 0.0.

get_band(index)#

Retrieve the gain for a specific band at a specifix index.

Parameters

index (int) – The index of the band to retrieve. Must be between 0 and 14.

Returns

The gain for the specified band.

Return type

float

Raises

IndexError – The index is out of range. (Not between 0 and 14)

classmethod jazz()#

Returns an equalizer suitable for jazzy music.

classmethod metal()#

Returns an equalizer suitable for metal/rock music.

classmethod piano()#

Returns an equalizer suitable for piano music or music with high tones.

This may cut off some bass tones.

classmethod pop()#

Returns an equalizer suitable for pop music.

reset()#

Resets the equalizer band gains to the default values.

set_band_at(index, /, gain)#

Sets the gain for a specific band at a specifix index to the given gain.

Parameters

index (int) – The index of the band the set. Must be between 0 and 14.

Raises

IndexError – The index is out of range.

set_bands(*gains)#

Overwrites the band gains for this equalizer. Exactly 15 gains must be specified.

Furthermore, each gain must be between -0.25 and +1.0.

Parameters

*gains (float) – The new gains for the equalizer in order.

Raises

ValueError – You did not specify exactly 15 bands

to_dict()#

Returns a JSON-serializable payload for the filter. This is used to send the filter to Lavalink.

Returns

The JSON-serializable payload for the filter.

Return type

Any

TimescaleFilter#

class magmatic.TimescaleFilter(*, speed=1.0, pitch=1.0, rate=1.0)#

A filter which modifies the piatch, speed, and rate of the audio.

All parameters are optional and default to 1.0. (No change)

Parameters
  • speed (float) – The speed multiplier. For example, a value of 2 will double the speed of the audio.

  • pitch (Union[float, magmatic.filters.PitchMultiplier, magmatic.filters.PitchOctaves, magmatic.filters.PitchSemitones]) –

    The pitch multiplier/relative value. A higher value makes the audio a higher pitch.

    Passing in a raw float will default to it being a normal multiplier. You can pass in special values such as magmatic.filters.PitchOctaves(1) to use octaves instead, for example.

    The following are available:

    magmatic.filters.PitchMultiplier

    Modifies the multiplier of the pitch relative to the original pitch. A value of 1.0 will not change the pitch.

    magmatic.filters.PitchOctaves

    Modifies the amount of octaves the pitch should change by relative to the original pitch. A value of 0.0 will not change the pitch.

    magmatic.filters.PitchSemitones

    Modifies the amount of semitones the pitch should change by relative to the original pitch. A value of 0.0 will not change the pitch. 12 semitones make up an octave.

  • rate (float) – The rate multiplier.

property pitch#

The pitch multiplier represented as a float. A value of 1.0 is the original pitch.

Type

float

property rate#

The rate multiplier represented as a float. A value of 1.0 is the original rate.

Type

float

property speed#

The speed multiplier represented as a float. A value of 1.0 is the original speed.

Type

float

to_dict()#

Returns a JSON-serializable payload for the filter. This is used to send the filter to Lavalink.

Returns

The JSON-serializable payload for the filter.

Return type

Any

update(*, speed=None, pitch=None, rate=None)#

Modifies the speed, pitch, and rate multipliers with the given values.

All parameters are optional and keyword-only.

Parameters
  • speed (float) – The new speed multiplier.

  • pitch (Union[float, magmatic.filters.PitchMultiplier, magmatic.filters.PitchOctaves, magmatic.filters.PitchSemitones]) – The new pitch multiplier/relative value. See documentation on TimescaleFilter for more information.

  • rate (float) – The new rate multiplier.

RotationFilter#

class magmatic.RotationFilter(*, hz=5.0)#

A filter which simulates an audio source rotating around the listener using audio panning.

Parameters

hz (float) – The hertz (“revolutions” per second) at which to rotate the audio. Defaults to 5.0.

property hz#

The hertz (“revolutions” per second) at which to rotate the audio.

Type

float

to_dict()#

Returns a JSON-serializable payload for the filter. This is used to send the filter to Lavalink.

Returns

The JSON-serializable payload for the filter.

Return type

Any

VibratoFilter#

class magmatic.VibratoFilter(*, frequency=2.0, depth=0.5)#

A filter which oscillates the pitch. Similar to TremoloFilter which oscillates the volume.

All parameters are keyword-only.

Parameters
  • frequency (float) – The frequency at which to oscillate the pitch. Must be greater than 0.0 and at most 14.0, and defaults to 2.0.

  • depth (float) – The depth/intensity of this filter. Must be greater than 0.0 and at most 1.0, defaults to 0.5.

property depth#

The depth/intensity of this filter.

Type

float

property frequency#

The frequency at which to oscillate the pitch.

Type

float

to_dict()#

Returns a JSON-serializable payload for the filter. This is used to send the filter to Lavalink.

Returns

The JSON-serializable payload for the filter.

Return type

Any

TremoloFilter#

class magmatic.TremoloFilter(*, frequency=2.0, depth=0.5)#

A filter which oscillates the volume. Similar to VibratoFilter which oscillates the pitch.

All parameters are keyword-only.

Parameters
  • frequency (float) – The frequency at which to oscillate the volume. Must be greater than 0.0 and defaults to 2.0.

  • depth (float) – The depth/intensity of this filter. Must be greater than 0.0 and at most 1.0, defaults to 0.5.

property depth#

The depth/intensity of this filter.

Type

float

property frequency#

The frequency at which to oscillate the volume.

Type

float

to_dict()#

Returns a JSON-serializable payload for the filter. This is used to send the filter to Lavalink.

Returns

The JSON-serializable payload for the filter.

Return type

Any

Event Models#

See Event Reference for more information on events.

TrackStartEvent#

class magmatic.TrackStartEvent#

Triggered when a track starts playing.

player#

The player on which the track started playing on.

Type

Player

track_id#

The base 64 ID of the track that started playing. To resolve this into a full track object, see track().

Type

str

property node#

The Lavalink node that received this event.

Type

Node

async track(*, metadata=None)#

This function is a coroutine.

Resolves the track ID into a Track object.

This will make a request to Lavalink to decode the track ID associated with this event. See Node.fetch_track() for more information.

Parameters

metadata

The metadata to associate with the fetched track.

Could be useful for associating a requester with the track. This is optional and defaults to None.

Returns

The track object associated with this event.

Return type

Track

Raises

NotFound – The track was not found.

TrackEndEvent#

class magmatic.TrackEndEvent#

Triggered when a track ends and stops playing.

player#

The player on which the track ended playing on.

Type

Player

track_id#

The base 64 ID of the track that ended playing. To resolve this into a full track object, see track().

Type

str

reason#

The reason the track ended.

Type

TrackEndReason

property may_start_next#

Whether it is safe for the player to start playing the next track.

Type

bool

property node#

The Lavalink node that received this event.

Type

Node

async track(*, metadata=None)#

This function is a coroutine.

Resolves the track ID into a Track object.

This will make a request to Lavalink to decode the track ID associated with this event. See Node.fetch_track() for more information.

Parameters

metadata

The metadata to associate with the fetched track.

Could be useful for associating a requester with the track. This is optional and defaults to None.

Returns

The track object associated with this event.

Return type

Track

Raises

NotFound – The track was not found.

TrackExceptionEvent#

class magmatic.TrackExceptionEvent#

Triggered when a track throws an exception during playback.

player#

The player on which the track threw an exception on.

Type

Player

track_id#

The base 64 ID of the track that threw an exception. To resolve this into a full track object, see track().

Type

str

message#

The exception message provided by Lavalink.

Type

str

severity#

The severity of the exception.

Type

ErrorSeverity

cause#

The cause of the exception.

Type

str

property node#

The Lavalink node that received this event.

Type

Node

async track(*, metadata=None)#

This function is a coroutine.

Resolves the track ID into a Track object.

This will make a request to Lavalink to decode the track ID associated with this event. See Node.fetch_track() for more information.

Parameters

metadata

The metadata to associate with the fetched track.

Could be useful for associating a requester with the track. This is optional and defaults to None.

Returns

The track object associated with this event.

Return type

Track

Raises

NotFound – The track was not found.

TrackStuckEvent#

class magmatic.TrackStuckEvent#

Triggered when a track is stuck.

player#

The player on which the track is stuck on.

Type

Player

track_id#

The base 64 ID of the track that is stuck. To resolve this into a full track object, see track().

Type

str

threshold#

The threshold in seconds at which the track is considered stuck.

Type

float

property node#

The Lavalink node that received this event.

Type

Node

async track(*, metadata=None)#

This function is a coroutine.

Resolves the track ID into a Track object.

This will make a request to Lavalink to decode the track ID associated with this event. See Node.fetch_track() for more information.

Parameters

metadata

The metadata to associate with the fetched track.

Could be useful for associating a requester with the track. This is optional and defaults to None.

Returns

The track object associated with this event.

Return type

Track

Raises

NotFound – The track was not found.

WebSocketCloseEvent#

class magmatic.WebSocketCloseEvent#

Triggered when the websocket connection is closed.

code#

The websocket close code.

Type

int

reason#

The websocket close reason.

Type

str

by_remote#

Whether the websocket was closed remotely.

Type

bool

property node#

The Lavalink node that received this event.

Type

Node

Event Reference#

This section goes over all events dispatched by magmatic. You can handle most of these events in two different ways:

Through your discord.py client/bot instance:

class MyMusicBot(commands.Bot):
    async def on_magmatic_node_ready(self, node):
        print(f'Node {node.identifier} is ready!')

    async def on_magmatic_track_start(self, player, event):
        track = await event.track()
        print(f'Player in {player.guild.name} started playing {track.title!r}')

# or...
@bot.event
async def on_magmatic_node_ready(node):
    print(f'Node {node.identifier} is ready!')

Or, for all non-node related events (that is, events that do not contain “node” in their name), they can be handled through a Player subclass:

class MyCustomPlayer(magmatic.Player):
    # Notice the absence of "on_magmatic_" and instead just "on_"
    async def on_track_start(self, event):
        track = await event.track()
        print(f'Player in {self.guild.name} started playing {track.title!r}')

For events that can be implemented in both ways, the top event is documented as the signature for a discord.py client/bot listener while the second if documented as the signature for a Player.

Stats#

Stats#

class magmatic.Stats#

Statistical information about a given node.

uptime#

The amount of time the node has been running, in seconds.

Type

float

players#

The amount of players currently connected to the node.

Type

int

playing_players#

The amount of players currently connected and playing audio on the node.

Type

int

memory#

The memory information about the node.

Type

MemoryStats

cpu_cores#

The amount of CPU cores the node is able to use.

Type

int

system_load#

The amount of load from the system.

Type

float

The amount of load from Lavalink.

Type

float

frames_sent#

The amount of frames sent to the node.

Type

int

frames_nulled#

The amount of frames nulled by the node.

Type

int

frames_deficit#

The amount of frames deficit by the node.

Type

int

penalty#

The amount of load-balancing penalty on the node.

Type

float

MemoryStats#

class magmatic.MemoryStats#

Memory information about a given node.

free#

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

Type

int

used#

The amount of memory the node is actively using, in bytes.

Type

int

allocated#

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

Type

int

reservable#

The amount of memory the node is able to allocate, in bytes.

Type

int

property total#

The total amount of memory on the node, in bytes.

Type

int

Queues#

Magmatic provides a set of preset, easy-to-use queue models.

Quick Example:

# Use this as the player subclass
class PlayerWithQueue(magmatic.Player):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.queue = magmatic.Queue()

    async def start_queue(self):
        track = self.queue.get()
        await self.play(track)

    async def enqueue(self, track):
        self.queue.add(track)

        if not self.is_playing():
            await self.start_queue()

    async def on_track_end(self, event):
        if event.may_start_next:
            if track := self.queue.get():
                await self.play(track)

# later...
@bot.command()
async def play(ctx, *, track: magmatic.YoutubeTrack):
    await ctx.voice_client.enqueue(track)

BaseQueue#

class magmatic.BaseQueue#

An abstract base class that all queues should inherit from.

In reality, this wraps over an internal queue, i.e. a deque by default.

max_size#

The maximum size of the queue. None if no maximum size was set.

Type

int

add(item, *, discard=False)#

Adds/enqueues a track or playlist to the queue.

If a playlist is provided, each of its tracks will be added to the queue.

Parameters
  • item (Union[Track, Playlist]) – The track or playlist to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

add_multiple(items, *, discard=False)#

Adds multiple tracks or playlists to the queue.

This is in reality just a shortcut to calling add() for each track or playlist in the iterable.

Parameters
  • items (Iterable[Union[Track, Playlist]]) – An iterable (i.e. a list) of tracks or playlists to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

clear()#

Removes all tracks from the queue.

copy()#

Creates and returns a copy of the queue.

property count#

The number of tracks in the queue.

Type

int

property current#

The current track the queue is pointing to.

This is None if the queue is empty or if the queue is not pointing to a track.

Type

Optional[Track]

extend(items, *, discard=False)#

An alias for add_multiple(). See documentation for that instead.

get()#

Gets the next track in the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

insert(index, item)#

Inserts a track or playlist into the queue at the specified index.

Note

This is zero-indexed - the first track is at index 0.

Parameters
  • index (int) – The index at which to insert the track or playlist.

  • item (Union[Track, Playlist]) – The track or playlist to insert.

is_empty()#

bool: Whether the queue is empty.

is_full()#

bool: Whether the queue is full. This is always False for queues that do not have a maximum size.

jump_to(index)#

Jumps to the track at the given index.

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index to jump to.

Returns

The track at the given index.

Return type

Track

jump_to_last()#

Jumps to the last track in the queue.

Returns

The last track in the queue.

Return type

Track

pop()#

Pops the last enqueued track from the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

property queue#

The internal queue this queue wraps around. Usually deque.

remove(item)#

Removes a track (or track at a given index) from the queue.

Parameters

item (Track) – The track to remove from the queue, or the index of the track to remove.

remove_index(index=0)#

Removes the track at the specified index from the queue. If you have an index, this is usually preferred over remove().

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index of the track to removed.

Returns

The track that was removed.

Return type

Track

skip(count=1)#

Skips the next track (or count number of tracks) in the queue and returns the new track. In some queue implementations, this is identical to get().

In Queue, this will ignore LoopType.track and move on to the next track regardless.

Parameters

count (int) – The number of tracks to skip. Defaults to 1.

Returns

The retrieved track, or None if the queue is empty.

Return type

Optional[Track]

property up_next#

The next track in the queue. This is None if there is no next track.

Type

Optional[Track]

property upcoming#

A list of all upcoming tracks in the queue.

Type

List[Track]

ConsumptionQueue#

class magmatic.ConsumptionQueue(*, max_size=None, factory=deque)#

A queue that gets rid of tracks as they are retrieved.

For a more common use case of a queue where tracks are kept, see Queue.

max_size#

The maximum amount of tracks this queue can hold. None if no limit was set.

Type

Optional[int]

Parameters
  • max_size (Optional[int]) – The maximum amount of tracks this queue should hold. Leave blank to allow an infinite amount of tracks.

  • factory (() -> deque) – The factory function or class to use to create the internal queue. Defaults to the built-in collections.deque itself.

add(item, *, discard=False)#

Adds/enqueues a track or playlist to the queue.

If a playlist is provided, each of its tracks will be added to the queue.

Parameters
  • item (Union[Track, Playlist]) – The track or playlist to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

add_multiple(items, *, discard=False)#

Adds multiple tracks or playlists to the queue.

This is in reality just a shortcut to calling add() for each track or playlist in the iterable.

Parameters
  • items (Iterable[Union[Track, Playlist]]) – An iterable (i.e. a list) of tracks or playlists to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

clear()#

Removes all tracks from the queue.

copy()#

Creates and returns a copy of the queue.

property count#

The number of tracks in the queue.

Type

int

property current#

The current track the queue is pointing to.

This is None if the queue is empty or if the queue is not pointing to a track.

Type

Optional[Track]

extend(items, *, discard=False)#

An alias for add_multiple(). See documentation for that instead.

get()#

Gets the next track in the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

insert(index, item)#

Inserts a track or playlist into the queue at the specified index.

Note

This is zero-indexed - the first track is at index 0.

Parameters
  • index (int) – The index at which to insert the track or playlist.

  • item (Union[Track, Playlist]) – The track or playlist to insert.

is_empty()#

bool: Whether the queue is empty.

is_full()#

bool: Whether the queue is full. This is always False for queues that do not have a maximum size.

jump_to(index)#

Jumps to the track at the given index.

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index to jump to.

Returns

The track at the given index.

Return type

Track

jump_to_last()#

Jumps to the last track in the queue.

Returns

The last track in the queue.

Return type

Track

pop()#

Pops the last enqueued track from the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

property queue#

The internal queue this queue wraps around. Usually deque.

remove(item)#

Removes a track (or track at a given index) from the queue.

Parameters

item (Track) – The track to remove from the queue, or the index of the track to remove.

remove_index(index=0)#

Removes the track at the specified index from the queue. If you have an index, this is usually preferred over remove().

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index of the track to removed.

Returns

The track that was removed.

Return type

Track

skip(count=1)#

Skips the next track (or count number of tracks) in the queue and returns the new track. In some queue implementations, this is identical to get().

In Queue, this will ignore LoopType.track and move on to the next track regardless.

Parameters

count (int) – The number of tracks to skip. Defaults to 1.

Returns

The retrieved track, or None if the queue is empty.

Return type

Optional[Track]

property up_next#

The next track in the queue. This is None if there is no next track.

Type

Optional[Track]

property upcoming#

A list of all upcoming tracks in the queue.

Type

List[Track]

Queue#

class magmatic.Queue(*, max_size=None, loop_type=LoopType.none, factory=deque)#

A queue that keeps its tracks, moving a pointer to each track which is retrieved.

Because this is the most common use case for queues, this is just named “Queue”. For a queue that consumes tracks as they are retrieved, see ConsumptionQueue.

This also adds the ability for looping.

max_size#

The maximum amount of tracks this queue can hold. None if no limit was set.

Type

Optional[int]

loop_type#

The looping policy this queue is using.

Type

LoopType

Parameters
  • max_size (Optional[int]) – The maximum amount of tracks this queue should hold. Leave blank to allow an infinite amount of tracks.

  • loop_type (LoopType) – The loop type to use. Defaults to none.

  • factory (() -> deque) – The factory function or class to use to create the internal queue. Defaults to the built-in collections.deque itself.

add(item, *, discard=False)#

Adds/enqueues a track or playlist to the queue.

If a playlist is provided, each of its tracks will be added to the queue.

Parameters
  • item (Union[Track, Playlist]) – The track or playlist to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

add_multiple(items, *, discard=False)#

Adds multiple tracks or playlists to the queue.

This is in reality just a shortcut to calling add() for each track or playlist in the iterable.

Parameters
  • items (Iterable[Union[Track, Playlist]]) – An iterable (i.e. a list) of tracks or playlists to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

clear()#

Removes all tracks from the queue.

copy()#

Creates and returns a copy of the queue.

property count#

The number of tracks in the queue.

Type

int

property current#

The current track the queue is pointing to.

This is None if the queue is empty or if the queue is not pointing to a track.

Type

Optional[Track]

property current_index#

The index of the current track the queue is pointing to. This could be an index out of bounds if the queue has exhausted all tracks.

This is None if the queue is not pointing to a track.

Type

Optional[int]

extend(items, *, discard=False)#

An alias for add_multiple(). See documentation for that instead.

get()#

Gets the next track in the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

insert(index, item)#

Inserts a track or playlist into the queue at the specified index.

Note

This is zero-indexed - the first track is at index 0.

Parameters
  • index (int) – The index at which to insert the track or playlist.

  • item (Union[Track, Playlist]) – The track or playlist to insert.

is_empty()#

bool: Whether the queue is empty.

is_full()#

bool: Whether the queue is full. This is always False for queues that do not have a maximum size.

jump_to(index)#

Jumps to the track at the given index.

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index to jump to.

Returns

The track at the given index.

Return type

Track

jump_to_last()#

Jumps to the last track in the queue.

Returns

The last track in the queue.

Return type

Track

pop()#

Pops the last enqueued track from the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

property queue#

The internal queue this queue wraps around. Usually deque.

remove(item)#

Removes a track (or track at a given index) from the queue.

Parameters

item (Track) – The track to remove from the queue, or the index of the track to remove.

remove_index(index=0)#

Removes the track at the specified index from the queue. If you have an index, this is usually preferred over remove().

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index of the track to removed.

Returns

The track that was removed.

Return type

Track

reset(*, hard=False)#

Resets the queue pointer.

Parameters

hard (bool) –

Whether get() should be called to retrieve the first track again. If False the queue will just reset to the first track.

Defaults to False.

shift()#

Shifts the queue so that the first track is now the current track.

Warning

This will discard tracks that come before the current track in the queue.

skip(count=1)#

Skips the next track (or count number of tracks) in the queue and returns the new track. In some queue implementations, this is identical to get().

In Queue, this will ignore LoopType.track and move on to the next track regardless.

Parameters

count (int) – The number of tracks to skip. Defaults to 1.

Returns

The retrieved track, or None if the queue is empty.

Return type

Optional[Track]

property up_next#

The next track in the queue. This is None if there is no next track.

Type

Optional[Track]

property upcoming#

A list of all upcoming tracks in the queue.

Type

List[Track]

WaitableConsumptionQueue#

class magmatic.WaitableConsumptionQueue(*, max_size=None, factory=deque, loop=None)#

A ConsumptionQueue that supports waiting for queues by storing a persistent asyncio.Future.

See ConsumptionQueue for more information on parameters and attributes.

The only difference in the constructor signature is that it additionally takes a loop kwarg, specifying the event loop in which wait-futures will be created upon. This is optional.

add(item, *, discard=False)#

Adds/enqueues a track or playlist to the queue.

If a playlist is provided, each of its tracks will be added to the queue.

Parameters
  • item (Union[Track, Playlist]) – The track or playlist to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

add_multiple(items, *, discard=False)#

Adds multiple tracks or playlists to the queue.

This is in reality just a shortcut to calling add() for each track or playlist in the iterable.

Parameters
  • items (Iterable[Union[Track, Playlist]]) – An iterable (i.e. a list) of tracks or playlists to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

cancel_waiter()#

Cancels the waiter in this queue.

In consequence, asyncio.CancelledError will be raised where you have awaited this waiter.

clear()#

Removes all tracks from the queue.

copy()#

Creates and returns a copy of the queue.

property count#

The number of tracks in the queue.

Type

int

property current#

The current track the queue is pointing to.

This is None if the queue is empty or if the queue is not pointing to a track.

Type

Optional[Track]

extend(items, *, discard=False)#

An alias for add_multiple(). See documentation for that instead.

get()#

Gets the next track in the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

async get_wait()#

This function is a coroutine.

Runs get() but waits for a track to be available beforehand. This guarantees the track returned will not be None.

Returns

The track that was retrieved.

Return type

Track

insert(index, item)#

Inserts a track or playlist into the queue at the specified index.

Note

This is zero-indexed - the first track is at index 0.

Parameters
  • index (int) – The index at which to insert the track or playlist.

  • item (Union[Track, Playlist]) – The track or playlist to insert.

is_empty()#

bool: Whether the queue is empty.

is_full()#

bool: Whether the queue is full. This is always False for queues that do not have a maximum size.

jump_to(index)#

Jumps to the track at the given index.

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index to jump to.

Returns

The track at the given index.

Return type

Track

jump_to_last()#

Jumps to the last track in the queue.

Returns

The last track in the queue.

Return type

Track

pop()#

Pops the last enqueued track from the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

property queue#

The internal queue this queue wraps around. Usually deque.

remove(item)#

Removes a track (or track at a given index) from the queue.

Parameters

item (Track) – The track to remove from the queue, or the index of the track to remove.

remove_index(index=0)#

Removes the track at the specified index from the queue. If you have an index, this is usually preferred over remove().

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index of the track to removed.

Returns

The track that was removed.

Return type

Track

skip(count=1)#

Skips the next track (or count number of tracks) in the queue and returns the new track. In some queue implementations, this is identical to get().

In Queue, this will ignore LoopType.track and move on to the next track regardless.

Parameters

count (int) – The number of tracks to skip. Defaults to 1.

Returns

The retrieved track, or None if the queue is empty.

Return type

Optional[Track]

async skip_wait()#

This function is a coroutine.

Runs skip() but waits for a track to be available beforehand. This guarantees the track returned will not be None.

Returns

The track that was skipped.

Return type

Track

property up_next#

The next track in the queue. This is None if there is no next track.

Type

Optional[Track]

property upcoming#

A list of all upcoming tracks in the queue.

Type

List[Track]

WaitableQueue#

class magmatic.WaitableQueue(*, max_size=None, loop_type=LoopType.none, factory=deque, loop=None)#

A Queue that supports waiting for queues by storing a persistent asyncio.Future.

See Queue for more information on parameters and attributes.

The only difference in the constructor signature is that it additionally takes a loop kwarg, specifying the event loop in which wait-futures will be created upon. This is optional.

add(item, *, discard=False)#

Adds/enqueues a track or playlist to the queue.

If a playlist is provided, each of its tracks will be added to the queue.

Parameters
  • item (Union[Track, Playlist]) – The track or playlist to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

add_multiple(items, *, discard=False)#

Adds multiple tracks or playlists to the queue.

This is in reality just a shortcut to calling add() for each track or playlist in the iterable.

Parameters
  • items (Iterable[Union[Track, Playlist]]) – An iterable (i.e. a list) of tracks or playlists to add to the queue.

  • discard (bool) – Whether to discard another track if the queue is full. If this is False (the default), QueueFull will be raised instead.

Returns

A list of discarded tracks if discard was True. If discard was False, this will be an empty list.

Return type

List[Track]

Raises

QueueFull – If the queue is full and discard was False.

cancel_waiter()#

Cancels the waiter in this queue.

In consequence, asyncio.CancelledError will be raised where you have awaited this waiter.

clear()#

Removes all tracks from the queue.

copy()#

Creates and returns a copy of the queue.

property count#

The number of tracks in the queue.

Type

int

property current#

The current track the queue is pointing to.

This is None if the queue is empty or if the queue is not pointing to a track.

Type

Optional[Track]

property current_index#

The index of the current track the queue is pointing to. This could be an index out of bounds if the queue has exhausted all tracks.

This is None if the queue is not pointing to a track.

Type

Optional[int]

extend(items, *, discard=False)#

An alias for add_multiple(). See documentation for that instead.

get()#

Gets the next track in the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

async get_wait()#

This function is a coroutine.

Runs get() but waits for a track to be available beforehand. This guarantees the track returned will not be None.

Returns

The track that was retrieved.

Return type

Track

insert(index, item)#

Inserts a track or playlist into the queue at the specified index.

Note

This is zero-indexed - the first track is at index 0.

Parameters
  • index (int) – The index at which to insert the track or playlist.

  • item (Union[Track, Playlist]) – The track or playlist to insert.

is_empty()#

bool: Whether the queue is empty.

is_full()#

bool: Whether the queue is full. This is always False for queues that do not have a maximum size.

jump_to(index)#

Jumps to the track at the given index.

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index to jump to.

Returns

The track at the given index.

Return type

Track

jump_to_last()#

Jumps to the last track in the queue.

Returns

The last track in the queue.

Return type

Track

pop()#

Pops the last enqueued track from the queue. If no tracks are in the queue, this returns None.

Returns

The next track in the queue, or None if the queue is empty.

Return type

Optional[Track[MetadataT]]

property queue#

The internal queue this queue wraps around. Usually deque.

remove(item)#

Removes a track (or track at a given index) from the queue.

Parameters

item (Track) – The track to remove from the queue, or the index of the track to remove.

remove_index(index=0)#

Removes the track at the specified index from the queue. If you have an index, this is usually preferred over remove().

Note

This is zero-indexed - the first track is at index 0.

Parameters

index (int) – The index of the track to removed.

Returns

The track that was removed.

Return type

Track

reset(*args, **kwargs)#

Resets the queue pointer.

Parameters

hard (bool) –

Whether get() should be called to retrieve the first track again. If False the queue will just reset to the first track.

Defaults to False.

shift()#

Shifts the queue so that the first track is now the current track.

Warning

This will discard tracks that come before the current track in the queue.

skip(count=1)#

Skips the next track (or count number of tracks) in the queue and returns the new track. In some queue implementations, this is identical to get().

In Queue, this will ignore LoopType.track and move on to the next track regardless.

Parameters

count (int) – The number of tracks to skip. Defaults to 1.

Returns

The retrieved track, or None if the queue is empty.

Return type

Optional[Track]

async skip_wait()#

This function is a coroutine.

Runs skip() but waits for a track to be available beforehand. This guarantees the track returned will not be None.

Returns

The track that was skipped.

Return type

Track

property up_next#

The next track in the queue. This is None if there is no next track.

Type

Optional[Track]

property upcoming#

A list of all upcoming tracks in the queue.

Type

List[Track]

Enums#

Source#

enum magmatic.Source(value)#

This is an enum.

The source to use when searching for a track. See Node.search_tracks() for more information on track searching.

This is not to be confused with LoadSource, which represents the source of a track that has already been loaded.

Valid values are as follows:

youtube = <Source.youtube: 'ytsearch'>#
youtube_music = <Source.youtube_music: 'ytmsearch'>#
soundcloud = <Source.soundcloud: 'scsearch'>#
spotify = <Source.spotify: 'spotify'>#
local = <Source.local: 'local'>#

LoadSource#

enum magmatic.LoadSource(value)#

This is an enum.

Represents the source of a loaded track, e.g. YouTube.

This is not to be confused with Source, which is to be used when searching for tracks. Rather, this enum represents the source of a track that has been loaded.

Valid values are as follows:

youtube = <LoadSource.youtube: 'youtube'>#
soundcloud = <LoadSource.soundcloud: 'soundcloud'>#
spotify = <LoadSource.spotify: 'spotify'>#
twitch = <LoadSource.twitch: 'twitch'>#
bandcamp = <LoadSource.bandcamp: 'bandcamp'>#
vimeo = <LoadSource.vimeo: 'vimeo'>#
beam = <LoadSource.beam: 'beam'>#
nico = <LoadSource.nico: 'nico'>#
getyarn = <LoadSource.getyarn: 'getyarn.io'>#
local = <LoadSource.local: 'local'>#
http = <LoadSource.http: 'http'>#
stream = <LoadSource.stream: 'stream'>#

LoopType#

enum magmatic.LoopType(value)#

This is an enum.

The track looping type of a Queue.

Member Type

int

Valid values are as follows:

none = <LoopType.none: 0>#
track = <LoopType.track: 1>#
queue = <LoopType.queue: 2>#

LoadType#

enum magmatic.LoadType(value)#

This is an enum.

Represents the response type of a track loading request.

This is usually used internally.

Valid values are as follows:

track_loaded = <LoadType.track_loaded: 'TRACK_LOADED'>#
playlist_loaded = <LoadType.playlist_loaded: 'PLAYLIST_LOADED'>#
search_result = <LoadType.search_result: 'SEARCH_RESULT'>#
no_matches = <LoadType.no_matches: 'NO_MATCHES'>#
load_failed = <LoadType.load_failed: 'LOAD_FAILED'>#

ErrorSeverity#

enum magmatic.ErrorSeverity(value)#

This is an enum.

Represents the severity of an error received from Lavalink.

Valid values are as follows:

common = <ErrorSeverity.common: 'COMMON'>#
suspicious = <ErrorSeverity.suspicious: 'SUSPICIOUS'>#
fault = <ErrorSeverity.fault: 'FAULT'>#

TrackEndReason#

enum magmatic.TrackEndReason(value)#

This is an enum.

Represents why a track has ended.

Valid values are as follows:

finished = <TrackEndReason.finished: 'FINISHED'>#
load_failed = <TrackEndReason.load_failed: 'LOAD_FAILED'>#
stopped = <TrackEndReason.stopped: 'STOPPED'>#
replaced = <TrackEndReason.replaced: 'REPLACED'>#
cleanup = <TrackEndReason.cleanup: 'CLEANUP'>#

The Enum and its members also have the following methods:

property may_start_next#

Whether it is safe to start playing another track.

Type

bool

Internal Enums#

enum magmatic.OpCode(value)#

This is an enum.

Represents an inbound Op-code received from Lavalink’s websocket.

This is only used internally and should rarely be used.

Valid values are as follows:

stats = <OpCode.stats: 'stats'>#
event = <OpCode.event: 'event'>#
player_update = <OpCode.player_update: 'playerUpdate'>#
enum magmatic.EventType(value)#

This is an enum.

Represents the type of event received from Lavalink’s websocket via the event op-code.

This is only used internally and should rarely be used.

Valid values are as follows:

track_start = <EventType.track_start: 'TrackStartEvent'>#
track_end = <EventType.track_end: 'TrackEndEvent'>#
track_stuck = <EventType.track_stuck: 'TrackStuckEvent'>#
track_exception = <EventType.track_exception: 'TrackExceptionEvent'>#
websocket_closed = <EventType.websocket_closed: 'WebSocketClosedEvent'>#