### Async API Usage Example Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/configuration.md Demonstrates how to instantiate the Marzban client, get an authentication token, and fetch user data within an async context. Requires Python 3.7+. ```python import asyncio async def main(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() users = await panel.get_all_users(token) # Run the async function asyncio.run(main()) ``` -------------------------------- ### Typical User Structure Example Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/user.md Provides a comprehensive example of creating a User object with multiple proxy protocols, inbound configurations, data limits, and status. ```python user = User( username="customer1", proxies={ "vmess": {"id": "35e7e39c-7d5c-1f4b-8b71-508e4f37ff53"}, "vless": {"id": "35e7e39c-7d5c-1f4b-8b71-508e4f37ff53"} }, inbounds={ "vmess": ["VMess TCP"], "vless": ["VLESS TCP REALITY"] }, data_limit=1099511627776, # 1 TB data_limit_reset_strategy="month", expire=1735689600, status="active" ) ``` -------------------------------- ### Inbound Configuration Example Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/configuration.md Specify the inbound protocols and configurations to be used for user connections. ```python inbounds = { "vmess": ["VMess TCP", "VMess WebSocket"], "vless": ["VLESS TCP REALITY", "VLESS gRPC"] } ``` -------------------------------- ### Get Subscription Info and Monitor Usage Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/subscription.md This snippet demonstrates a typical workflow for monitoring user subscriptions. It retrieves user details, fetches subscription information, checks expiration dates, and analyzes data usage. Ensure you have the Marzpy library installed and replace placeholder credentials and URLs. ```python from marzpy import Marzban import asyncio from datetime import datetime async def monitor_user_subscription(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() username = "john_doe" user = await panel.get_user(username, token) # Get subscription information sub_info = await panel.get_subscription_info(user.subscription_url) if not sub_info: print(f"Failed to retrieve subscription info for {username}") return # Check if expiring soon expire_ts = sub_info['expire'] if expire_ts > 0: expire_date = datetime.fromtimestamp(expire_ts) days_remaining = (expire_date - datetime.now()).days print(f"User: {username}") print(f"Expires in: {days_remaining} days") if days_remaining < 7: print("⚠️ Subscription expires soon!") # Check data usage used_gb = sub_info['used_traffic'] / 1024 / 1024 / 1024 limit_gb = sub_info['data_limit'] / 1024 / 1024 / 1024 percent_used = (sub_info['used_traffic'] / sub_info['data_limit'] * 100) if sub_info['data_limit'] > 0 else 0 print(f"\nData Usage: {used_gb:.2f}GB / {limit_gb:.2f}GB ({percent_used:.1f}%)") if percent_used > 80: print("⚠️ User has used >80% of data limit") # Show available protocols print(f"\nAvailable Protocols:") for protocol in sub_info['inbounds'].keys(): print(f" - {protocol}") asyncio.run(monitor_user_subscription()) ``` -------------------------------- ### Get Host Configuration Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Retrieves the current host configuration settings. ```Python host_config = client.system.get_hosts() print(host_config) ``` -------------------------------- ### Proxy Configuration Example Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/configuration.md Define proxy configurations for user accounts, specifying protocols like vmess or vless. ```python proxies = { "vmess": { "id": "8849e5ab-e97a-45b0-b827-b4d63c5146f5" }, "vless": { "id": "8849e5ab-e97a-45b0-b827-b4d63c5146f5" } } ``` -------------------------------- ### Install Marzpy Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/configuration.md Install or upgrade the marzpy package using pip. Ensure you are using a compatible Python version. ```bash pip install marzpy --upgrade ``` -------------------------------- ### Get Subscription Configuration Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Retrieves the configuration details for a specific subscription. ```Python sub_config = client.subscription.get_subscription(username="testuser") print(sub_config) ``` -------------------------------- ### Full Subscription Workflow Example Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/subscription.md Demonstrates a complete workflow for listing users and checking their subscription status and expiration dates. Requires Marzban client initialization and authentication. ```python async def full_subscription_workflow(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() # Step 1: List all users users = await panel.get_all_users(token) # Step 2: Check each user's subscription for user in users: sub_info = await panel.get_subscription_info(user.subscription_url) if sub_info: print(f"{user.username}: {sub_info['status']} - {sub_info['expire_date']}") asyncio.run(full_subscription_workflow()) ``` -------------------------------- ### Get Xray Core Configuration Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Fetches the current configuration settings of the Xray core. ```Python core_config = client.core.get_xray_config() print(core_config) ``` -------------------------------- ### Initialize and Use Marzban Client Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/README.md Demonstrates initializing the Marzban client, authenticating to get a token, and then fetching and printing user information. Ensure you have the correct admin credentials and panel URL. ```python from marzpy import Marzban import asyncio async def main(): # Initialize client panel = Marzban("admin", "password", "https://panel.example.com") # Authenticate token = await panel.get_token() # Use API users = await panel.get_all_users(token) for user in users: print(f"{user.username}: {user.status}") asyncio.run(main()) ``` -------------------------------- ### Initialize Marzban Client and Get Token Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/INDEX.md Instantiate the Marzban client with panel credentials and retrieve an authentication token. This is the first step for most API interactions. ```python panel = Marzban("username", "password", "https://panel.example.com") token = await panel.get_token() ``` -------------------------------- ### Basic Usage: Initialize Marzban and Get Token Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Demonstrates how to initialize the Marzban client with credentials and retrieve an authentication token. This is a fundamental step before making other API calls. ```python from marzpy import Marzban import asyncio async def main(): panel = Marzban("username","password","https://example.com") token = await panel.get_token() #await panel.anyfunction(token) asyncio.run(main()) ``` -------------------------------- ### Get All User Templates Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieves a list of all user templates. Requires an authentication token. ```APIDOC ## Get All User Templates ### Description Retrieves a list of all user templates. ### Method `GET` (assumed) ### Endpoint `/templates` (assumed) ### Parameters #### Query Parameters - **token** (string) - Required - Authentication token. ### Request Example ```python result = await panel.get_all_templates(token=mytoken) #return template list object for template in result: print(template.name) ``` ### Response #### Success Response (200) - **templates** (list) - A list of template objects, each containing template details. ``` -------------------------------- ### Get System Hosts Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/system.md Retrieves the current host configuration for the system. Requires an authorization token. ```python async def get_hosts(self, token: dict) -> dict: # ... implementation details ... pass ``` ```python token = await panel.get_token() hosts = await panel.get_hosts(token) for inbound_name, host_list in hosts.items(): print(f"\nInbound: {inbound_name}") for host in host_list: print(f" - {host['remark']} ({host['address']}:{host['port']})") print(f" Security: {host['security']}") ``` -------------------------------- ### Get Hosts Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieve a list of configured hosts from the Marzban panel. Requires an API token. ```python result = await panel.get_hosts(token=mytoken) print(result) #output: list of hosts ``` -------------------------------- ### Get Template by ID Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Retrieves a specific client template using its unique identifier. ```Python template_info = client.template.get_template_by_id(template_id="some_template_id") print(template_info) ``` -------------------------------- ### Manage Marzban System Resources and Configuration Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/system.md This asynchronous function demonstrates a typical workflow for managing a Marzban system. It retrieves authentication tokens, checks system resource usage (CPU, memory), lists configured inbounds, fetches host configurations, and creates a backup of the hosts configuration. Ensure you have the 'marzpy' library installed and replace placeholder credentials and URLs with your actual Marzban panel details. ```python from marzpy import Marzban import json import asyncio async def manage_system(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() # Check system resources stats = await panel.get_system_stats(token) cpu = stats['cpu'] mem_percent = stats['memory']['percent'] print(f"System Status:") print(f" CPU: {cpu}%") print(f" Memory: {mem_percent}%") if cpu > 80 or mem_percent > 80: print("WARNING: High resource usage detected!") # Check configured inbounds inbounds = await panel.get_inbounds(token) print(f"\nConfigured Inbounds:") for name in inbounds.keys(): print(f" - {name}") # Get hosts configuration hosts = await panel.get_hosts(token) print(f"\nHost Configuration:") for inbound_name, host_list in hosts.items(): print(f" {inbound_name}: {len(host_list)} host(s)") # Backup hosts configuration with open("hosts_backup.json", "w") as f: json.dump(hosts, f, indent=2) print("\nHosts backup saved to hosts_backup.json") asyncio.run(manage_system()) ``` -------------------------------- ### Get XRay Configuration Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/core.md Retrieve the current XRay core configuration. Requires an authorization token. ```python async def get_xray_config(self, token: dict) -> dict ``` ```python { "log": {...}, "api": {...}, "dns": {...}, "routing": {...}, "inbounds": [...], "outbounds": [...], "transport": {...}, "stats": {...}, "policy": {...} } ``` ```python import json token = await panel.get_token() config = await panel.get_xray_config(token) # Pretty print the configuration print(json.dumps(config, indent=2)) # Access specific parts if "inbounds" in config: print(f"Number of inbounds: {len(config['inbounds'])}") ``` -------------------------------- ### Get System Inbounds Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/system.md Retrieves information about all configured inbounds on the system. Requires an authorization token. ```python async def get_inbounds(self, token: dict) -> dict: # ... implementation details ... pass ``` ```python token = await panel.get_token() inbounds = await panel.get_inbounds(token) for inbound_name, inbound_config in inbounds.items(): print(f"Inbound: {inbound_name}") print(f" Port: {inbound_config.get('port')}") print(f" Protocol: {inbound_config.get('protocol')}") ``` -------------------------------- ### Get All Templates Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/template.md Retrieves a list of all user templates from the Marzpy panel. Requires an authorization token. ```python async def get_all_templates(self, token: dict) -> list: # Implementation details omitted for brevity pass ``` ```python from marzpy import Marzban import asyncio async def list_templates(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() templates = await panel.get_all_templates(token) for template in templates: print(f"Template: {template.name} (ID: {template.id})") print(f" Inbounds: {template.inbounds}") print(f" Data Limit: {template.data_limit}") print() asyncio.run(list_templates()) ``` -------------------------------- ### Get Host Configurations Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/INDEX.md Retrieve the list of configured host settings within the Marzban panel. Requires an authentication token. ```python hosts = await panel.get_hosts(token) ``` -------------------------------- ### Get All User Templates Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieves a list of all user templates. Iterate through the result to access template names. ```python result = await panel.get_all_templates(token=mytoken) #return template list object for template in result: print(template.name) ``` -------------------------------- ### Get Xray Core Configuration Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieve the current configuration of the Xray core. Requires an API token. ```python result = await panel.get_xray_config(token=mytoken) print(result) #output: your xray core config ``` -------------------------------- ### Get User Subscription Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Fetch subscription details using a subscription URL. This is useful for retrieving client configurations. ```python subscription_url = "https://sub.yourdomain.com/sub/eyJhbGciOiJIUzI8NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJNbWRDcmFaeSIsImFjY2VzcyI8InN1YnNjcmlwdGlvbiIsImlhdCI1MTY5NDk1NTkxMH0.o75ML5835SPXpVPKXcvEIUxMTwSy-4XGS9NIdWOAmXY" result = await panel.get_subscription(subscription_url) print(result) #output: Configs ``` -------------------------------- ### Get User Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieve a User object by username. This allows access to user-specific details like their subscription URL. ```python result = await panel.get_user("Mewhrzad",token=mytoken) #return User object print(result.subscription_url) ``` -------------------------------- ### Get System Statistics Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/system.md Retrieve current system statistics such as CPU and memory usage. Requires an authorization token. ```python async def get_system_stats(self, token: dict) -> dict ``` ```python { "cpu": 45.2, "memory": { "total": 8589934592, "used": 4294967296, "free": 4294967296, "percent": 50.0 }, "disk": { "total": 107374182400, "used": 53687091200, "free": 53687091200, "percent": 50.0 }, "uptime": 3456789 } ``` ```python from marzpy import Marzban import asyncio async def monitor_system(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() stats = await panel.get_system_stats(token) print(f"CPU Usage: {stats['cpu']}% ভিট") print(f"Memory: {stats['memory']['used'] / 1024 / 1024 / 1024:.2f}GB / {stats['memory']['total'] / 1024 / 1024 / 1024:.2f}GB ({stats['memory']['percent']}%) ভিট") print(f"Disk: {stats['disk']['used'] / 1024 / 1024 / 1024:.2f}GB / {stats['disk']['total'] / 1024 / 1024 / 1024:.2f}GB ({stats['disk']['percent']}%) ভিট") print(f"Uptime: {stats['uptime'] / 86400:.1f} days") asyncio.run(monitor_system()) ``` -------------------------------- ### Create User from Template Configuration Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/template.md Demonstrates how to create a new user by applying the configuration settings from an existing template. This involves fetching a template and then instantiating a User object with its properties. ```python from marzpy.api.user import User from marzpy.api.template import Template import asyncio async def create_user_from_template(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() # Get template template = await panel.get_template_by_id(1, token) # Create user using template configuration new_user = User( username=f"{template.username_prefix}john{template.username_suffix}", proxies={ "vmess": {"id": "8849e5ab-e97a-45b0-b827-b4d63c5146f5"}, "vless": {"id": "8849e5ab-e97a-45b0-b827-b4d63c5146f5"} }, inbounds=template.inbounds, data_limit=template.data_limit, expire_duration=template.expire_duration ) created = await panel.add_user(new_user, token) print(f"User {created.username} created from template {template.name}") asyncio.run(create_user_from_template()) ``` -------------------------------- ### Python - Host Data Structure Example Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/system.md This is the expected data structure for host configurations when using methods like `get_hosts` or `modify_hosts`. It includes details for different protocols like VMess TCP and VLESS TCP REALITY. ```python { "VMess TCP": [ { "remark": "Server 1", "address": "newaddress.example.com", "port": 8080, "sni": "example.com", "host": "example.com", "security": "tls", "alpn": "h2,http/1.1", "fingerprint": "chrome" } ], "VLESS TCP REALITY": [ { "remark": "Server 2", "address": "server2.example.com", "port": 8443, "sni": "example.com", "host": "example.com", "security": "reality", "alpn": "http/1.1", "fingerprint": "randomized" } ] } ``` -------------------------------- ### get_all_users_count Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/user.md Get the total count of users on the panel. ```APIDOC ## Method: get_all_users_count ### Description Get the total count of users on the panel. ### Method Signature `async def get_all_users_count(self, token: dict) -> int` ### Parameters #### Path Parameters - **token** (dict) - Required - Authorization token from `get_token()` ### Returns #### Success Response - **int** - Total count of users ### Usage Example ```python token = await panel.get_token() total_users = await panel.get_all_users_count(token) print(f"Total users on panel: {total_users}") ``` ``` -------------------------------- ### Get Subscription Configuration Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/subscription.md Retrieves the user's subscription configuration in a base64-decoded string format. This is useful for obtaining proxy server details and connection settings. ```python async def get_subscription(self, sub_link: str) -> str ``` ```python from marzpy import Marzban import asyncio async def get_sub_config(): panel = Marzban("admin", "password", "https://panel.example.com") # Get user's subscription URL token = await panel.get_token() user = await panel.get_user("john_doe", token) # Retrieve subscription configuration sub_config = await panel.get_subscription(user.subscription_url) print(sub_config) asyncio.run(get_sub_config()) ``` -------------------------------- ### Get All Nodes Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieves a list of all nodes. Requires an authentication token. ```APIDOC ## Get All Nodes ### Description Retrieves a list of all nodes. ### Method `GET` (assumed) ### Endpoint `/nodes` (assumed) ### Parameters #### Query Parameters - **token** (string) - Required - Authentication token. ### Request Example ```python result = await panel.get_all_nodes(token=mytoken) # return List of Node object for node in result: print(node.address) ``` ### Response #### Success Response (200) - **nodes** (list) - A list of node objects, each containing node details. ``` -------------------------------- ### List All Templates Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Retrieves a list of all available client configuration templates. ```Python all_templates = client.template.get_all_templates() print(all_templates) ``` -------------------------------- ### Get All Users Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieves a list of all users. Requires an authentication token. ```APIDOC ## Get All Users ### Description Retrieves a list of all users. ### Method `GET` (assumed) ### Endpoint `/users` (assumed) ### Parameters #### Query Parameters - **token** (string) - Required - Authentication token. ### Request Example ```python result = await panel.get_all_users(token=mytoken) #return list of users for user in result: print(user.username) ``` ### Response #### Success Response (200) - **users** (list) - A list of user objects, each containing user details like username. ``` -------------------------------- ### Create User with Configuration Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/configuration.md Instantiate the User class with various configuration options for creating or modifying users. ```python from marzpy.api.user import User user = User( username="customer1", proxies={...}, inbounds={...}, data_limit=1099511627776, data_limit_reset_strategy="month", expire=1735689600, status="active" ) ``` -------------------------------- ### Get Node Usage Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieves the usage statistics for all nodes. Requires an authentication token. ```APIDOC ## Get Node Usage ### Description Retrieves the usage statistics for all nodes. ### Method `GET` (assumed) ### Endpoint `/nodes/usage` (assumed) ### Parameters #### Query Parameters - **token** (string) - Required - Authentication token. ### Request Example ```python result = await panel.get_nodes_usage(token=mytoken) for node in result: print(node) #output:{'node_id': 1, 'node_name': 'N1', 'uplink': 1000000000000, 'downlink': 1000000000000} # {'node_id': 2, 'node_name': 'N2', 'uplink': 1000000000000, 'downlink': 1000000000000} ``` ### Response #### Success Response (200) - **usage_data** (list) - A list of objects, each detailing usage for a node. ``` -------------------------------- ### User Constructor Parameters Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/user.md Lists the parameters available for initializing a User object, including data limits, expiration, and traffic usage. ```python def __init__( self, username: str, proxies: dict, inbounds: dict, data_limit: float, data_limit_reset_strategy: str = "no_reset", status: str = "", expire: float = 0, used_traffic: float = 0, lifetime_used_traffic: float = 0, created_at: str = "", links: list = [], subscription_url: str = "", excluded_inbounds: dict = {}, note: str = "", on_hold_timeout: int = 0, on_hold_expire_duration: int = 0, sub_updated_at: int = 0, online_at: int = 0, sub_last_user_agent: str = "", auto_delete_in_days: int = 0, **_ ) ``` -------------------------------- ### Get All Admins Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieve a list of all admin users on the panel. Requires an API token. ```python result = await panel.get_all_admins(token=mytoken) print(result) #output: [{'username': 'test', 'is_sudo': True}, {'username': 'test1', 'is_sudo': False}] ``` -------------------------------- ### Create a Template Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/configuration.md Initialize a Template object with parameters for defining user plans. Configure inbound protocols, data limits, and username formatting. ```python from marzpy.api.template import Template template = Template( name="Basic Plan", inbounds={ "vmess": ["VMess TCP"], "vless": ["VLESS TCP REALITY"] }, data_limit=1099511627776, expire_duration=2592000, username_prefix="basic_", username_suffix="_user" ) ``` -------------------------------- ### Marzban Client Initialization Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/marzban.md Initialize the Marzban client with your panel credentials and address. ```APIDOC ## Constructor ```python def __init__(self, username: str, password: str, panel_address: str) -> None ``` ### Description Initializes the Marzban client. ### Parameters #### Path Parameters - **username** (str) - Required - Admin username for authentication - **password** (str) - Required - Admin password for authentication - **panel_address** (str) - Required - Base URL of the Marzban panel (e.g., https://example.com) ``` -------------------------------- ### Initialize Marzban Client Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/marzban.md Initializes the Marzban client with admin credentials and panel address. This is the first step before making any API calls. ```python from marzpy import Marzban import asyncio async def main(): # Initialize the client panel = Marzban("admin_username", "admin_password", "https://panel.example.com") # Get authentication token token = await panel.get_token() if token and "access_token" in token: print("Authentication successful") else: print("Authentication failed") asyncio.run(main()) ``` -------------------------------- ### Get Node by ID Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Retrieves information about a specific node using its unique identifier. ```Python node_info = client.node.get_node_by_id(node_id="some_node_id") print(node_info) ``` -------------------------------- ### Create a Node Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/configuration.md Instantiate a Node object with essential configuration parameters. Ensure the certificate is provided in the correct format. ```python from marzpy.api.node import Node node = Node( name="Server 1", address="node1.example.com", port=62050, api_port=62051, certificate="-----BEGIN CERTIFICATE-----...", xray_version="1.8.1" ) ``` -------------------------------- ### Get User Information Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Retrieves detailed information for a specific user, identified by their username. ```Python user_info = client.user.get_user(username="testuser") print(user_info) ``` -------------------------------- ### Instantiate and Access Node Attributes Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/node.md Demonstrates how to create a Node object with specific parameters and access its attributes like name, address, and status. ```python node = Node( name="Server 1", address="node1.example.com", port=62050, api_port=62051, id=1, xray_version="1.8.1", status="connected" ) print(node.name) # "Server 1" print(node.address) # "node1.example.com" print(node.status) # "connected" ``` -------------------------------- ### Get Authentication Token Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/marzban.md Obtain an authentication token by providing valid admin credentials. ```APIDOC ## Get Token ### Description Retrieves an authentication token for API access. ### Method `get_token()` ### Request Example ```python # Assuming 'panel' is an initialized Marzban client instance token = await panel.get_token() ``` ### Response #### Success Response (200) - **access_token** (str) - The authentication token ``` -------------------------------- ### Get Authentication Token Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/INDEX.md Retrieves an authentication token. This is the first step for authenticated API interactions. ```python get_token() ``` -------------------------------- ### Marzban Client Initialization Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/configuration.md Initialize the Marzban client with administrator credentials and the panel address. This snippet demonstrates basic initialization and token retrieval for authentication verification. ```python from marzpy import Marzban import asyncio async def initialize_client(): # Basic initialization panel = Marzban( username="admin", password="secure_password123", panel_address="https://panel.example.com" ) # Get token to verify credentials token = await panel.get_token() if token and "access_token" in token: print("Authentication successful") else: print("Authentication failed") asyncio.run(initialize_client()) ``` -------------------------------- ### Add New Template Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Creates a new client configuration template. Templates define default settings for user subscriptions. ```Python new_template = client.template.add_template(name="basic_template", protocol="vless", settings={...}) print(new_template) ``` -------------------------------- ### Manage XRay Core Workflow Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/core.md This snippet demonstrates a complete workflow for managing the XRay core. It shows how to authenticate, check the core's status, retrieve and modify its configuration, update the configuration, and restart the core to apply changes. Ensure you have the Marzban panel URL and valid admin credentials. ```python from marzpy import Marzban import json import asyncio async def manage_xray_core(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() # Check core status core_info = await panel.get_xray_core(token) print(f"XRay {core_info['version']} is {'running' if core_info['started'] else 'stopped'}") # Get current configuration config = await panel.get_xray_config(token) print(f"Current log level: {config['log'].get('loglevel', 'info')}") # Modify configuration config["log"]["loglevel"] = "info" # Update configuration result = await panel.modify_xray_config(token, config) print(f"Config updated: {result}") # Restart core to apply changes restart_result = await panel.restart_xray_core(token) print(f"Core restarted: {restart_result}") # Verify new status updated_info = await panel.get_xray_core(token) print(f"New status: {'Running' if updated_info['started'] else 'Stopped'}") asyncio.run(manage_xray_core()) ``` -------------------------------- ### Create Admin Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Create a new admin user by providing their username, password, and sudo status. Requires an API token. ```python info = {'username':'test','password':'pasword','is_sudo':False} rsault = await panel.create_admin(token=mytoken,data=info) print(result) #output: success ``` -------------------------------- ### Typical Marzban User Management Workflow Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/marzban.md Demonstrates a common workflow for managing users via the Marzban client, including authentication, creation, retrieval, modification, usage check, and deletion. ```python from marzpy import Marzban from marzpy.api.user import User import asyncio async def manage_users(): panel = Marzban("admin", "password", "https://panel.example.com") # Step 1: Authenticate token = await panel.get_token() # Step 2: Create a new user new_user = User( username="john_doe", proxies={"vmess": {"id": "uuid-here"}}, inbounds={"vmess": ["VMess TCP"]}, data_limit=1099511627776, # 1TB expire=1735689600, data_limit_reset_strategy="no_reset", status="active" ) created_user = await panel.add_user(new_user, token) # Step 3: Get user information user_info = await panel.get_user("john_doe", token) # Step 4: Modify user new_user.data_limit = 2199023255552 # 2TB modified_user = await panel.modify_user("john_doe", token, new_user) # Step 5: Check user usage usage = await panel.get_user_usage("john_doe", token) # Step 6: Delete user result = await panel.delete_user("john_doe", token) asyncio.run(manage_users()) ``` -------------------------------- ### Get Inbounds Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieve a list of all configured inbounds on the Marzban panel. Requires an API token. ```python result = await panel.get_inbounds(token=mytoken) print(result) #output: list of inbounds ``` -------------------------------- ### Add User Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/user.md Creates a new user on the panel with specified configurations. ```APIDOC ## Method: add_user ### Description Create a new user on the panel. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **user** (User) - Required - User object with configuration - **token** (dict) - Required - Authorization token from `get_token()` ### Response #### Success Response (200) - **User** (User) - The created User object with all panel-assigned properties ### Behavior - If `on_hold_expire_duration` is set, status is automatically changed to "on_hold" - Otherwise, status is set to "active" ``` -------------------------------- ### Access User Attributes Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/user.md Demonstrates how to create a User instance and access its attributes like username and data limit. ```python user = User( username="john", proxies={"vmess": {"id": "uuid"}}, inbounds={"vmess": ["VMess TCP"]}, data_limit=1099511627776, expire=1735689600 ) print(user.username) # "john" print(user.data_limit) # 1099511627776 print(user.subscription_url) # "" ``` -------------------------------- ### Get Xray Core Status Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Retrieves the current operational status of the Xray core service. ```Python core_status = client.core.get_xray_core() print(core_status) ``` -------------------------------- ### Get Node by ID Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieves a specific node by its ID. Requires the node ID and an authentication token. ```APIDOC ## Get Node ### Description Retrieves a specific node by its ID. ### Method `GET` (assumed) ### Endpoint `/nodes/{id}` (assumed) ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the node. #### Query Parameters - **token** (string) - Required - Authentication token. ### Request Example ```python result = await panel.get_node_by_id(id=1, token=mytoken) # return exist Node object print(result.address) #output: address of node 1 ``` ### Response #### Success Response (200) - **node** (object) - The requested node object. ``` -------------------------------- ### System Management Methods Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/INDEX.md Offers methods for monitoring system health, retrieving inbound connections, and managing host configurations. ```python get_system_stats() get_inbounds() get_hosts() modify_hosts() ``` -------------------------------- ### Get User Usage Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieves the data usage for a specific user. Requires a username and an authentication token. ```APIDOC ## Get User Usage ### Description Retrieves the data usage for a specific user. ### Method `GET` (assumed) ### Endpoint `/users/{username}/usage` (assumed) ### Parameters #### Path Parameters - **username** (string) - Required - The username of the user. #### Query Parameters - **token** (string) - Required - Authentication token. ### Request Example ```python result = await panel.get_user_usage("mewhrzad",token=mytoken) print(result) #output: [{'node_id': None, 'node_name': 'MTN', 'used_traffic': 0}, #{'node_id': 1, 'node_name': 'MCI', 'used_traffic': 0}] ``` ### Response #### Success Response (200) - **usage_data** (list) - A list of objects, each detailing usage per node. ``` -------------------------------- ### Create Admin Account Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/admin.md Use this method to create a new admin account on the panel. Requires an authorization token and admin information. ```python async def create_admin(self, token: dict, data: dict) -> str: # ... implementation details ... pass ``` ```python { "username": "new_admin", "password": "secure_password", "is_sudo": False } ``` ```python token = await panel.get_token() admin_data = { "username": "new_operator", "password": "secure_password123", "is_sudo": False } result = await panel.create_admin(token, admin_data) print(result) # Output: "success" ``` -------------------------------- ### System Management Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/README.md Methods for retrieving system-level information and configurations. ```APIDOC ## get_system_stats(token) ### Description Retrieves statistics about the system's resource utilization. ### Method `get_system_stats(token: str)` ### Parameters #### Path Parameters - **token** (str) - Required - The session token for authentication. ### Returns `dict` - System statistics. ``` ```APIDOC ## get_inbounds(token) ### Description Retrieves a list of configured inbounds for the panel. ### Method `get_inbounds(token: str)` ### Parameters #### Path Parameters - **token** (str) - Required - The session token for authentication. ### Returns `dict` - A dictionary containing inbound configurations. ``` ```APIDOC ## get_hosts(token) ### Description Retrieves the host configuration from the panel. ### Method `get_hosts(token: str)` ### Parameters #### Path Parameters - **token** (str) - Required - The session token for authentication. ### Returns `dict` - The host configuration. ``` ```APIDOC ## modify_hosts(token, data) ### Description Updates the host configuration in the panel. ### Method `modify_hosts(token: str, data: dict)` ### Parameters #### Path Parameters - **token** (str) - Required - The session token for authentication. - **data** (dict) - Required - A dictionary containing the updated host configuration. ### Returns `dict` - The updated host configuration. ``` -------------------------------- ### Get All Nodes Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/node.md Retrieves a list of all Node objects on the panel. Requires an authorization token obtained from `get_token()`. ```python async def get_all_nodes(self, token: dict) -> list: pass ``` ```python token = await panel.get_token() all_nodes = await panel.get_all_nodes(token) for node in all_nodes: status_icon = "✓" if node.status == "connected" else "✗" print(f"{status_icon} {node.name} ({node.address})") print(f" ID: {node.id}, XRay: {node.xray_version}") ``` -------------------------------- ### Backup and Restore XRay Configuration with Marzpy Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/README.md This snippet demonstrates how to back up the current XRay configuration to a JSON file and how to restore it, followed by a restart of the XRay core. ```python import json async def backup_config(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() # Get and save config config = await panel.get_xray_config(token) with open("xray_backup.json", "w") as f: json.dump(config, f, indent=2) print("Config backed up") async def restore_config(): panel = Marzban("admin", "password", "https://panel.example.com") token = await panel.get_token() # Load and restore config with open("xray_backup.json", "r") as f: config = json.load(f) await panel.modify_xray_config(token, config) await panel.restart_xray_core(token) print("Config restored") asyncio.run(backup_config()) # asyncio.run(restore_config()) ``` -------------------------------- ### Get Current Admin Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Retrieve details of the currently authenticated admin using a valid API token. ```python admin = await panel.get_current_admin(token=mytoken) print(admin) #output: {'username': 'admin', 'is_sudo': True} ``` -------------------------------- ### Template Class Constructor Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/template.md Initializes a new user template with specified configurations. Parameters include name, inbounds, data limit, expiration duration, username prefix/suffix, and an optional ID. ```APIDOC ## Class: Template Data model representing a user template for creating users with predefined configurations. ### Constructor ```python def __init__( self, name: str = "", inbounds: dict = {}, data_limit: dict = {}, expire_duration: int = 0, username_prefix: str = "", username_suffix: str = "", id: int = None ) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | name | str | No | "" | Display name for the template | | inbounds | dict | No | {} | Dictionary of inbound configurations | | data_limit | dict | No | {} | Data limit configuration | | expire_duration | int | No | 0 | Expiration duration in seconds | | username_prefix | str | No | "" | Prefix to add to usernames created from this template | | username_suffix | str | No | "" | Suffix to add to usernames created from this template | | id | int | No | None | Template ID (assigned by panel) | ### Attributes All constructor parameters become instance attributes: ```python template = Template( name="Standard Plan", inbounds={"vmess": ["VMess TCP"], "vless": ["VLESS TCP REALITY"]}, data_limit=1099511627776, expire_duration=2592000, username_prefix="std_", id=1 ) print(template.name) # "Standard Plan" print(template.data_limit) # 1099511627776 print(template.expire_duration) # 2592000 (30 days) ``` ``` -------------------------------- ### System Methods Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/api-reference/marzban.md Methods for retrieving system-level information. ```APIDOC ## System Methods ### Description Offers methods to fetch system-level statistics and configurations, such as system stats and host information. ### Methods - `get_system_stats()`: Retrieves statistics about the system. - `get_inbounds()`: Retrieves information about inbound connections. - `get_hosts()`: Retrieves a list of hosts. - `modify_hosts(hosts_object)`: Modifies the hosts configuration. ``` -------------------------------- ### Get API Token Source: https://github.com/mewhrzad/marzpy/blob/main/README.md Instantiate the Marzban client and retrieve an API token using your username and password. ```python from marzpy import Marzban panel = Marzban("username","password","https://example.com") mytoken = await panel.get_token() ``` -------------------------------- ### Add a New User Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/INDEX.md Create a new user with specified properties and add them to the Marzban panel. Requires an existing authentication token. ```python user = User(username="...", proxies={...}, inbounds={...}, data_limit=...) created = await panel.add_user(user, token) ``` -------------------------------- ### Get Nodes Usage Statistics Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Fetches traffic usage statistics aggregated across all registered nodes. ```Python nodes_usage = client.node.get_nodes_usage() print(nodes_usage) ``` -------------------------------- ### Get Authentication Token Source: https://github.com/mewhrzad/marzpy/blob/main/_autodocs/MANIFEST.txt Retrieves an authentication token for administrative access. This method is part of the admin module. ```Python token = client.admin.get_token() print(token) ```