### Install aiomarzban Source: https://github.com/p1nk-l0rd/aiomarzban/blob/main/README.md Use pip to install the library. ```bash pip install aiomarzban --upgrade ``` -------------------------------- ### Get Node Settings and Usage Statistics Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Retrieve essential node configuration settings, including the minimum required node version and the server certificate for new node connections. Also, fetch and display traffic usage statistics for all nodes within a specified date range. ```python async def node_info(): # Get node settings (certificate for connecting new nodes) settings = await marzban.get_node_settings() print(f"Min version: {settings.min_node_version}") print(f"Certificate: {settings.certificate[:50]}...") # Get all nodes' usage statistics usage = await marzban.get_nodes_usage(start="2024-01-01", end="2024-12-31") for node_usage in usage.usages: total = node_usage.uplink + node_usage.downlink print(f"{node_usage.node_name}: {total / (1024**3):.2f} GB") ``` -------------------------------- ### Get System Statistics Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Monitor system resources and user statistics. This provides an overview of the panel's health and user activity. ```python async def get_system_stats(): stats = await marzban.get_system_stats() print(f"Panel Version: {stats.version}") print(f"Memory: {stats.mem_used / (1024**3):.2f} / {stats.mem_total / (1024**3):.2f} GB") print(f"CPU: {stats.cpu_usage}% ({stats.cpu_cores} cores)") print(f"Total Users: {stats.total_user}") print(f"Online Users: {stats.online_users}") print(f"Active: {stats.users_active}, On Hold: {stats.users_on_hold}") print(f"Disabled: {stats.users_disabled}, Expired: {stats.users_expired}") print(f"Limited: {stats.users_limited}") print(f"Bandwidth In: {stats.incoming_bandwidth / (1024**3):.2f} GB") print(f"Bandwidth Out: {stats.outgoing_bandwidth / (1024**3):.2f} GB") ``` -------------------------------- ### Get or Create User Idempotently Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Atomically retrieve an existing user by username or create a new one with specified subscription details if it does not exist. This ensures a user record is always available. ```python async def idempotent_user_creation(): # Returns existing user or creates new one user = await marzban.get_or_create_user( username="user123", days=30, data_limit=50, proxies={"vless": {"flow": ""}}, ) print(f"User: {user.username}, Created: {user.created_at}") ``` -------------------------------- ### GET /api/admin/list Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Get a list of all admins with pagination support. ```APIDOC ## GET /api/admin/list ### Description Get a list of all admins with pagination support. ### Method GET ### Endpoint /api/admin/list ### Parameters #### Query Parameters - **offset** (int) - Optional - The number of admins to skip (for pagination). - **limit** (int) - Optional - The maximum number of admins to return. - **username** (str) - Optional - Filter admins by username (supports partial matching). ### Request Example ```python admins = await marzban.get_admins(offset=0, limit=50, username="support") for admin in admins: print(f"Admin: {admin.username}, Sudo: {admin.is_sudo}") ``` ### Response #### Success Response (200) - List of Admin objects, each containing: - **username** (str) - The username of the admin. - **is_sudo** (bool) - Whether the admin has sudo privileges. - **telegram_id** (int | None) - The Telegram ID for notifications. - **discord_webhook** (str | None) - The Discord webhook URL for notifications. #### Response Example ```json [ { "username": "support_admin", "is_sudo": false, "telegram_id": 123456789, "discord_webhook": "https://discord.com/api/webhooks/..." } ] ``` ``` -------------------------------- ### Enable All Inbounds and Get Online Users Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Enable all available inbounds for a specific user and retrieve a list of all currently online users. Online users are defined as those active within the last 60 seconds. ```python async def inbound_and_online_operations(): # Get a user and enable all inbounds user = await marzban.get_user("user123") user = await marzban.user_set_all_inbounds(user) print(f"Enabled inbounds: {list(user.inbounds.keys())}") # Get all currently online users (active within last 60 seconds) online = await marzban.get_online_users() print(f"Online users: {online.total}") for user in online.users: print(f" {user.username} - last seen: {user.online_at}") ``` -------------------------------- ### List Users with Filters and Sorting Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Query users based on various criteria including status, search terms, and pagination. Sorting is supported, for example, by creation date in descending order. Can also retrieve specific users by providing a list of usernames. ```python from aiomarzban import UserStatus async def list_users(): # Get all users with pagination result = await marzban.get_users( offset=0, limit=100, status=UserStatus.active, search="premium", # Search in username/note sort="-created_at", # Sort by creation date descending timeout=40, # Custom timeout for large queries ) print(f"Total users: {result.total}") for user in result.users: print(f" {user.username}: {user.status}, {user.used_traffic} bytes used") # Get specific users by username list specific_users = await marzban.get_users(username=["user1", "user2", "user3"]) ``` -------------------------------- ### GET /api/admin/usage/{username} Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Get the total data usage of all users managed by a specific admin. ```APIDOC ## GET /api/admin/usage/{username} ### Description Get the total data usage of all users managed by a specific admin. ### Method GET ### Endpoint /api/admin/usage/{username} ### Parameters #### Path Parameters - **username** (str) - Required - The username of the admin. ### Request Example ```python usage = await marzban.get_admin_usage("support_admin") print(f"Total usage: {usage} bytes") ``` ### Response #### Success Response (200) - **usage** (int) - The total data usage in bytes. #### Response Example ```json { "usage": 10737418240 } ``` ``` -------------------------------- ### GET /api/admin/me Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Retrieve information about the currently authenticated admin account. ```APIDOC ## GET /api/admin/me ### Description Retrieve information about the currently authenticated admin account. ### Method GET ### Endpoint /api/admin/me ### Response #### Success Response (200) - **username** (str) - The username of the admin. - **is_sudo** (bool) - Whether the admin has sudo privileges. - **telegram_id** (int | None) - The Telegram ID for notifications. - **discord_webhook** (str | None) - The Discord webhook URL for notifications. - **users_usage** (int) - Total usage of users managed by this admin. #### Response Example ```json { "username": "admin", "is_sudo": true, "telegram_id": null, "discord_webhook": null, "users_usage": 0 } ``` ``` -------------------------------- ### Get and Modify User Details Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Retrieve a user's current status and traffic usage, then update their settings such as data limit, status, and notes. Ensure the username exists before attempting modification. ```python from aiomarzban import UserStatusModify, UserDataLimitResetStrategy async def manage_user(): # Get user details user = await marzban.get_user("user123") print(f"Status: {user.status}") print(f"Used Traffic: {user.used_traffic / (1024**3):.2f} GB") print(f"Online At: {user.online_at}") # Modify user modified_user = await marzban.modify_user( username="user123", data_limit=200, # Increase to 200 GB status=UserStatusModify.active, note="Upgraded to premium", data_limit_reset_strategy=UserDataLimitResetStrategy.month, ) print(f"Updated data limit: {modified_user.data_limit}") ``` -------------------------------- ### Manage Nodes: Get, Modify, Reconnect, Remove Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Perform lifecycle operations on proxy nodes, including retrieving all nodes, fetching a specific node by ID, modifying its settings, reconnecting it, and removing it from the panel. Requires node IDs for modification and removal. ```python from aiomarzban import NodeStatus async def manage_nodes(): # Get all nodes nodes = await marzban.get_nodes() for node in nodes: print(f"{node.name} ({node.address}): {node.status}") # Get specific node node = await marzban.get_node(node_id=1) print(f"Node details: {node}") # Modify node modified = await marzban.modify_node( node_id=1, name="Germany Server v2", usage_coefficient=0.5, # 50% traffic counting status=NodeStatus.disabled, ) # Reconnect node await marzban.reconnect_node(node_id=1) # Remove node await marzban.remove_node(node_id=1) ``` -------------------------------- ### User Management - Get and Modify User Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Retrieve user details and update user settings, including status changes and data limits. ```APIDOC ## GET /api/v1/user/{username} ### Description Retrieves the details of a specific user. ### Method GET ### Endpoint /api/v1/user/{username} ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user to retrieve. ### Response #### Success Response (200) - **username** (string) - The username. - **status** (string) - The current status of the user. - **used_traffic** (integer) - The amount of traffic used in bytes. - **online_at** (integer) - Unix timestamp of the last online activity. ### Response Example ```json { "username": "user123", "status": "active", "used_traffic": 5368709120, "online_at": 1700000000 } ``` ## PUT /api/v1/user/{username} ### Description Modifies the settings of an existing user. ### Method PUT ### Endpoint /api/v1/user/{username} ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user to modify. #### Request Body - **data_limit** (integer) - Optional - The new data limit in GB. - **status** (string) - Optional - The new status of the user. Enum: `"active"`, `"inactive"`, `"suspended"`. - **note** (string) - Optional - The updated note for the user. - **data_limit_reset_strategy** (string) - Optional - The new data limit reset strategy. Enum: `"none"`, `"month"`, `"week"`, `"day"`. ### Response #### Success Response (200) - **username** (string) - The username of the modified user. - **data_limit** (integer) - The updated data limit in bytes. - **status** (string) - The updated status. - **note** (string) - The updated note. ### Response Example ```json { "username": "user123", "data_limit": 214748364800, "status": "active", "note": "Upgraded to premium" } ``` ``` -------------------------------- ### Initializing MarzbanAPI Client Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Demonstrates how to create and configure the MarzbanAPI client with basic or advanced settings, including default user parameters and request configurations. ```APIDOC ## Initializing MarzbanAPI Client Create and configure the MarzbanAPI client with panel credentials and optional default user settings. The client handles authentication automatically and refreshes tokens when needed. ### Request Example ```python from aiomarzban import MarzbanAPI, UserDataLimitResetStrategy # Basic initialization marzban = MarzbanAPI( address="https://panel.example.com/", username="admin", password="your_secure_password", ) # Advanced initialization with default user settings marzban = MarzbanAPI( address="https://panel.example.com/", username="admin", password="your_secure_password", sub_path="sub", # Subscription URL path # Default user parameters (applied when creating users) default_days=30, default_data_limit=50, # 50 GB default_data_limit_reset_strategy=UserDataLimitResetStrategy.month, default_proxies={"vless": {"flow": ""}}, default_inbounds={"vless": ["VLESS TCP REALITY"]}, # Request settings timeout=10, # seconds retries=3, # retry count after failure ) ``` ``` -------------------------------- ### Initialize MarzbanAPI Client Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Configure the client with panel credentials and optional default settings for user creation and request behavior. ```python from aiomarzban import MarzbanAPI, UserDataLimitResetStrategy # Basic initialization marzban = MarzbanAPI( address="https://panel.example.com/", username="admin", password="your_secure_password", ) # Advanced initialization with default user settings marzban = MarzbanAPI( address="https://panel.example.com/", username="admin", password="your_secure_password", sub_path="sub", # Subscription URL path # Default user parameters (applied when creating users) default_days=30, default_data_limit=50, # 50 GB default_data_limit_reset_strategy=UserDataLimitResetStrategy.month, default_proxies={"vless": {"flow": ""}}, default_inbounds={"vless": ["VLESS TCP REALITY"]}, # Request settings timeout=10, # seconds retries=3, # retry count after failure ) ``` -------------------------------- ### Add New User with Subscription Settings Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Create a new user with specified subscription details like duration, data limits, and status. Data limits are automatically converted from GB to bytes. ```python from aiomarzban import MarzbanAPI, UserDataLimitResetStrategy, UserStatusCreate async def create_user(): user = await marzban.add_user( username="user123", days=90, # 90-day subscription (alternative: expire=unix_timestamp) data_limit=100, # 100 GB data_limit_reset_strategy=UserDataLimitResetStrategy.month, proxies={"vless": {"flow": "xtls-rprx-vision"}}, inbounds={"vless": ["VLESS TCP REALITY"]}, note="Premium user", status=UserStatusCreate.active, auto_delete_in_days=7, # Auto-delete 7 days after expiration ) print(f"Username: {user.username}") print(f"Subscription URL: {user.subscription_url}") print(f"Links: {user.links}") print(f"Expires: {user.expire}") # Unix timestamp print(f"Data Limit: {user.data_limit} bytes") ``` -------------------------------- ### Manage User Templates Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Create, list, retrieve, modify, and delete user templates for provisioning. Templates define default settings for new users. ```python async def manage_templates(): # Create template template = await marzban.add_user_template( name="Basic Plan", data_limit=30, # 30 GB expire_duration=2592000, # 30 days in seconds username_prefix="basic_", inbounds={"vless": ["VLESS TCP REALITY"]}, ) print(f"Template ID: {template.id}") # List all templates templates = await marzban.get_user_templates() for t in templates: print(f"{t.name}: {t.data_limit} bytes, {t.expire_duration}s") # Get specific template template = await marzban.get_user_template(template_id=1) # Modify template modified = await marzban.modify_user_template( template_id=1, data_limit=50, # Upgrade to 50 GB name="Premium Plan", ) # Delete template await marzban.remove_user_template(template_id=1) ``` -------------------------------- ### Create New Admin Account Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Provision a new admin with specific permissions and optional notification integrations. ```python async def create_new_admin(): new_admin = await marzban.create_admin( username="support_admin", password="secure_password_123", is_sudo=False, # Non-sudo admin telegram_id=123456789, # Optional Telegram notifications discord_webhook="https://discord.com/api/webhooks/...", # Optional Discord ) print(f"Created admin: {new_admin.username}") # Returns: Admin(username='support_admin', is_sudo=False, telegram_id=123456789, ...) ``` -------------------------------- ### Interact with Marzban API Source: https://github.com/p1nk-l0rd/aiomarzban/blob/main/README.md Initialize the MarzbanAPI client and perform common administrative tasks like user and node management. ```python from aiomarzban import MarzbanAPI, UserDataLimitResetStrategy, UserStatusModify marzban = MarzbanAPI( address="https://my_domain.com/", username="admin", password="super_secret_password", default_proxies={"vless": {"flow": ""}}, ) async def main(): # Create admin new_admin = await marzban.create_admin(username="new_admin", password="12345678", is_sudo=False) print("New admin: ", new_admin) # Create user new_user = await marzban.add_user( username="user1", days=90, data_limit=100, # In GB data_limit_reset_strategy=UserDataLimitResetStrategy.month, ) print("New user: ", new_user) # Modify user modified_user = await marzban.modify_user( username="user1", status=UserStatusModify.disabled, ) print("Modified user: ", modified_user) # Add days of subscription to user modified_user = await marzban.user_add_days("user1", 60) print("Modified user: ", modified_user) # Get users users = await marzban.get_users(offset=0, limit=100) print("Users: ", users) # Create node new_node = await marzban.add_node( name="New node", address="8.8.8.8", ) print("New node: ", new_node) # Modify node modified_node = await marzban.modify_node( node_id=new_node.id, usage_coefficient=0.2, ) print("Modified node: ", modified_node) ``` -------------------------------- ### POST /api/admin/add Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Create a new admin account with specified permissions and optional notification integrations. ```APIDOC ## POST /api/admin/add ### Description Create a new admin account with specified permissions and optional notification integrations. ### Method POST ### Endpoint /api/admin/add ### Parameters #### Request Body - **username** (str) - Required - The username for the new admin. - **password** (str) - Required - The password for the new admin. - **is_sudo** (bool) - Optional - Whether the new admin should have sudo privileges (defaults to false). - **telegram_id** (int) - Optional - Telegram ID for notifications. - **discord_webhook** (str) - Optional - Discord webhook URL for notifications. ### Request Example ```python new_admin = await marzban.create_admin( username="support_admin", password="secure_password_123", is_sudo=False, # Non-sudo admin telegram_id=123456789, # Optional Telegram notifications discord_webhook="https://discord.com/api/webhooks/...", # Optional Discord ) ``` ### Response #### Success Response (200) - **username** (str) - The username of the newly created admin. - **is_sudo** (bool) - Whether the new admin has sudo privileges. - **telegram_id** (int | None) - The Telegram ID for notifications. - **discord_webhook** (str | None) - The Discord webhook URL for notifications. #### Response Example ```json { "username": "support_admin", "is_sudo": false, "telegram_id": 123456789, "discord_webhook": "https://discord.com/api/webhooks/..." } ``` ``` -------------------------------- ### User Management - Add User Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Create a new user with specified subscription settings. Data limits are handled in GB and converted to bytes. ```APIDOC ## POST /api/v1/user ### Description Creates a new user with subscription details, including data limits, subscription duration, and status. ### Method POST ### Endpoint /api/v1/user ### Parameters #### Request Body - **username** (string) - Required - The username for the new user. - **days** (integer) - Optional - The number of days the subscription is valid. Alternatively, use `expire`. - **expire** (integer) - Optional - Unix timestamp for subscription expiration. Use instead of `days`. - **data_limit** (integer) - Optional - The data limit for the user in GB. This will be converted to bytes. - **data_limit_reset_strategy** (string) - Optional - Strategy for resetting the data limit. Enum: `"none"`, `"month"`, `"week"`, `"day"`. - **proxies** (object) - Optional - Proxy configuration for the user. - **inbounds** (object) - Optional - Inbound configurations for the user. - **note** (string) - Optional - A note or description for the user. - **status** (string) - Optional - The initial status of the user. Enum: `"active"`, `"inactive"`, `"suspended"`. - **auto_delete_in_days** (integer) - Optional - Number of days after expiration to automatically delete the user. ### Response #### Success Response (200) - **username** (string) - The username of the created user. - **subscription_url** (string) - The generated subscription URL. - **links** (object) - Links associated with the user's subscription. - **expire** (integer) - Unix timestamp of the subscription expiration. - **data_limit** (integer) - The data limit in bytes. ### Request Example ```json { "username": "user123", "days": 90, "data_limit": 100, "data_limit_reset_strategy": "month", "proxies": {"vless": {"flow": "xtls-rprx-vision"}}, "inbounds": {"vless": ["VLESS TCP REALITY"]}, "note": "Premium user", "status": "active", "auto_delete_in_days": 7 } ``` ### Response Example ```json { "username": "user123", "subscription_url": "https://your.marzban.server/api/v1/subscription/your_uuid", "links": {"vless": "vless://...", "trojan": "trojan://..."}, "expire": 1735689600, "data_limit": 107374182400 } ``` ``` -------------------------------- ### Run tests Source: https://github.com/p1nk-l0rd/aiomarzban/blob/main/README.md Execute the test suite using pytest after configuring the .env file. ```bash pytest tests/ ``` -------------------------------- ### Manage Inbounds and Hosts Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Manage proxy inbounds and host configurations. This includes retrieving and modifying host settings. ```python async def manage_hosts(): # Get all inbounds inbounds = await marzban.get_inbounds() for protocol, inbound_list in inbounds.items(): print(f"{protocol}:") for inbound in inbound_list: print(f" {inbound['tag']}: {inbound['port']}") # Get all hosts hosts = await marzban.get_hosts() for tag, host_list in hosts.items(): print(f"{tag}: {len(host_list)} hosts") # Modify hosts (update entire host configuration) updated_hosts = await marzban.modify_hosts(hosts) ``` -------------------------------- ### Manage Xray Core Service Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Control and configure the Xray core service, including retrieving status, configuration, and restarting the service. Ensure the core is running and configured as expected. ```python async def manage_core(): # Get core status stats = await marzban.get_core_stats() print(f"Xray Version: {stats.version}") print(f"Started: {stats.started}") print(f"Logs WebSocket: {stats.logs_websocket}") # Get core configuration config = await marzban.get_core_config() print(f"Config: {config}") # Modify core configuration config["log"]["loglevel"] = "warning" updated_config = await marzban.modify_core_config(config) # Restart core await marzban.restart_core() print("Core restarted") ``` -------------------------------- ### User Management - List Users with Filters Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Query users with various filters, pagination, and sorting options. ```APIDOC ## GET /api/v1/users ### Description Retrieves a list of users, supporting filtering, pagination, and sorting. ### Method GET ### Endpoint /api/v1/users ### Parameters #### Query Parameters - **offset** (integer) - Optional - The number of users to skip (for pagination). - **limit** (integer) - Optional - The maximum number of users to return. - **status** (string) - Optional - Filter users by status. Enum: `"active"`, `"inactive"`, `"suspended"`. - **search** (string) - Optional - Search term to filter by username or note. - **sort** (string) - Optional - Field to sort by. Prefix with `-` for descending order (e.g., `-created_at`). - **timeout** (integer) - Optional - Custom timeout in seconds for the query. - **username** (array of strings) - Optional - Filter users by a list of specific usernames. ### Response #### Success Response (200) - **total** (integer) - The total number of users matching the query. - **users** (array of objects) - A list of user objects. - **username** (string) - The username. - **status** (string) - The user's status. - **used_traffic** (integer) - The traffic used in bytes. ### Response Example ```json { "total": 150, "users": [ { "username": "premium_user", "status": "active", "used_traffic": 10737418240 }, { "username": "trial_user", "status": "active", "used_traffic": 536870912 } ] } ``` ``` -------------------------------- ### Transfer User Ownership and Activate Next Plan Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Transfer user ownership to another admin and activate the user's next scheduled plan. Ensure the target admin exists and the user has a configured next plan. ```python async def advanced_user_operations(): # Transfer user to another admin user = await marzban.set_owner( username="user123", admin_username="support_admin" ) print(f"User {user.username} now owned by {user.admin.username}") # Activate user's next plan (if configured) user = await marzban.active_next_plan("user123") print(f"Next plan activated: {user.expire}, {user.data_limit}") ``` -------------------------------- ### Access Subscription Endpoints Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Retrieve subscription information and usage data using user tokens. This is typically used by client applications. ```python async def subscription_access(): token = "abc123xyz" # User's subscription token # Get subscription config (returns proxy configs) config = await marzban.user_subscription( token=token, user_agent="Clash/1.0" ) # Get subscription info info = await marzban.user_subscription_info(token=token) print(f"Username: {info.username}") print(f"Status: {info.status}") print(f"Used: {info.used_traffic}, Limit: {info.data_limit}") print(f"Links: {info.links}") # Get usage via subscription token usage = await marzban.user_get_usage( token=token, start="2024-01-01", end="2024-12-31" ) # Get subscription for specific client type clash_config = await marzban.user_subscription_with_client_type( client_type="clash", token=token, user_agent="Clash/1.0" ) ``` -------------------------------- ### Add New Proxy Node Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Add a new proxy node to the Marzban panel, specifying its name, address, ports, and traffic usage coefficient. The `add_as_new_host` parameter can automatically configure it as a new host. ```python async def add_node(): node = await marzban.add_node( name="Germany Server", address="de.server.com", port=62050, # Marzban node port api_port=62051, # API port usage_coefficient=1.0, # Traffic multiplier add_as_new_host=True, # Auto-add as host ) print(f"Node ID: {node.id}") print(f"Status: {node.status}") print(f"Xray Version: {node.xray_version}") ``` -------------------------------- ### POST /api/admin/user/enable Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Activate all disabled users associated with a specific admin. ```APIDOC ## POST /api/admin/user/enable ### Description Activate all disabled users associated with a specific admin. ### Method POST ### Endpoint /api/admin/user/enable ### Parameters #### Request Body - **username** (str) - Required - The username of the admin whose users should be activated. ### Request Example ```python await marzban.activate_all_disabled_users("support_admin") print("All disabled users activated") ``` ``` -------------------------------- ### Retrieve Current Admin Information Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Fetch details about the currently authenticated admin account. ```python async def get_admin_info(): marzban = MarzbanAPI( address="https://panel.example.com/", username="admin", password="password" ) admin = await marzban.get_current_admin() print(f"Username: {admin.username}") print(f"Is Sudo: {admin.is_sudo}") print(f"Telegram ID: {admin.telegram_id}") # Output: Admin(username='admin', is_sudo=True, telegram_id=None, discord_webhook=None, users_usage=0) ``` -------------------------------- ### Manage User Subscriptions and Usage Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Perform subscription operations such as revoking and regenerating a user's subscription URL. Also includes methods to retrieve detailed usage breakdowns by node or for all users within a specified date range. ```python async def subscription_operations(): # Revoke and regenerate subscription URL user = await marzban.revoke_user_subscription("user123") print(f"New subscription URL: {user.subscription_url}") # Get user usage breakdown by node usage = await marzban.get_user_usage( username="user123", start="2024-01-01", end="2024-12-31" ) for node_usage in usage.usages: print(f"Node {node_usage.node_name}: {node_usage.used_traffic} bytes") # Get all users' usage all_usage = await marzban.get_users_usage(start="2024-01-01", end="2024-12-31") for user_usage in all_usage.usages: print(f"{user_usage.username}: {sum(u.used_traffic for u in user_usage.usages)} bytes") ``` -------------------------------- ### Manage Admin User Operations Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Perform bulk user status changes and track usage statistics for a specific admin. ```python async def admin_user_operations(): # Disable all active users of an admin await marzban.disable_all_active_users("support_admin") print("All active users disabled") # Activate all disabled users of an admin await marzban.activate_all_disabled_users("support_admin") print("All disabled users activated") # Get admin's users total usage usage = await marzban.get_admin_usage("support_admin") print(f"Total usage: {usage} bytes") # Reset admin's usage counter admin = await marzban.reset_admin_usage("support_admin") print(f"Usage reset for {admin.username}") ``` -------------------------------- ### Extend User Subscription Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Extend a user's subscription by adding a specified number of days. This method correctly handles expired subscriptions by calculating the new expiration date from the current time. ```python async def extend_subscription(): # Add 30 days to existing subscription user = await marzban.user_add_days("user123", days=30) print(f"New expiration: {user.expire}") # If subscription is expired, starts from now expired_user = await marzban.user_add_days("expired_user", days=30) print(f"Renewed until: {expired_user.expire}") ``` -------------------------------- ### User Management - Remove User and Reset Usage Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Delete users from the system and reset their traffic usage statistics. ```APIDOC ## DELETE /api/v1/user/{username} ### Description Removes a specific user from the system. ### Method DELETE ### Endpoint /api/v1/user/{username} ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user to remove. ### Response #### Success Response (204) No content is returned upon successful deletion. ## POST /api/v1/user/{username}/reset_usage ### Description Resets the traffic usage data for a specific user. ### Method POST ### Endpoint /api/v1/user/{username}/reset_usage ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user whose usage data to reset. ### Response #### Success Response (200) - **username** (string) - The username of the user whose usage was reset. - **used_traffic** (integer) - The reset traffic usage, which should be 0. ### Response Example ```json { "username": "user456", "used_traffic": 0 } ``` ## POST /api/v1/users/reset_usage ### Description Resets the traffic usage data for all users. Use with caution. ### Method POST ### Endpoint /api/v1/users/reset_usage ### Response #### Success Response (204) No content is returned upon successful reset of all user usage data. ``` -------------------------------- ### Using Type-Safe Enums Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Utilize imported enums for user status, data reset strategies, and proxy configurations to ensure type safety during API interactions. ```python from aiomarzban import ( UserStatus, # active, on_hold, disabled, limited, expired UserStatusCreate, # active, on_hold UserStatusModify, # active, disabled, on_hold UserDataLimitResetStrategy, # no_reset, day, week, month, year NodeStatus, # connected, connecting, error, disabled ProxyTypes, # vmess, vless, trojan, shadowsocks ProxyHostSecurity, # inbound_default, none, tls ProxyHostALPN, # none, h3, h2, http/1.1, combinations ProxyHostFingerprint, # chrome, firefox, safari, ios, android, etc. ) # Example usage user = await marzban.add_user( username="user1", status=UserStatusCreate.on_hold, data_limit_reset_strategy=UserDataLimitResetStrategy.month, ) await marzban.modify_user( username="user1", status=UserStatusModify.active, ) users = await marzban.get_users(status=UserStatus.expired) ``` -------------------------------- ### List and Remove Admins Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Retrieve a paginated list of admins or delete an admin account. ```python async def manage_admins(): # List admins with pagination admins = await marzban.get_admins(offset=0, limit=50, username="support") for admin in admins: print(f"Admin: {admin.username}, Sudo: {admin.is_sudo}") # Remove an admin await marzban.remove_admin("support_admin") print("Admin removed successfully") ``` -------------------------------- ### Modify Existing Admin Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Update an admin's credentials, sudo status, or notification settings. ```python async def update_admin(): modified_admin = await marzban.modify_admin( username="support_admin", is_sudo=True, # Promote to sudo password="new_secure_password", # Optional password change telegram_id=987654321, ) print(f"Admin {modified_admin.username} is now sudo: {modified_admin.is_sudo}") ``` -------------------------------- ### POST /api/admin/usage/reset/{username} Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Reset the data usage counter for all users managed by a specific admin. ```APIDOC ## POST /api/admin/usage/reset/{username} ### Description Reset the data usage counter for all users managed by a specific admin. ### Method POST ### Endpoint /api/admin/usage/reset/{username} ### Parameters #### Path Parameters - **username** (str) - Required - The username of the admin whose usage should be reset. ### Request Example ```python admin = await marzban.reset_admin_usage("support_admin") print(f"Usage reset for {admin.username}") ``` ### Response #### Success Response (200) - **username** (str) - The username of the admin whose usage was reset. - **is_sudo** (bool) - The sudo status of the admin. - **telegram_id** (int | None) - The Telegram ID for notifications. - **discord_webhook** (str | None) - The Discord webhook URL for notifications. #### Response Example ```json { "username": "support_admin", "is_sudo": false, "telegram_id": 123456789, "discord_webhook": "https://discord.com/api/webhooks/..." } ``` ``` -------------------------------- ### Handle Expired Users Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Retrieve a list of usernames for users whose subscriptions have expired within a specified date range. Also provides functionality to delete all expired users within a given period. ```python async def handle_expired_users(): # Get list of expired usernames expired = await marzban.get_expired_users( expired_after="2024-01-01", expired_before="2024-06-30" ) print(f"Expired users: {expired}") # Returns list of usernames # Delete all expired users in date range deleted = await marzban.delete_expired_users( expired_after="2024-01-01", expired_before="2024-03-01" ) print(f"Deleted users: {deleted}") ``` -------------------------------- ### User Management - Subscription Operations Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Manage user subscriptions, including revoking and regenerating subscription URLs, and tracking usage. ```APIDOC ## POST /api/v1/user/{username}/revoke ### Description Revokes the current subscription URL for a user and generates a new one. ### Method POST ### Endpoint /api/v1/user/{username}/revoke ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user whose subscription to revoke. ### Response #### Success Response (200) - **username** (string) - The username of the user. - **subscription_url** (string) - The newly generated subscription URL. ### Response Example ```json { "username": "user123", "subscription_url": "https://your.marzban.server/api/v1/subscription/new_uuid" } ``` ## GET /api/v1/user/{username}/usage ### Description Retrieves the traffic usage breakdown for a specific user by node within a date range. ### Method GET ### Endpoint /api/v1/user/{username}/usage ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user. #### Query Parameters - **start** (string) - Required - Start date for the usage data (YYYY-MM-DD). - **end** (string) - Required - End date for the usage data (YYYY-MM-DD). ### Response #### Success Response (200) - **usages** (array of objects) - List of usage data per node. - **node_name** (string) - The name of the node. - **used_traffic** (integer) - The traffic used on this node in bytes. ### Response Example ```json { "usages": [ { "node_name": "Node-A", "used_traffic": 5368709120 }, { "node_name": "Node-B", "used_traffic": 2684354560 } ] } ``` ## GET /api/v1/users/usage ### Description Retrieves the traffic usage for all users within a specified date range. ### Method GET ### Endpoint /api/v1/users/usage ### Parameters #### Query Parameters - **start** (string) - Required - Start date for the usage data (YYYY-MM-DD). - **end** (string) - Required - End date for the usage data (YYYY-MM-DD). ### Response #### Success Response (200) - **usages** (array of objects) - List of usage data per user. - **username** (string) - The username. - **usages** (array of objects) - Detailed usage per node for this user. - **node_name** (string) - The name of the node. - **used_traffic** (integer) - The traffic used on this node in bytes. ### Response Example ```json { "usages": [ { "username": "user123", "usages": [ {"node_name": "Node-A", "used_traffic": 5368709120}, {"node_name": "Node-B", "used_traffic": 2684354560} ] }, { "username": "user456", "usages": [ {"node_name": "Node-A", "used_traffic": 1073741824} ] } ] } ``` ``` -------------------------------- ### PUT /api/admin/mod/{username} Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Update an existing admin's password, permissions, or notification settings. ```APIDOC ## PUT /api/admin/mod/{username} ### Description Update an existing admin's password, permissions, or notification settings. ### Method PUT ### Endpoint /api/admin/mod/{username} ### Parameters #### Path Parameters - **username** (str) - Required - The username of the admin to modify. #### Request Body - **is_sudo** (bool) - Optional - Whether to promote or demote the admin. - **password** (str) - Optional - The new password for the admin. - **telegram_id** (int) - Optional - The new Telegram ID for notifications. - **discord_webhook** (str) - Optional - The new Discord webhook URL for notifications. ### Request Example ```python modified_admin = await marzban.modify_admin( username="support_admin", is_sudo=True, # Promote to sudo password="new_secure_password", # Optional password change telegram_id=987654321, ) ``` ### Response #### Success Response (200) - **username** (str) - The username of the modified admin. - **is_sudo** (bool) - The updated sudo status. - **telegram_id** (int | None) - The updated Telegram ID. - **discord_webhook** (str | None) - The updated Discord webhook URL. #### Response Example ```json { "username": "support_admin", "is_sudo": true, "telegram_id": 987654321, "discord_webhook": null } ``` ``` -------------------------------- ### Handle API Errors Gracefully Source: https://context7.com/p1nk-l0rd/aiomarzban/llms.txt Implement robust error handling for API operations using custom exceptions. This ensures graceful failure and allows for fallback mechanisms like adding a user if not found. ```python from aiomarzban import MarzbanAPI from aiomarzban.exceptions import MarzbanException, MarzbanNotFoundException async def safe_operations(): marzban = MarzbanAPI( address="https://panel.example.com/", username="admin", password="password", timeout=10, retries=3, # Automatic retry on connection errors ) try: user = await marzban.get_user("nonexistent_user") except MarzbanNotFoundException: print("User not found") user = await marzban.add_user(username="nonexistent_user", days=30) except MarzbanException as e: print(f"API error: {e}") except Exception as e: print(f"Connection error: {e}") ```