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’sidentifierwill 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
Nodeand 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 to2333.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 standardwsprotocol. Defaults toFalse.secure (
bool) –Whether to use a secure protocol when requesting/connecting to Lavalink. Only set this to
Trueif the givenhostis remote.Defaults to
False.resume (
bool) – Whether to resume the node after reconnection. Defaults toFalse.serializer –
An object/module with two methods:
loadsanddumpswhich serializes and deserializes JSON data.Defaults to the standard
jsonmodule.
- Returns
The created node.
- Return type
- 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.
- get_node(identifier=None, *, region=None)#
Gets the least loaded node from this pool that has the given identifier and/or region.
- Parameters
- Returns
The node that was found.
- Return type
- 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 asdiscord.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
- 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 to2333.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 standardwsprotocol. Defaults toFalse.secure (
bool) –Whether to use a secure protocol when requesting/connecting to Lavalink. Only set this to
Trueif the givenhostis remote.Defaults to
False.resume (
bool) – Whether to resume the node after reconnection. Defaults toFalse.serializer –
An object/module with two methods:
loadsanddumpswhich serializes and deserializes JSON data.Defaults to the standard
jsonmodule.
- Returns
The created node.
- Return type
- Raises
NodeConflict – The node identifier is already in use.
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
Nodeand 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 to2333.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 standardwsprotocol. Defaults toFalse.secure (
bool) –Whether to use a secure protocol when requesting/connecting to Lavalink. Only set this to
Trueif the givenhostis remote.Defaults to
False.resume (
bool) – Whether to resume the node after reconnection. Defaults toFalse.serializer –
An object/module with two methods:
loadsanddumpswhich serializes and deserializes JSON data.Defaults to the standard
jsonmodule.
- Returns
The created node.
- Return type
- 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 to2333.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 standardwsprotocol. Defaults toFalse.secure (
bool) –Whether to use a secure protocol when requesting/connecting to Lavalink. Only set this to
Trueif the givenhostis remote.Defaults to
False.resume (
bool) – Whether to resume the node after reconnection. Defaults toFalse.serializer –
An object/module with two methods:
loadsanddumpswhich serializes and deserializes JSON data.Defaults to the standard
jsonmodule.
- Returns
The created node.
- Return type
- 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’sidentifierwill 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
- Returns
The node that was found.
- Return type
- 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 asdiscord.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
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()orstart_node().- bot#
The discord.py client/bot instance associated with this node.
- Type
- 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
- 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 toFalse.self_deaf (
bool) – Whether to self-deafen upon connecting. Defaults toFalse.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
- property connection#
The
ConnectionManagermanaging 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 toTrue.
- 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
- 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
atomicisTrue.
- get_player(guild, *, cls=<class 'magmatic.player.Player'>, fail_if_not_exists=False)#
Returns the
Playerassociated with the given guild.If
fail_if_not_existsisFalseand 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 asdiscord.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
- Raises
PlayerNotFound –
fail_if_not_existsisTrueand the player does not exist.
- property loop#
The event loop associated with this node.
- property password#
The password used by this node to authenticate with Lavalink.
If no password was set, this will return
None.- Type
Optional[
str]
- async request(method, endpoint, *, data=None, **params)#
This function is a coroutine.
Sends a request to an endpoint on Lavalink’s REST API.
- 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 theTrack.sourceto 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 aPlaylistobject, however it will have the chance of returningNoneif no tracks are in the playlist.Else, if a playlist is found, this will still return the
Playlistobject.Defaults to
False.prefer_selected_track (bool) –
If set to
Trueand a playlist is returned, then thePlaylist.selected_trackwill 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
- 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 theTrack.sourceto 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 alist, and neverPlaylist.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_playliststoTrueif 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, aPlaylistobject 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()orget_player()for retrieving the player object itself.This class inherits from
discord.VoiceProtocol. If this is directly constructed (likely using theclskwarg inConnectable.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).- guild#
The guild associated with this player.
- channel#
The current voice channel the player is in.
Noneif 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
FilterSinkand applies them immediately.This is the equivalent of calling
Player.filters.add()and thenPlayer.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 fromBaseFilter.
- async apply_filters()#
This function is a coroutine.
Applies the filters from
Player.filtersto the player.
- property bot#
The discord.py client/bot object associated with this player.
- Type
- property channel_id#
The ID of the voice channel this player is connected to.
This is
Noneif 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
FilterSinkand applies changes immediately.This is the equivalent of calling
Player.filters.clear()and thenPlayer.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 toFalse.self_deaf (
bool) – Whether to self-deafen upon connecting. Defaults toFalse.
- Raises
RuntimeError – The given guild was not a complete
discord.Guildobject, 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 toTrue.
- async disconnect(*, force=False, destroy=True)#
This function is a coroutine.
Disconnects from the voice channel associated with this player.
- Parameters
- Raises
RuntimeError – The given guild was not a complete
discord.Guildobject, 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
Noneif 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
- 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
FilterSinkfor more information on using filters.- Type
- 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.Guildobject, 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 thenPlayer.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 fromBaseFilter.
- 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.
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
- 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
FilterSinkand 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 inEqualizeritself - 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 thenPlayer.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 subclassBaseFilter.
- 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 toTrueto pause;Falseto 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 between0and1000.- Raises
ValueError – The given volume was not between
0and1000.
- async toggle_pause()#
This function is a coroutine.
Sets the paused state of the player to
Trueif it is currentlyFalse, elseFalseif it is currentlyTrue.
- property track#
The currently playing track.
Noneif no track is currently playing.- Type
Optional[
Track]
- property voice#
The voice state associated with this player.
This is
Noneif the player is not connected to a voice channel. This is alsoNoneifdiscord.Intents.voice_statesis not enabled.- Type
Optional[
discord.VoiceState]
Tracks#
Track#
- class magmatic.Track#
Represents a playable track, usually retrieved by search.
See
Node.search_track()andNode.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()orNode.fetch_tracks()for information on how.- Type
- uri#
The URI (or URL) which can be used to access this track. This may be
Noneif the track is a local track.- Type
Optional[
str]
- identifier#
The identifier of this track. This can be
Nonedepending on the video’ssource.- Type
Optional[
str]
- 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
Noneif 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
Trueif this track is seekable.
- is_stream()#
bool: Returns
Trueif 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]
Playlist#
- class magmatic.Playlist#
Represents a playlist of tracks, usually retrieved by search.
See
Node.search_track()andNode.search_tracks()for more information. These should not be constructed manually.This implements
collections.abc.Sequence.- selected_track_index#
The index of the currently selected track.
-1if no track is selected.- Type
- 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.
- is_empty()#
bool: Returns whether the playlist is empty.
- seek(index)#
Seeks to the track of the given index.
This changes
selected_track_indexand in consequenceselected_track.
- property selected_track#
The currently selected track in the playlist.
Noneif 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
- Type
Track Converters#
- class magmatic.YoutubeTrack#
A subclass of
Tracksolely used for conversion purposes.This class when used as a discord.py
Converterwill search for the first track with the source set toSource.youtube.
- class magmatic.YoutubeMusicTrack#
A subclass of
Tracksolely used for conversion purposes.This class when used as a discord.py
Converterwill search for the first track with the source set toSource.youtube_music.
- class magmatic.SoundCloudTrack#
A subclass of
Tracksolely used for conversion purposes.This class when used as a discord.py
Converterwill search for the first track with the source set toSource.soundcloud.
- class magmatic.SpotifyTrack#
A subclass of
Tracksolely used for conversion purposes.This class when used as a discord.py
Converterwill search for the first track with the source set toSource.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
Playerinstance.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.
Noneif 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 byFilterSink.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 inEqualizeritself - 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.
Noneif there is no rotation filter.- Return type
Optional[
RotationFilter]
- property timescale#
The timescale filter of this sink.
- Returns
The timescale filter instance.
Noneif 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.
Noneif there is no tremolo filter.- Return type
Optional[
TremoloFilter]
- property vibrato#
The vibrato filter of this sink.
- Returns
The vibrato filter instance.
Noneif there is no vibrato filter.- Return type
Optional[
VibratoFilter]
- property volume#
The volume filter of this sink.
You can cast this to a
floatto retrieve the actual volume number.- Returns
The volume filter instance.
Noneif there is no volume filter.- Return type
Optional[
VolumeFilter]
BaseFilter#
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.volumewill 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.0is 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
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 toNone.
- 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
- 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 of2will 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.PitchMultiplierModifies the multiplier of the pitch relative to the original pitch. A value of
1.0will not change the pitch.magmatic.filters.PitchOctavesModifies the amount of octaves the pitch should change by relative to the original pitch. A value of
0.0will not change the pitch.magmatic.filters.PitchSemitonesModifies the amount of semitones the pitch should change by relative to the original pitch. A value of
0.0will 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.0is the original pitch.- Type
- property rate#
The rate multiplier represented as a float. A value of
1.0is the original rate.- Type
- property speed#
The speed multiplier represented as a float. A value of
1.0is the original speed.- Type
- 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 onTimescaleFilterfor 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.
- 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
TremoloFilterwhich oscillates the volume.All parameters are keyword-only.
- Parameters
- 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
VibratoFilterwhich oscillates the pitch.All parameters are keyword-only.
- Parameters
- 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.
- track_id#
The base 64 ID of the track that started playing. To resolve this into a full track object, see
track().- Type
- async track(*, metadata=None)#
This function is a coroutine.
Resolves the track ID into a
Trackobject.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
- Raises
NotFound – The track was not found.
TrackEndEvent#
- class magmatic.TrackEndEvent#
Triggered when a track ends and stops playing.
- track_id#
The base 64 ID of the track that ended playing. To resolve this into a full track object, see
track().- Type
- reason#
The reason the track ended.
- Type
- property may_start_next#
Whether it is safe for the player to start playing the next track.
- Type
- async track(*, metadata=None)#
This function is a coroutine.
Resolves the track ID into a
Trackobject.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
- Raises
NotFound – The track was not found.
TrackExceptionEvent#
- class magmatic.TrackExceptionEvent#
Triggered when a track throws an exception during playback.
- track_id#
The base 64 ID of the track that threw an exception. To resolve this into a full track object, see
track().- Type
- severity#
The severity of the exception.
- Type
- async track(*, metadata=None)#
This function is a coroutine.
Resolves the track ID into a
Trackobject.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
- Raises
NotFound – The track was not found.
TrackStuckEvent#
- class magmatic.TrackStuckEvent#
Triggered when a track is stuck.
- track_id#
The base 64 ID of the track that is stuck. To resolve this into a full track object, see
track().- Type
- async track(*, metadata=None)#
This function is a coroutine.
Resolves the track ID into a
Trackobject.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
- Raises
NotFound – The track was not found.
WebSocketCloseEvent#
- class magmatic.WebSocketCloseEvent#
Triggered when the websocket connection is closed.
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#
MemoryStats#
- class magmatic.MemoryStats#
Memory information about a given node.
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
dequeby default.- 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- clear()#
Removes all tracks from the queue.
- copy()#
Creates and returns a copy of the queue.
- property current#
The current track the queue is pointing to.
This is
Noneif 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
Noneif 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.
- is_empty()#
bool: Whether the queue is empty.
- is_full()#
bool: Whether the queue is full. This is always
Falsefor 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.
- jump_to_last()#
Jumps to the last track in the queue.
- Returns
The last track in the queue.
- Return type
- 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
Noneif the queue is empty.- Return type
Optional[Track[MetadataT]]
- 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.
- skip(count=1)#
Skips the next track (or
countnumber of tracks) in the queue and returns the new track. In some queue implementations, this is identical toget().In
Queue, this will ignoreLoopType.trackand move on to the next track regardless.
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.
Noneif 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-incollections.dequeitself.
- 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- clear()#
Removes all tracks from the queue.
- copy()#
Creates and returns a copy of the queue.
- property current#
The current track the queue is pointing to.
This is
Noneif 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
Noneif 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.
- is_empty()#
bool: Whether the queue is empty.
- is_full()#
bool: Whether the queue is full. This is always
Falsefor 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.
- jump_to_last()#
Jumps to the last track in the queue.
- Returns
The last track in the queue.
- Return type
- 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
Noneif the queue is empty.- Return type
Optional[Track[MetadataT]]
- 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.
- skip(count=1)#
Skips the next track (or
countnumber of tracks) in the queue and returns the new track. In some queue implementations, this is identical toget().In
Queue, this will ignoreLoopType.trackand move on to the next track regardless.
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.
Noneif 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.loop_type (
LoopType) – The loop type to use. Defaults tonone.factory (() ->
deque) – The factory function or class to use to create the internal queue. Defaults to the built-incollections.dequeitself.
- 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- clear()#
Removes all tracks from the queue.
- copy()#
Creates and returns a copy of the queue.
- property current#
The current track the queue is pointing to.
This is
Noneif 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
Noneif 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
Noneif 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.
- is_empty()#
bool: Whether the queue is empty.
- is_full()#
bool: Whether the queue is full. This is always
Falsefor 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.
- jump_to_last()#
Jumps to the last track in the queue.
- Returns
The last track in the queue.
- Return type
- 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
Noneif the queue is empty.- Return type
Optional[Track[MetadataT]]
- 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.
- reset(*, hard=False)#
Resets the queue pointer.
- 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
countnumber of tracks) in the queue and returns the new track. In some queue implementations, this is identical toget().In
Queue, this will ignoreLoopType.trackand move on to the next track regardless.
WaitableConsumptionQueue#
- class magmatic.WaitableConsumptionQueue(*, max_size=None, factory=deque, loop=None)#
A
ConsumptionQueuethat supports waiting for queues by storing a persistentasyncio.Future.See
ConsumptionQueuefor more information on parameters and attributes.The only difference in the constructor signature is that it additionally takes a
loopkwarg, 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- cancel_waiter()#
Cancels the waiter in this queue.
In consequence,
asyncio.CancelledErrorwill 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 current#
The current track the queue is pointing to.
This is
Noneif 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
Noneif 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 beNone.- Returns
The track that was retrieved.
- Return type
- 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.
- is_empty()#
bool: Whether the queue is empty.
- is_full()#
bool: Whether the queue is full. This is always
Falsefor 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.
- jump_to_last()#
Jumps to the last track in the queue.
- Returns
The last track in the queue.
- Return type
- 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
Noneif the queue is empty.- Return type
Optional[Track[MetadataT]]
- 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.
- skip(count=1)#
Skips the next track (or
countnumber of tracks) in the queue and returns the new track. In some queue implementations, this is identical toget().In
Queue, this will ignoreLoopType.trackand move on to the next track regardless.
- 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 beNone.- Returns
The track that was skipped.
- Return type
WaitableQueue#
- class magmatic.WaitableQueue(*, max_size=None, loop_type=LoopType.none, factory=deque, loop=None)#
A
Queuethat supports waiting for queues by storing a persistentasyncio.Future.See
Queuefor more information on parameters and attributes.The only difference in the constructor signature is that it additionally takes a
loopkwarg, 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- 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
- Returns
A list of discarded tracks if
discardwasTrue. IfdiscardwasFalse, this will be an empty list.- Return type
List[
Track]- Raises
QueueFull – If the queue is full and
discardwasFalse.
- cancel_waiter()#
Cancels the waiter in this queue.
In consequence,
asyncio.CancelledErrorwill 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 current#
The current track the queue is pointing to.
This is
Noneif 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
Noneif 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
Noneif 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 beNone.- Returns
The track that was retrieved.
- Return type
- 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.
- is_empty()#
bool: Whether the queue is empty.
- is_full()#
bool: Whether the queue is full. This is always
Falsefor 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.
- jump_to_last()#
Jumps to the last track in the queue.
- Returns
The last track in the queue.
- Return type
- 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
Noneif the queue is empty.- Return type
Optional[Track[MetadataT]]
- 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.
- reset(*args, **kwargs)#
Resets the queue pointer.
- 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
countnumber of tracks) in the queue and returns the new track. In some queue implementations, this is identical toget().In
Queue, this will ignoreLoopType.trackand move on to the next track regardless.
- 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 beNone.- Returns
The track that was skipped.
- Return type
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#
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#
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
Enumand its members also have the following methods:
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
eventop-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'>#