### Install Mafic on Windows Source: https://mafic.readthedocs.io/en/latest/installing This command installs the Mafic library using pip on a Windows system. Ensure you have Python 3.8 or newer installed and that 'py' is correctly configured in your system's PATH. ```bash > py -m pip install mafic ``` -------------------------------- ### Install Mafic on macOS/Linux Source: https://mafic.readthedocs.io/en/latest/installing This command installs the Mafic library using pip on macOS or Linux systems. It requires Python 3.8 or newer to be installed and accessible via the 'python3' command. ```bash $ python3 -m pip install mafic ``` -------------------------------- ### NodePool Class and Methods Source: https://mafic.readthedocs.io/en/latest/api/node-management Documentation for the NodePool class, which manages Lavalink nodes and selects them based on strategies. Includes methods for adding, closing, creating, removing, getting, and getting random nodes. ```APIDOC ## NodePool Class ### Description A class that manages nodes and chooses them based on strategies. ### Parameters - **client** (`ClientT`) - The client to use to connect to the nodes. - **default_strategies** (`Optional[StrategyList]`) - The default strategies to use when selecting a node. Defaults to [`Strategy.SHARD`, `Strategy.LOCATION`, `Strategy.USAGE`]. ## NodePool Methods ### `async add_node(node, *, player_cls=None)` #### Description Add an existing node to this pool. Generally, `create_node()` should be used instead. This is typically used after running `remove_node()` to re-add the node if it has been restarted. #### Parameters - **node** (`Node[ClientT]`) - The node to add. - **player_cls** (`Optional[type[Player[ClientT]]]) - The player class to use for this node when resuming. (New in version 2.8) #### Return type `None` ### `async close()` #### Description Close all nodes in the pool. #### Return type `None` (New in version 2.6) ### `async create_node(*, host: str, port: int, label: str, password: str, secure: bool = False, heartbeat: int = 30, timeout: float = 10, session: Optional[aiohttp.ClientSession] = None, resume_key: Optional[str] = None, regions: Optional[Sequence[Union[Group, Region, VoiceRegion]]] = None, shard_ids: Optional[Sequence[int]] = None, resuming_session_id: Optional[str] = None, player_cls: Optional[type[Player[ClientT]]] = None)` #### Description Create a node and connect it. The parameters here relate to `Node`. #### Parameters - **host** (`str`) - The host of the node to connect to. - **port** (`int`) - The port of the node to connect to. - **label** (`str`) - The label of the node used to identify it. - **password** (`str`) - The password of the node to authenticate. - **secure** (`bool`) - Whether to use SSL (TLS) or not. (Default: `False`) - **heartbeat** (`int`) - The interval to send heartbeats to the node websocket connection. (Default: `30`) - **timeout** (`float`) - The timeout to use for the node websocket connection. (Default: `10`) - **session** (`Optional[aiohttp.ClientSession]`) - The session to use for the node websocket connection. - **resume_key** (`Optional[str]`) - The key to use when resuming the node. If not provided, the key will be generated from the host, port and label. (Ignored in lavalink V4, use `resuming_session_id` instead.) - **regions** (`Optional[Sequence[Union[Group, Region, VoiceRegion]]]`) - The voice regions that the node can be used in. This is used to determine when to use this node. - **shard_ids** (`Optional[Sequence[int]]`) - The shard IDs that the node can be used in. This is used to determine when to use this node. - **resuming_session_id** (`Optional[str]`) - The session ID to use when resuming the node. If not provided, the node will not resume. This should be stored from `on_node_ready()` with `session_id` to resume the session and gain control of the players. If the node is not resuming, players will be destroyed if Lavalink loses connection to us. (New in version 2.2) - **player_cls** (`Optional[type[Player[ClientT]]]`) - The player class to use for this node when resuming. (New in version 2.8) #### Returns The created node. #### Return type `Node` #### Raises **RuntimeError** - If the node pool has not been initialized. ### `classmethod get_node(*, guild_id: Union[str, int], endpoint: Optional[str] = None, strategies: Optional[StrategyList] = None)` #### Description Get a node based on the given strategies. #### Parameters - **guild_id** (`str` | `int`) - The guild ID to get a node for. - **endpoint** (`Optional[str]`) - The endpoint to get a node for. - **strategies** (`Optional[StrategyList]`) - The strategies to use to get a node. If not provided, the default strategies will be used. #### Returns The node to use. #### Return type `Node` #### Raises **RuntimeError** - If the node pool has not been initialized. ### `classmethod get_random_node()` #### Description Get a random node. #### Returns The random node. #### Return type `Node` #### Raises **ValueError** - If there are no nodes. ### `async remove_node(node: Union[Node[ClientT], str], *, transfer_players: bool = True)` #### Description Remove a node from the pool. #### Parameters - **node** (`Union[Node[ClientT], str]`) - The node to remove. - **transfer_players** (`bool`) - Whether to transfer players to other nodes or destroy them. (Default: `True`) #### Return type `None` (New in version 2.6) ``` -------------------------------- ### Plugin and Address Management Source: https://mafic.readthedocs.io/en/latest/api/node Methods for fetching information about installed plugins and managing node addresses. ```APIDOC ## Plugin and Address Management ### `fetch_plugins()` #### Description Fetches a list of plugins currently loaded and active on the Lavalink node. #### Method `async` #### Returns - `list` - A list of plugin information. ### `unmark_all_addresses()` #### Description Resets all known failed addresses for the node, allowing them to be attempted again. #### Method `async` ### `unmark_failed_address(address)` #### Description Marks a specific address as no longer failed, potentially allowing future connections through it. #### Method `async` #### Parameters - **address** (`str`) - The specific address to unmark as failed. ``` -------------------------------- ### Instantiating a Mafic Node (Conceptual) Source: https://mafic.readthedocs.io/en/latest/api/node This snippet demonstrates the conceptual way a Node is instantiated, emphasizing that manual instantiation is discouraged. Use NodePool.create_node() instead. It outlines the parameters required for creating a Node, such as host, port, password, and optional configuration for secure connections, heartbeats, timeouts, and session resumption. ```python from mafic.nodes import Node # Note: This is for demonstration. Use NodePool.create_node() in practice. # node = Node( # host='localhost', # port=2333, # password='your_password', # client=your_discord_client, # secure=False, # Set to True for WSS/HTTPS # heartbeat=30, # timeout=10, # resume_key='your_resume_key', # regions=['us', 'eu'] # ) ``` -------------------------------- ### Player Class Methods Source: https://mafic.readthedocs.io/en/latest/api/player This section details the methods available for controlling music playback and player state. ```APIDOC ## Player Class Methods ### Description Provides methods for managing music playback, player state, and audio filters. ### Methods - `clear_filters()`: Clears all applied filters. - `connect()`: Establishes a connection to the music service. - `disconnect()`: Closes the connection to the music service. - `dispatch_event()`: Dispatches a custom event. - `fetch_tracks()`: Fetches available tracks. - `has_filter()`: Checks if a specific filter is applied. - `is_connected()`: Returns a boolean indicating if the player is connected. - `pause()`: Pauses the current playback. - `play()`: Starts or resumes playback. - `remove_filter()`: Removes a specified filter. - `resume()`: Resumes playback after being paused. - `seek()`: Seeks to a specific position in the current track. - `set_volume()`: Sets the playback volume. - `stop()`: Stops the current playback. - `transfer_to()`: Transfers playback to another node. - `update()`: Updates the player's state. ### Properties - `connected` (bool): Indicates if the player is currently connected. - `current` (Track): The currently playing track. - `node` (Node): The node the player is connected to. - `paused` (bool): Indicates if the player is currently paused. - `ping` (int): The ping time to the connected node. - `position` (int): The current playback position in milliseconds. ``` -------------------------------- ### Player State and Filters Source: https://mafic.readthedocs.io/en/latest/api/player Methods for managing player state like pause status, position, volume, and applying/removing filters. ```APIDOC ## GET /player/state ### Description Retrieves the current state of the player, including whether it is paused, its current position, and ping. ### Method GET ### Endpoint /player/state ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **paused** (bool) - Whether the player is currently paused. - **position** (int) - The current playback position in milliseconds. - **ping** (int) - The current ping of the player in milliseconds. #### Response Example ```json { "paused": false, "position": 123456, "ping": 78 } ``` ## POST /player/pause ### Description Pauses the current track. ### Method POST ### Endpoint /player/pause ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (str) - Indicates the success of the operation. #### Response Example ```json { "status": "paused" } ``` ## POST /player/set_volume ### Description Sets the volume for the player. ### Method POST ### Endpoint /player/set_volume ### Parameters #### Request Body - **volume** (int) - Required - The volume to set (0-1000). ### Request Example ```json { "volume": 75 } ``` ### Response #### Success Response (200) - **status** (str) - Indicates the success of the operation. #### Response Example ```json { "status": "volume_set" } ``` ## POST /player/filters/remove ### Description Removes a filter from the player. ### Method POST ### Endpoint /player/filters/remove ### Parameters #### Request Body - **label** (str) - Required - The label of the filter to remove. - **fast_apply** (bool) - Optional - Whether to seek to the current position after updating filters. Defaults to False. ### Request Example ```json { "label": "vocal_reverb", "fast_apply": true } ``` ### Response #### Success Response (200) - **status** (str) - Indicates the success of the operation. #### Response Example ```json { "status": "filter_removed" } ``` ``` -------------------------------- ### Player API Source: https://mafic.readthedocs.io/en/latest/api/index API reference for the `Player` class and related types for controlling audio playback. ```APIDOC ## Player ### Description This section describes the `Player` class, which is responsible for handling audio playback, track queuing, and search functionalities. ### Classes and Types - `Player`: The main class for controlling playback. - `SearchType`: Defines the types of searches that can be performed. ``` -------------------------------- ### Node Management API Source: https://mafic.readthedocs.io/en/latest/api/index Documentation for classes related to managing nodes within the Mafic system, including ClientT, NodePool, and various Strategy classes. ```APIDOC ## Node Management Classes ### Description This section details the classes used for managing client connections, node pools, and different strategy implementations for node selection. ### Classes - `ClientT`: Represents a client connection to a Lavalink node. - `NodePool`: Manages a collection of Lavalink nodes. - `StrategyList`: A collection of strategies. - `StrategyCallable`: A callable strategy. - `Strategy`: Abstract base class for node selection strategies. - `VoiceRegion`: Represents a voice region. - `Region`: Represents a region. - `Group`: Represents a group of nodes. ``` -------------------------------- ### Events API Source: https://mafic.readthedocs.io/en/latest/api/index API documentation for handling events and callbacks within Mafic. ```APIDOC ## Events and Callbacks ### Description This section outlines the event system in Mafic, including available event classes and how to register and handle callbacks. ### Content - Classes - Callbacks ``` -------------------------------- ### Utils API Source: https://mafic.readthedocs.io/en/latest/api/index API documentation for utility functions provided by the Mafic library. ```APIDOC ## Utils ### Description This section lists the utility functions available in Mafic that can assist with various common tasks. ``` -------------------------------- ### Connecting to a Lavalink Node Source: https://mafic.readthedocs.io/en/latest/api/node This asynchronous method establishes a connection to the Lavalink node. It handles reconnections with an optional backoff strategy and allows specifying a custom Player class. Connection attempts can time out, and exceptions like NodeAlreadyConnected may be raised. ```python import asyncio from mafic.nodes import Node # Assuming 'node' is an instance of mafic.nodes.Node async def connect_to_node(node): try: await node.connect() print(f"Successfully connected to node {node.label}") except asyncio.TimeoutError: print(f"Connection to node {node.label} timed out.") except Exception as e: print(f"An error occurred during connection: {e}") # Example usage (within an async context): # asyncio.run(connect_to_node(my_node_instance)) ``` -------------------------------- ### Configuring Session Resuming Source: https://mafic.readthedocs.io/en/latest/api/node The 'configure_resuming' method prepares the node to resume an interrupted session. This is vital for maintaining player state across temporary disconnections, especially in Lavalink v4 and above where `resuming_session_id` is preferred. ```python import asyncio from mafic.nodes import Node # Assuming 'node' is an instance of mafic.nodes.Node async def setup_resuming(node): await node.configure_resuming() print(f"Resuming configured for node {node.label}.") # Example usage (within an async context): # asyncio.run(setup_resuming(my_node_instance)) ``` -------------------------------- ### Python: Apply Filter to Audio Playback Source: https://mafic.readthedocs.io/en/latest/api/filters Demonstrates how to use the Filter class with Player.add_filter() to modify audio playback. The Filter class accepts various optional filter types as arguments. ```python from mafic import Player, Filter # Assuming player is an initialized Mafic Player instance # and track is a loaded Track object # Example: Applying volume and distortion filters my_filter = Filter( volume=0.8, # Set volume to 80% distortion=Filter.Distortion( offset=0.1, scale=1.2 ) ) player.add_filter(track, my_filter) ``` -------------------------------- ### Tracks and Playlists API Source: https://mafic.readthedocs.io/en/latest/api/index API reference for classes related to audio tracks and playlist management. ```APIDOC ## Tracks and Playlists ### Description Details the classes for representing audio tracks and managing playlists within the Mafic player. ### Classes - `Track`: Represents an audio track. - `Playlist`: Represents a playlist of tracks. ``` -------------------------------- ### Node Attributes and Initialization Source: https://mafic.readthedocs.io/en/latest/api/node Represents a Lavalink node. This class should not be instantiated manually. Instead, use `NodePool.create_node()`. It exposes various attributes and parameters for configuring and managing a Lavalink instance. ```APIDOC ## Node Class ### Description Represents a Lavalink node, which is a single instance of the Lavalink server. It manages connections, player states, and track information. ### Initialization Parameters - **host** (`str`) - The hostname or IP address of the Lavalink node. - **port** (`int`) - The port number the Lavalink node is listening on. - **label** (`str`) - A unique identifier for the node. - **password** (`str`) - The password required for authenticating with the Lavalink node. - **client** (`ClientT`) - The client instance associated with this node. - **secure** (`bool`, optional) - `True` if using a secure connection (HTTPS/WSS), `False` otherwise. Defaults to `False`. - **heartbeat** (`int`, optional) - The interval in seconds for sending heartbeat signals to the node. Defaults to `30`. - **timeout** (`float`, optional) - The timeout in seconds for waiting for responses from the node. Defaults to `10`. - **session** (`aiohttp.ClientSession`, optional) - An existing `aiohttp.ClientSession` to use for connections. - **resume_key** (`str`, optional) - The key used for resuming node connections. Ignored in Lavalink V4. - **regions** (`Sequence[Group | Region | VoiceRegion]`, optional) - A list of voice regions this node should handle. - **shard_ids** (`Sequence[int]`, optional) - A list of shard IDs this node is responsible for. - **resuming_session_id** (`str`, optional) - The session ID for resuming connections, crucial for Lavalink V4 and above. ### Attributes - **available** (`bool`) - Indicates if the node is currently connected and ready. - **client** (`ClientT`) - The client instance attached to this node. - **host** (`str`) - The hostname or IP address of the node. - **label** (`str`) - The label identifying the node. - **players** (`dict`) - A dictionary of players managed by this node. - **port** (`int`) - The port number of the node. - **regions** (`Optional[list[VoiceRegion]]`) - The voice regions the node serves. - **secure** (`bool`) - Whether the connection is secure. - **session_id** (`str`) - The session ID for the current connection. - **shard_ids** (`Optional[list[int]]`) - The shard IDs the node manages. - **stats** (`dict`) - Statistics about the node's current performance. - **version** (`str`) - The Lavalink version the node is running. - **weight** (`int`) - The weight of the node, used for load balancing. ``` -------------------------------- ### Type Aliases Source: https://mafic.readthedocs.io/en/latest/api/node-management Documentation for type aliases used within the mafic library, specifically for client types and strategy lists. ```APIDOC ## Type Aliases ### `mafic.type_variables.ClientT` #### Description A type hint for a client that is (optionally a subclass of) your library’s client. - `discord.Client` for discord.py. - `nextcord.Client` for nextcord. - `disnake.Client` for disnake. - `discord.Client` for py-cord. This is used in `NodePool` to type hint the client used to create `Node`s and `Player`s. `Node.client` will be of this type. ### `mafic.pool.StrategyList` #### Description A type hint for a list of strategies to select the best node. This can either be: - A single `StrategyCallable`. - A sequence of `Strategy`s. ``` -------------------------------- ### Player Management on a Node Source: https://mafic.readthedocs.io/en/latest/api/node These methods allow for the management of player instances associated with a specific guild on the Lavalink node. 'add_player' registers a player, 'get_player' retrieves an existing player, and 'destroy' removes a player, stopping playback for that guild. ```python from mafic.nodes import Node # Assuming 'node' is an instance of mafic.nodes.Node # Assuming 'guild_id' is an integer representing the guild # Assuming 'player' is an instance of a Player class # Add a player # node.add_player(guild_id, player) # Get a player # retrieved_player = node.get_player(guild_id) # Destroy a player # node.destroy(guild_id) ``` -------------------------------- ### Player Management Source: https://mafic.readthedocs.io/en/latest/api/node Methods for managing audio players on a Lavalink node, including adding, fetching, and destroying players. ```APIDOC ## Player Management ### `add_player(guild_id, player)` #### Description Adds an existing player to the node's management. #### Method `def` #### Parameters - **guild_id** (`int`) - The ID of the guild to associate the player with. - **player** (`Player[ClientT]`) - The player instance to add. ### `destroy(guild_id)` #### Description Destroys the player associated with the given guild ID on the Lavalink node. #### Method `def` #### Parameters - **guild_id** (`int`) - The ID of the guild whose player should be destroyed. ### `fetch_player(guild_id)` #### Description Retrieves a player instance associated with the given guild ID from the Lavalink node. #### Method `async` #### Parameters - **guild_id** (`int`) - The ID of the guild whose player to fetch. #### Returns - `Player[ClientT]` - The fetched player instance. ### `get_player(guild_id)` #### Description Returns the player instance for the given guild ID if it exists locally, without making an external request. #### Method `def` #### Parameters - **guild_id** (`int`) - The ID of the guild whose player to retrieve. #### Returns - `Player[ClientT]` or `None` - The player instance if found, otherwise `None`. ### `remove_player(guild_id)` #### Description Removes a player associated with the given guild ID from the node's management. #### Method `def` #### Parameters - **guild_id** (`int`) - The ID of the guild whose player to remove. ### `sync_players()` #### Description Synchronizes the state of all players managed by this node with the Lavalink server. #### Method `async` ``` -------------------------------- ### Filters API Source: https://mafic.readthedocs.io/en/latest/api/index API documentation for various audio filters that can be applied to playback. ```APIDOC ## Filters ### Description This section describes the various audio filters available in Mafic, which can be applied to modify the playback sound. ### Filter Classes - `Filter`: Base class for filters. - `ChannelMix`: Adjusts channel volumes. - `Distortion`: Applies distortion effects. - `EQBand`: Represents an equalizer band. - `Equalizer`: Applies equalizer adjustments. - `Karaoke`: Applies karaoke effect. - `LowPass`: Applies a low-pass filter. - `Rotation`: Applies audio rotation. - `Timescale`: Adjusts playback speed and pitch. - `Tremolo`: Applies tremolo effect. - `Vibrato`: Applies vibrato effect. ``` -------------------------------- ### Node Availability Check Source: https://mafic.readthedocs.io/en/latest/api/node The 'available' property provides a boolean status indicating whether the node is currently connected and ready to accept commands. This is crucial for ensuring that operations are only attempted on active and responsive nodes. ```python from mafic.nodes import Node # Assuming 'node' is an instance of mafic.nodes.Node # Check if the node is available # is_available = node.available # print(f"Node available: {is_available}") ``` -------------------------------- ### Errors and Warnings API Source: https://mafic.readthedocs.io/en/latest/api/index API reference for error and warning handling within the Mafic library. ```APIDOC ## Errors and Warnings ### Description This section covers the error and warning types raised by the Mafic library, aiding in debugging and issue resolution. ### Content - Errors - Warnings ``` -------------------------------- ### Fetching Tracks from a Node Source: https://mafic.readthedocs.io/en/latest/api/node This asynchronous method retrieves track information from the Lavalink node based on a query. It can accept a search query or a direct track URL/identifier. The method returns a list of decoded Track objects. ```python import asyncio from mafic.nodes import Node # Assuming 'node' is an instance of mafic.nodes.Node async def fetch_tracks_from_node(node, query): try: tracks = await node.fetch_tracks(query) print(f"Found {len(tracks)} tracks for query: '{query}'") # Process the tracks list return tracks except Exception as e: print(f"Error fetching tracks: {e}") return [] # Example usage (within an async context): # search_query = "Bohemian Rhapsody - Queen" # found_tracks = asyncio.run(fetch_tracks_from_node(my_node_instance, search_query)) ``` -------------------------------- ### IP Block Management API Source: https://mafic.readthedocs.io/en/latest/api/index Documentation for classes and types related to managing IP blocks and routing strategies within Mafic. ```APIDOC ## IP Block Management ### Description This section details the components for managing IP address blocks, route planning, and status tracking for network balancing. ### Classes and Types - `IPRoutePlannerType`: Type for IP route planners. - `IPBlockType`: Type for IP blocks. - `IPBlock`: Represents an IP block. - `FailingAddress`: Represents a failing network address. - `BaseIPRoutePlannerStatus`: Base class for IP route planner status. - `BalancingIPRoutePlannerStatus`: Status for balancing IP route planners. - `NanoIPRoutePlannerStatus`: Status for nano IP route planners. - `RotatingIPRoutePlannerStatus`: Status for rotating IP route planners. - `RotatingNanoIPRoutePlannerStatus`: Status for rotating nano IP route planners. - `RoutePlannerStatus`: General route planner status. ``` -------------------------------- ### Player Playback Control Source: https://mafic.readthedocs.io/en/latest/api/player Methods for controlling audio playback, including playing, pausing, resuming, seeking, and stopping tracks. ```APIDOC ## POST /player/play ### Description Plays a given track. This method can be used to start a new track or replace the current one. ### Method POST ### Endpoint /player/play ### Parameters #### Request Body - **track** (Track | str) - Required - The track to play. Can be a Track object or an identifier. - **start_time** (Optional[int]) - Optional - The position to start the track at in milliseconds. - **end_time** (Optional[int]) - Optional - The time to end the track at in milliseconds. - **volume** (Optional[int]) - Optional - The volume to play the track at (0-1000). - **replace** (bool) - Optional - Whether to replace the current track if one is playing. Defaults to True. - **pause** (Optional[bool]) - Optional - Whether to pause the track after playing. Defaults to None. ### Request Example ```json { "track": "TRACK_IDENTIFIER", "start_time": 10000, "volume": 50, "replace": true } ``` ### Response #### Success Response (200) - **status** (str) - Indicates the success of the operation. #### Response Example ```json { "status": "playing" } ``` ## POST /player/resume ### Description Resumes the current track if it was paused. ### Method POST ### Endpoint /player/resume ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (str) - Indicates the success of the operation. #### Response Example ```json { "status": "resumed" } ``` ## POST /player/seek ### Description Seeks to a specific position in the current track. ### Method POST ### Endpoint /player/seek ### Parameters #### Request Body - **position** (int) - Required - The position to seek to, in milliseconds. ### Request Example ```json { "position": 50000 } ``` ### Response #### Success Response (200) - **status** (str) - Indicates the success of the operation. #### Response Example ```json { "status": "seeked" } ``` ## POST /player/stop ### Description Stops the current track and clears the playback queue. ### Method POST ### Endpoint /player/stop ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **status** (str) - Indicates the success of the operation. #### Response Example ```json { "status": "stopped" } ``` ``` -------------------------------- ### Mafic Warnings Source: https://mafic.readthedocs.io/en/latest/api/errors-and-warnings This section details the warnings that can be issued by the Mafic library. ```APIDOC ## Mafic Warnings ### UnsupportedVersionWarning **Description**: Represents a warning for an unsupported version of Lavalink. ``` -------------------------------- ### Playlist Object API Source: https://mafic.readthedocs.io/en/latest/api/track-and-playlist Represents a collection of audio tracks. It includes the playlist's name, the index of a selected track if applicable, and a list of Track objects. ```APIDOC ## Playlist Object ### Description Represents a playlist containing multiple tracks. It includes the playlist's name, an optional selected track index, and a list of `Track` objects. ### Attributes - **name** (str) - The name of the playlist. - **selected_track** (Optional[int]) - The index of the selected track within the `tracks` list, if any. - **tracks** (list[Track]) - A list containing `Track` objects that constitute the playlist. - **plugin_info** (dict[str, Any]) - A dictionary containing plugin-specific information. New in version 2.3. ### Class Definition (Conceptual) ```python class Playlist: def __init__(self, info: dict, tracks: list[Track], plugin_info: Optional[dict] = None): # ... initialization logic ... pass ``` ``` -------------------------------- ### Player Transfer Source: https://mafic.readthedocs.io/en/latest/api/player Method for transferring the player to a different node. ```APIDOC ## POST /player/transfer ### Description Transfers the player to a different Lavalink node. ### Method POST ### Endpoint /player/transfer ### Parameters #### Request Body - **node** (Node) - Required - The node to transfer the player to. ### Request Example ```json { "node": "NODE_ID" } ``` ### Response #### Success Response (200) - **status** (str) - Indicates the success of the operation. #### Response Example ```json { "status": "transferred" } ``` ``` -------------------------------- ### Python: Distortion Filter Configuration Source: https://mafic.readthedocs.io/en/latest/api/filters Explains the parameters for the Distortion filter, which adds a distortion effect to audio using sine, cosine, and tangent functions. The formula for distortion is provided. ```python from mafic import Filter # Example: Applying a specific sine distortion distortion_filter = Filter.Distortion( sin_offset=0.0, sin_scale=1.5, offset=0.0, scale=0.8 ) # This distortion_filter can be used when creating a Filter object # player.add_filter(track, Filter(distortion=distortion_filter)) ``` -------------------------------- ### Node Connection and Management Source: https://mafic.readthedocs.io/en/latest/api/node Methods for managing the connection to a Lavalink node, including connecting, closing, and cleaning up resources. ```APIDOC ## Node Connection Methods ### `connect(*, backoff=None, player_cls=None)` #### Description Establishes a connection to the Lavalink node. #### Method `async` #### Parameters - **backoff** (`ExponentialBackoff` or `None`, optional) - The backoff strategy for reconnection attempts. - **player_cls** (`type[Player[ClientT]]` or `None`, optional) - The player class to use when resuming sessions. #### Raises - **NodeAlreadyConnected** - If the node is already connected. - **asyncio.TimeoutError** - If the connection attempt times out. ### `close()` #### Description Closes the connection to the Lavalink node, including the websocket and session. #### Method `async` ### `cleanup()` #### Description Cleans up the node's resources, effectively disconnecting and resetting its state as if it were never connected. #### Method `def` ``` -------------------------------- ### Fetching Route Planner Status Source: https://mafic.readthedocs.io/en/latest/api/node This asynchronous method retrieves the current status of the Lavalink node's route planner. This information can be useful for diagnosing network issues or understanding how the node is routing traffic. ```python import asyncio from mafic.nodes import Node # Assuming 'node' is an instance of mafic.nodes.Node async def get_route_planner_status(node): status = await node.fetch_route_planner_status() print(f"Route planner status for node {node.label}: {status}") return status # Example usage (within an async context): # asyncio.run(get_route_planner_status(my_node_instance)) ``` -------------------------------- ### Strategy Enum Source: https://mafic.readthedocs.io/en/latest/api/node-management Represents different strategies for selecting a node. Each strategy corresponds to a specific method of choosing a node from a pool. ```APIDOC ## Strategy Enum ### Description Represents a strategy for selecting a node. ### Enum Members - **LOCATION** (int): Selects a node based on the region the guild is in. - **RANDOM** (int): Selects a random node. - **SHARD** (int): Selects a node based on the shard ID of the guild. - **USAGE** (int): Selects a node based on the least used node. ``` -------------------------------- ### Python: Equalizer Filter Configuration Source: https://mafic.readthedocs.io/en/latest/api/filters Describes the Equalizer filter and its EQBand component. The Equalizer allows adjustment of specific frequency bands using EQBand objects, which define a band and its gain. ```python from mafic import Filter # Example: Creating an equalizer with two bands # Band 0: boost gain, Band 5: cut gain equalizer = Filter.Equalizer([ Filter.EQBand(band=0, gain=0.5), Filter.EQBand(band=5, gain=-0.3) ]) # This equalizer can be applied to a filter # player.add_filter(track, Filter(equalizer=equalizer)) ``` -------------------------------- ### Synchronizing Players Source: https://mafic.readthedocs.io/en/latest/api/node The asynchronous 'sync_players' method synchronizes the state of players between the client and the Lavalink node. This is generally handled internally but can be called manually if needed. ```python import asyncio from mafic.nodes import Node # Assuming 'node' is an instance of mafic.nodes.Node async def sync_node_players(node): await node.sync_players() print(f"Players synchronized for node {node.label}.") # Example usage (within an async context): # asyncio.run(sync_node_players(my_node_instance)) ``` -------------------------------- ### Node Cleanup Source: https://mafic.readthedocs.io/en/latest/api/node The 'cleanup' method resets the node's internal state as if it had never been connected. This can be useful for reinitializing a node or troubleshooting connection issues. ```python from mafic.nodes import Node # Assuming 'node' is an instance of mafic.nodes.Node # Perform cleanup # node.cleanup() # print("Node cleanup performed.") ``` -------------------------------- ### Mafic Custom Exceptions Source: https://mafic.readthedocs.io/en/latest/api/errors-and-warnings This section details the custom exceptions defined in the Mafic library, which extend the base Exception class to provide specific error information. ```APIDOC ## Mafic Custom Exceptions ### MaficException **Description**: The base exception class for custom exceptions raised by Mafic. ### LibraryCompatibilityError **Description**: An issue occurred when trying to find a compatible library. #### NoCompatibleLibraries **Description**: No compatible library was found. #### MultipleCompatibleLibraries(_libraries_) **Description**: Multiple compatible libraries were found. Mafic makes no attempt to assume which library you are using. ### PlayerException **Description**: An issue occurred when trying to play a track. #### TrackLoadException(_*, message, severity, cause) **Description**: An error raised when a track could not be loaded. **Parameters**: * `message` (str) - The message returned by the node. * `severity` (Literal["COMMON", "SUSPICIOUS", "FATAL"]) - The severity of the error. This is lowercase in Lavalink v4. * `cause` (str) - The cause of the error. #### PlayerNotConnected **Description**: An error raised when a player is not connected to a voice channel. ### HTTPException(_status, message) **Description**: An issue occurred when trying to make a request to the Lavalink REST API. #### HTTPBadRequest(_message) **Description**: An error raised when a bad request is made to the Lavalink REST API. #### HTTPUnauthorized(_message) **Description**: An error raised when an unauthorized request is made to the Lavalink REST API. #### HTTPNotFound(_message) **Description**: An error raised when a request is made to a non-existent endpoint. ### NodeAlreadyConnected **Description**: An error raised when a node is already connected to Mafic. ### NoNodesAvailable **Description**: An error raised when no nodes are available to handle a player. ``` -------------------------------- ### Track and Route Planner Operations Source: https://mafic.readthedocs.io/en/latest/api/node Methods for decoding track data and interacting with the route planner. ```APIDOC ## Track and Route Planner ### `decode_track(track)` #### Description Decodes a single track from its base64 encoded string representation. #### Method `async` #### Parameters - **track** (`str`) - The base64 encoded track string. #### Returns - `Track` - The decoded track object. ### `decode_tracks(tracks)` #### Description Decodes a list of tracks from their base64 encoded string representations. #### Method `async` #### Parameters - **tracks** (`list[str]`) - A list of base64 encoded track strings. #### Returns - `list[Track]` - A list of decoded track objects. ### `fetch_route_planner_status()` #### Description Retrieves the current status and statistics of the node's route planner. #### Method `async` #### Returns - `dict` - A dictionary containing route planner status information. ``` -------------------------------- ### Node Stats API Source: https://mafic.readthedocs.io/en/latest/api/index API documentation for classes that provide statistics about Lavalink nodes, including CPU, memory, and frame data. ```APIDOC ## Node Statistics ### Description This section covers the classes used to retrieve and analyze statistics from Lavalink nodes, such as CPU usage, memory consumption, and network frame information. ### Classes - `NodeStats`: Base class for node statistics. - `CPUStats`: Statistics related to CPU usage. - `MemoryStats`: Statistics related to memory usage. - `FrameStats`: Statistics related to network frames. ``` -------------------------------- ### Search Types Source: https://mafic.readthedocs.io/en/latest/api/player Available types for searching music content. ```APIDOC ## SearchType Enum ### Description Enumerates the different sources and types for searching music content. ### Members - `APPLE_MUSIC`: Search on Apple Music. - `DEEZER_ISRC`: Search by ISRC on Deezer. - `DEEZER_SEARCH`: General search on Deezer. - `SOUNDCLOUD`: Search on SoundCloud. - `SPOTIFY_RECOMMENDATIONS`: Get recommendations from Spotify. - `SPOTIFY_SEARCH`: General search on Spotify. - `TTS`: Text-to-speech audio source. - `VK_MUSIC`: Search on VK Music. - `YANDEX_MUSIC`: Search on Yandex Music. - `YOUTUBE`: Search on YouTube. - `YOUTUBE_MUSIC`: Search on YouTube Music. ``` -------------------------------- ### Unmarking Addresses Source: https://mafic.readthedocs.io/en/latest/api/node These methods are used to manage the node's internal list of network addresses. 'unmark_all_addresses' clears all previously marked addresses, while 'unmark_failed_address' removes a specific failed address, potentially aiding in network recovery. ```python import asyncio from mafic.nodes import Node # Assuming 'node' is an instance of mafic.nodes.Node async def manage_addresses(node, address_to_unmark=None): await node.unmark_all_addresses() print(f"All addresses unmarked for node {node.label}.") if address_to_unmark: await node.unmark_failed_address(address_to_unmark) print(f"Failed address '{address_to_unmark}' unmarked.") # Example usage (within an async context): # asyncio.run(manage_addresses(my_node_instance, '192.168.1.1')) ``` -------------------------------- ### Node Stats API Source: https://mafic.readthedocs.io/en/latest/api/stats Retrieves detailed statistics for a specific server node. This includes information about players, CPU, memory, and uptime. ```APIDOC ## GET /nodes/{nodeId}/stats ### Description Fetches detailed statistics for a specific server node. ### Method GET ### Endpoint /nodes/{nodeId}/stats ### Parameters #### Path Parameters - **nodeId** (string) - Required - The unique identifier of the node. ### Response #### Success Response (200) - **cpu** (object) - CPU statistics for the node. - **cores** (integer) - The number of CPU cores. - **system_load** (integer) - The overall system load. - **lavalink_load** (integer) - The load specifically used by Lavalink. - **frame_stats** (object or null) - Frame statistics for the node, if available. - **sent** (integer) - The number of frames sent. - **nulled** (integer) - The number of nulled frames. - **deficit** (integer) - The frame deficit. - **memory** (object) - Memory statistics for the node. - **free** (integer) - The amount of free memory in bytes. - **used** (integer) - The amount of used memory in bytes. - **allocated** (integer) - The amount of allocated memory in bytes. - **reservable** (integer) - The amount of reservable memory in bytes. - **player_count** (integer) - The total number of players connected to the node. - **playing_player_count** (integer) - The number of players currently playing audio. - **uptime** (datetime.timedelta) - The uptime of the node. #### Response Example ```json { "cpu": { "cores": 8, "system_load": 50, "lavalink_load": 20 }, "frame_stats": { "sent": 10000, "nulled": 5, "deficit": 0 }, "memory": { "free": 1073741824, "used": 536870912, "allocated": 2147483648, "reservable": 2147483648 }, "player_count": 50, "playing_player_count": 30, "uptime": "3 days, 2 hours, 15 minutes" } ``` ``` -------------------------------- ### Track Object API Source: https://mafic.readthedocs.io/en/latest/api/track-and-playlist Represents a single audio track within the Mafic library. It contains detailed information about the track, such as its ID, title, author, duration, and source. ```APIDOC ## Track Object ### Description Represents a track with various attributes including artwork, author, ID, identifier, ISRC, length, position, seekable status, source, stream status, title, and URI. ### Attributes - **artwork_url** (Optional[str]) - The artwork URL of the track. This is always `None` if the node does not use Lavalink v4. New in version 2.2. - **author** (str) - The author of the track. - **id** (str) - The ID of the track. This is base64 encoded data used by Lavalink. - **identifier** (str) - The identifier of the track. This is the ID of the track on the source. - **isrc** (Optional[str]) - The ISRC of the track. This is always `None` if the node does not use Lavalink v4. New in version 2.2. - **length** (int) - The length of the track in milliseconds. - **position** (int) - The current playback position of the track in milliseconds. - **seekable** (bool) - Indicates whether the track can be seeked. - **source** (str) - The source of the track (e.g., "youtube", "soundcloud"). - **stream** (bool) - Indicates if the track is a stream. - **title** (str) - The title of the track. - **uri** (Optional[str]) - The URI of the track. ### Class Definition (Conceptual) ```python class Track: def __init__(self, track_id: str, title: str, identifier: str, uri: Optional[str], source: str, stream: bool, seekable: bool, position: int = 0, length: int, artwork_url: Optional[str] = None, isrc: Optional[str] = None): # ... initialization logic ... pass ``` ``` -------------------------------- ### Python: ChannelMix Filter Configuration Source: https://mafic.readthedocs.io/en/latest/api/filters Details on configuring the ChannelMix filter to manipulate audio channel mixing. This filter allows control over how much of each channel is mixed into the left and right outputs. ```python from mafic import Filter # Example: Making audio mono by mixing channels equally mono_filter = Filter.ChannelMix( left_to_left=0.5, left_to_right=0.5, right_to_left=0.5, right_to_right=0.5 ) # This mono_filter can then be passed to the Filter constructor or added directly # player.add_filter(track, Filter(channel_mix=mono_filter)) ``` -------------------------------- ### Timescale Filter Configuration Source: https://mafic.readthedocs.io/en/latest/api/filters Modifies the speed, pitch, and rate of audio playback. 'speed', 'pitch', and 'rate' parameters must all be at least 0.0, with 1.0 representing normal values. ```python class Timescale(_speed =None_, _pitch =None_, _rate =None_): """Represents a filter which is used to change the speed, pitch and rate of audio. """ speed = None # The speed of the audio. Must be at least 0.0. pitch = None # The pitch of the audio. Must be at least 0.0. rate = None # The rate of the audio. Must be at least 0.0. ```