### Get User Details and Usage with Marzneshin API Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Retrieves detailed user information including username, status, data usage, data limit, and expiration date. It also fetches usage statistics for a specified time period. Requires the MarzneshinAPI library and an active API connection. The function returns the user details object. ```python import asyncio from marzneshin.api import MarzneshinAPI async def check_user_status(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Get user details user = await api.get_user('john_doe') print(f"Username: {user['username']}") print(f"Status: {user['status']}") print(f"Data used: {user['used_traffic']} bytes") print(f"Data limit: {user['data_limit']} bytes") print(f"Expiration: {user['expire_date']}") # Get usage statistics for specific time period usage = await api.get_user_usage( username='john_doe', start='2025-01-01T00:00:00', end='2025-12-31T23:59:59' ) print(f"Total usage: {usage}") return user asyncio.run(check_user_status()) ``` -------------------------------- ### Initialize Marzneshin API Client in Python Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Demonstrates how to create an instance of the MarzneshinAPI client with base URL and admin credentials. The client handles authentication and token management automatically. ```python from marzneshin.api import MarzneshinAPI api = MarzneshinAPI( base_url='https://your-marzneshin-server.com', username='admin', password='your_admin_password' ) # Token is automatically fetched on first request # Token expiration is checked before each request and renewed if needed current_admin = await api.get_current_admin() print(f"Logged in as: {current_admin['username']}") ``` -------------------------------- ### Initialize API Client Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Demonstrates how to initialize the MarzneshinAPI client with base URL and admin credentials. The client handles authentication automatically. ```APIDOC ## Initialize API Client ### Description Create a client instance with base URL and admin credentials. The client handles authentication automatically. ### Method N/A (Initialization) ### Endpoint N/A (Initialization) ### Parameters N/A ### Request Example ```python from marzneshin.api import MarzneshinAPI api = MarzneshinAPI( base_url='https://your-marzneshin-server.com', username='admin', password='your_admin_password' ) # Token is automatically fetched on first request # Token expiration is checked before each request and renewed if needed current_admin = await api.get_current_admin() print(f"Logged in as: {current_admin['username']}") ``` ### Response #### Success Response (200) - **current_admin** (dict) - Information about the currently logged-in admin. #### Response Example ```json { "username": "admin", "id": 1, "is_superuser": true, "is_active": true, "created_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Create User Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Create a new user with expiration strategy, data limits, and service assignments. ```APIDOC ## POST /api/users ### Description Create a new user with expiration strategy, data limits, and service assignments. ### Method POST ### Endpoint `/api/users` ### Parameters #### Request Body - **UserCreate** (object) - Required - User creation data. - **username** (str) - Required - The username for the new user. - **expire_strategy** (str) - Required - The expiration strategy ('fixed_date', 'never'). - **expire_date** (str) - Optional - The expiration date in ISO format (required if `expire_strategy` is 'fixed_date'). - **data_limit** (int) - Optional - The data limit in bytes. - **data_limit_reset_strategy** (str) - Optional - Strategy for resetting data limit ('month', 'day', 'no_reset'). - **note** (str) - Optional - A note for the user. - **service_ids** (list[int]) - Optional - A list of service IDs to assign to the user. ### Request Example ```python import asyncio from datetime import datetime, timedelta from marzneshin.api import MarzneshinAPI from marzneshin.models import UserCreate async def create_vpn_user(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Create user with fixed expiration date expiration_date = datetime.now() + timedelta(days=30) new_user = UserCreate( username='john_doe', expire_strategy='fixed_date', expire_date=expiration_date.isoformat(), data_limit=10737418240, # 10GB in bytes data_limit_reset_strategy='month', # Reset monthly note='Premium user - Monthly subscription', service_ids=[1, 2, 3] # Assign to services 1, 2, 3 ) try: result = await api.add_user(new_user) print(f"User created: {result['username']}") print(f"Subscription key: {result['key']}") print(f"Subscription URL: /sub/{result['username']}/{result['key']}") return result except Exception as e: print(f"Error creating user: {e}") return None asyncio.run(create_vpn_user()) ``` ### Response #### Success Response (200) - **username** (str) - The username of the created user. - **key** (str) - The unique subscription key for the user. - **expire_date** (str) - The expiration date of the user's subscription. - **data_limit** (int) - The data limit for the user in bytes. #### Response Example ```json { "username": "john_doe", "key": "a1b2c3d4e5f6", "expire_date": "2024-11-26T10:00:00Z", "data_limit": 10737418240 } ``` ``` -------------------------------- ### Create a VPN User with Marzneshin API Client in Python Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Illustrates creating a new VPN user using the Marzneshin API client. Supports setting expiration dates, data limits with reset strategies, notes, and assigning services. Requires Python 3.10+ and the marzneshin library. ```python import asyncio from datetime import datetime, timedelta from marzneshin.api import MarzneshinAPI from marzneshin.models import UserCreate async def create_vpn_user(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Create user with fixed expiration date expiration_date = datetime.now() + timedelta(days=30) new_user = UserCreate( username='john_doe', expire_strategy='fixed_date', expire_date=expiration_date.isoformat(), data_limit=10737418240, # 10GB in bytes data_limit_reset_strategy='month', # Reset monthly note='Premium user - Monthly subscription', service_ids=[1, 2, 3] # Assign to services 1, 2, 3 ) try: result = await api.add_user(new_user) print(f"User created: {result['username']}") print(f"Subscription key: {result['key']}") print(f"Subscription URL: /sub/{result['username']}/{result['key']}") return result except Exception as e: print(f"Error creating user: {e}") return None asyncio.run(create_vpn_user()) ``` -------------------------------- ### Manage Services with Marzneshin API Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Demonstrates how to create and configure services, which group inbounds and users. Operations include listing, creating, retrieving details, updating, and deleting services. Uses ServiceCreate and ServiceModify models. Requires MarzneshinAPI and model imports. ```python import asyncio from marzneshin.api import MarzneshinAPI from marzneshin.models import ServiceCreate, ServiceModify async def manage_services(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # List services services = await api.get_services(page=1, size=50) print(f"Total services: {services['total']}") # Create new service new_service = ServiceCreate( name='premium-us-servers', inbounds=[1, 2, 3], # Associate with inbounds users=[] # Users will be added later ) created = await api.add_service(new_service) print(f"Service created with ID: {created['id']}") # Get service details service = await api.get_service(created['id']) print(f"Service name: {service['name']}") print(f"Inbounds: {service['inbounds']}") # Update service service_update = ServiceModify( name='premium-us-servers-updated', inbounds=[1, 2, 3, 4] # Add inbound 4 ) updated = await api.modify_service(created['id'], service_update) print(f"Service updated: {updated['name']}") # Delete service await api.remove_service(created['id']) print("Service removed") asyncio.run(manage_services()) ``` -------------------------------- ### Complete User Lifecycle Management with Marzneshin API Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Demonstrates an end-to-end workflow for managing users via the Marzneshin API. This includes creating, monitoring, modifying, suspending, reactivating, and canceling user subscriptions. It requires API credentials and uses models for user data. ```python import asyncio from datetime import datetime, timedelta from marzneshin.api import MarzneshinAPI from marzneshin.models import UserCreate, UserModify async def complete_user_workflow(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') try: # 1. Create user new_user = UserCreate( username='customer_001', expire_strategy='fixed_date', expire_date=(datetime.now() + timedelta(days=30)).isoformat(), data_limit=10737418240, # 10GB data_limit_reset_strategy='month', note='Standard monthly plan', service_ids=[1, 2] ) user = await api.add_user(new_user) print(f"✓ User created: {user['username']}") print(f" Subscription: /sub/{user['username']}/{user['key']}") # 2. Monitor usage user_info = await api.get_user('customer_001') usage_percent = (user_info['used_traffic'] / user_info['data_limit']) * 100 print(f"✓ Current usage: {usage_percent:.2f}%") # 3. Handle quota exceeded - reset usage if usage_percent > 90: await api.reset_user_data_usage('customer_001') print("✓ Usage reset due to high consumption") # 4. Upgrade user plan upgrade = UserModify( username='customer_001', data_limit=21474836480, # 20GB expire_date=(datetime.now() + timedelta(days=60)).isoformat(), note='Upgraded to premium plan' ) await api.modify_user('customer_001', upgrade) print("✓ User upgraded to premium plan") # 5. Set ownership await api.set_owner('customer_001', 'manager1') print("✓ User assigned to manager1") # 6. Get statistics stats = await api.get_user_usage( 'customer_001', start=datetime.now().replace(day=1).isoformat(), end=datetime.now().isoformat() ) print(f"✓ Monthly usage: {stats}") # 7. Suspend for non-payment await api.disable_user('customer_001') print("✓ User suspended") # 8. Reactivate after payment await api.enable_user('customer_001') print("✓ User reactivated") # 9. User requests config change - revoke subscription result = await api.revoke_user_subscription('customer_001') print(f"✓ New subscription key generated: {result['key']}") # 10. Cancel subscription await api.remove_user('customer_001') print("✓ User subscription cancelled and removed") except Exception as e: print(f"✗ Error: {e}") asyncio.run(complete_user_workflow()) ``` -------------------------------- ### User Subscription Management with Marzneshin API (Python) Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Generate and retrieve user subscription URLs for various VPN clients using the Marzneshin API. This includes fetching subscription configurations, subscription information, client-specific configurations (like Clash or V2Ray), and usage statistics. Dependencies include the 'marzneshin' library. Inputs are username and key, with outputs being subscription URLs and usage data. ```python import asyncio from marzneshin.api import MarzneshinAPI async def get_user_subscription(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Get user to retrieve subscription key user = await api.get_user('john_doe') username = user['username'] key = user['key'] # Get generic subscription config subscription = await api.user_subscription(username, key) print(f"Subscription config: {subscription}") # Get subscription info info = await api.user_subscription_info(username, key) print(f"Total data: {info['total']} bytes") print(f"Used data: {info['used']} bytes") print(f"Remaining: {info['remaining']} bytes") print(f"Expires: {info['expire']}") # Get subscription for specific client type clash_config = await api.user_subscription_with_client_type(username, key, 'clash') print(f"Clash config: {clash_config}") v2ray_config = await api.user_subscription_with_client_type(username, key, 'v2ray') print(f"V2Ray config: {v2ray_config}") # Get usage for subscription usage = await api.user_get_usage( username=username, key=key, start='2025-01-01T00:00:00', end='2025-12-31T23:59:59' ) print(f"Usage statistics: {usage}") asyncio.run(get_user_subscription()) ``` -------------------------------- ### List and Filter Users with Marzneshin API Client in Python Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Shows how to retrieve all users from the Marzneshin API, including support for pagination and filtering by username, status, and sorting options. Requires Python 3.10+ and the marzneshin library. ```python import asyncio from marzneshin.api import MarzneshinAPI async def list_users(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Get all users (paginated) users = await api.get_users(page=1, size=50) print(f"Total users: {users['total']}") # Filter by username filtered = await api.get_users(username='john') # Filter by status and sort active_users = await api.get_users( status=['active', 'limited'], order_by='data_limit', descending=True, page=1, size=100 ) for user in active_users['items']: print(f"Username: {user['username']}, Status: {user['status']}") return users asyncio.run(list_users()) ``` -------------------------------- ### Manage Inbound Hosts with Marzneshin API (Python) Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Configure inbound connection hosts with various security and networking options using the Marzneshin API. This involves listing, creating, updating, and deleting hosts associated with inbound connections. Dependencies include the 'marzneshin' library. Input is typically an inbound ID and host details, with output being confirmation messages or host data. ```python import asyncio from marzneshin.api import MarzneshinAPI from marzneshin.models import InboundHost async def manage_inbound_hosts(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # List all hosts for an inbound hosts = await api.get_inbound_hosts(inbound_id=1, page=1, size=50) print(f"Total hosts: {hosts['total']}") # Create new host new_host = InboundHost( remark='US Server 1', address='us1.example.com', port=443, sni='us1.example.com', host='us1.example.com', path='/api/v1', security='tls', alpn='h2,http/1.1', fingerprint='chrome', allowinsecure=False, is_disabled=False, mux=True, fragment={'packets': '1-3', 'length': '100-200', 'interval': '10-20'} ) created = await api.create_inbound_host(inbound_id=1, host=new_host) print(f"Host created with ID: {created['id']}") # Update host host_update = InboundHost( remark='US Server 1 - Updated', address='us1-new.example.com', port=443, sni='us1-new.example.com' ) updated = await api.update_inbound_host(created['id'], host_update) print(f"Host updated: {updated['remark']}") # Get all hosts across all inbounds all_hosts = await api.get_hosts(page=1, size=100) for host in all_hosts['items']: print(f"Host: {host['remark']} - {host['address']}") # Delete host await api.delete_inbound_host(created['id']) print("Host removed") asyncio.run(manage_inbound_hosts()) ``` -------------------------------- ### Admin User Management with Marzneshin API (Python) Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Create, modify, and manage admin accounts with different permission levels using the Marzneshin API. This includes retrieving current admin details, listing all admins, creating new admins, updating existing ones, and deleting them. Dependencies include the 'marzneshin' library. Inputs are admin credentials and modification details, with outputs being confirmation messages or admin data. ```python import asyncio from marzneshin.api import MarzneshinAPI from marzneshin.models import AdminCreate, AdminModify async def manage_admins(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Get current admin info current = await api.get_current_admin() print(f"Current admin: {current['username']}, Sudo: {current['is_sudo']}") # List all admins admins = await api.get_admins(page=1, size=50) print(f"Total admins: {admins['total']}") # Create new admin new_admin = AdminCreate( username='manager1', password='SecurePassword123!', is_sudo=False # Regular admin, not superuser ) created = await api.create_admin(new_admin) print(f"Admin created: {created['username']}") # Modify admin admin_update = AdminModify( password='NewSecurePassword456!', is_sudo=True # Promote to superuser ) updated = await api.modify_admin('manager1', admin_update) print(f"Admin updated: {updated['username']}, Sudo: {updated['is_sudo']}") # Delete admin await api.remove_admin('manager1') print("Admin removed") asyncio.run(manage_admins()) ``` -------------------------------- ### Retrieve System Statistics using Marzneshin API Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Fetches and displays statistics for administrators, nodes, and users from the Marzneshin API. It requires the API endpoint, username, and password. Outputs include counts of admins, nodes, active users, and traffic information. ```python import asyncio from marzneshin.api import MarzneshinAPI async def get_system_stats(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Get admin statistics admin_stats = await api.get_admins_stats() print(f"Total admins: {admin_stats['total']}") print(f"Sudo admins: {admin_stats['sudo_count']}") # Get node statistics node_stats = await api.get_nodes_stats() print(f"Total nodes: {node_stats['total']}") print(f"Connected nodes: {node_stats['connected']}") print(f"Disconnected nodes: {node_stats['disconnected']}") print(f"Total traffic: {node_stats['total_traffic']} bytes") # Get user statistics user_stats = await api.get_users_stats() print(f"Total users: {user_stats['total']}") print(f"Active users: {user_stats['active']}") print(f"Expired users: {user_stats['expired']}") print(f"Limited users: {user_stats['limited']}") print(f"Disabled users: {user_stats['disabled']}") print(f"Total usage: {user_stats['total_usage']} bytes") # Get node usage for specific period node_usage = await api.get_node_usage( start='2025-01-01T00:00:00', end='2025-12-31T23:59:59' ) print(f"Node usage: {node_usage}") return { 'admins': admin_stats, 'nodes': node_stats, 'users': user_stats } asyncio.run(get_system_stats()) ``` -------------------------------- ### List and Filter Users Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Retrieve all users with optional filtering by username, status, and pagination support. ```APIDOC ## GET /api/users ### Description Retrieve all users with optional filtering by username, status, and pagination support. ### Method GET ### Endpoint `/api/users` ### Parameters #### Query Parameters - **page** (int) - Optional - The page number for pagination. - **size** (int) - Optional - The number of users per page. - **username** (str) - Optional - Filter users by username. - **status** (list[str]) - Optional - Filter users by status (e.g., 'active', 'limited'). - **order_by** (str) - Optional - Field to sort users by. - **descending** (bool) - Optional - If true, sort in descending order. ### Request Example ```python import asyncio from marzneshin.api import MarzneshinAPI async def list_users(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Get all users (paginated) users = await api.get_users(page=1, size=50) print(f"Total users: {users['total']}") # Filter by username filtered = await api.get_users(username='john') # Filter by status and sort active_users = await api.get_users( status=['active', 'limited'], order_by='data_limit', descending=True, page=1, size=100 ) for user in active_users['items']: print(f"Username: {user['username']}, Status: {user['status']}") return users asyncio.run(list_users()) ``` ### Response #### Success Response (200) - **total** (int) - The total number of users. - **items** (list[dict]) - A list of user objects. - **username** (str) - The username of the user. - **status** (str) - The status of the user. - **data_limit** (int) - The data limit for the user in bytes. - **expire_date** (str) - The expiration date of the user's subscription. #### Response Example ```json { "total": 150, "items": [ { "username": "john_doe", "status": "active", "data_limit": 10737418240, "expire_date": "2024-11-26T10:00:00Z" } ] } ``` ``` -------------------------------- ### Modify User Subscription with Marzneshin API Client in Python Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Demonstrates how to update an existing user's subscription details using the Marzneshin API client. Allows modification of expiration, data limits, reset strategies, notes, and service assignments. Requires Python 3.10+ and the marzneshin library. ```python import asyncio from datetime import datetime, timedelta from marzneshin.api import MarzneshinAPI from marzneshin.models import UserModify async def modify_user_subscription(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Update user with new expiration and increased data limit updated_data = UserModify( username='john_doe', expire_strategy='fixed_date', expire_date=(datetime.now() + timedelta(days=60)).isoformat(), data_limit=21474836480, # 20GB in bytes data_limit_reset_strategy='no_reset', note='Upgraded to premium plan', service_ids=[1, 2, 3, 4] # Add service 4 ) try: result = await api.modify_user('john_doe', updated_data) print(f"User updated: {result['username']}") print(f"New expiration: {result['expire_date']}") print(f"New data limit: {result['data_limit']} bytes") return result except Exception as e: print(f"Error modifying user: {e}") return None asyncio.run(modify_user_subscription()) ``` -------------------------------- ### Manage Nodes with Marzneshin API Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Handles the management of proxy nodes in the cluster, including listing, adding, updating, reconnecting, retrieving Xray configuration, and deleting nodes. It utilizes NodeCreate and NodeModify models for data structures. Requires MarzneshinAPI and model imports. ```python import asyncio from marzneshin.api import MarzneshinAPI from marzneshin.models import NodeCreate, NodeModify async def manage_nodes(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # List all nodes nodes = await api.get_nodes(page=1, size=50) print(f"Total nodes: {nodes['total']}") # Add new node new_node = NodeCreate( name='eu-germany-1', address='192.168.1.100', port=53042, connection_backend='grpclib', usage_coefficient=1.0, inbounds=[1, 2] # Assign inbounds ) created = await api.add_node(new_node) print(f"Node created with ID: {created['id']}") # Update node node_update = NodeModify( name='eu-germany-1-updated', usage_coefficient=1.5, status='connected' ) updated = await api.modify_node(created['id'], node_update) print(f"Node updated: {updated['name']}") # Reconnect node await api.reconnect_node(created['id']) print("Node reconnected") # Get node Xray configuration config = await api.get_node_xray_config(created['id']) print(f"Node Xray config: {config}") # Delete node await api.remove_node(created['id']) print("Node removed") asyncio.run(manage_nodes()) ``` -------------------------------- ### System Statistics API Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Retrieve system-wide statistics including counts for admins, nodes, and users, as well as traffic and usage data. It also allows fetching node usage for a specific period. ```APIDOC ## GET System Statistics ### Description Retrieves system-wide statistics for admins, nodes, and users. This includes total counts, connection status for nodes, traffic data, and user-specific metrics. ### Method GET ### Endpoint `/stats` ### Parameters #### Query Parameters - **start** (string) - Optional - The start of the period for node usage statistics (ISO 8601 format). - **end** (string) - Optional - The end of the period for node usage statistics (ISO 8601 format). ### Response #### Success Response (200) - **admins** (object) - Statistics related to administrators. - **total** (integer) - Total number of administrators. - **sudo_count** (integer) - Number of administrators with sudo privileges. - **nodes** (object) - Statistics related to nodes. - **total** (integer) - Total number of nodes. - **connected** (integer) - Number of connected nodes. - **disconnected** (integer) - Number of disconnected nodes. - **total_traffic** (integer) - Total traffic in bytes across all nodes. - **users** (object) - Statistics related to users. - **total** (integer) - Total number of users. - **active** (integer) - Number of active users. - **expired** (integer) - Number of expired user accounts. - **limited** (integer) - Number of users with data limits. - **disabled** (integer) - Number of disabled user accounts. - **total_usage** (integer) - Total data usage in bytes across all users. - **node_usage** (object) - Statistics for node usage over a specified period (if `start` and `end` parameters are provided). ### Request Example ```python # Example using the MarzneshinAPI client api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') admin_stats = await api.get_admins_stats() node_stats = await api.get_nodes_stats() user_stats = await api.get_users_stats() node_usage = await api.get_node_usage(start='2025-01-01T00:00:00', end='2025-12-31T23:59:59') ``` ### Response Example (Partial) ```json { "admins": {"total": 5, "sudo_count": 2}, "nodes": {"total": 10, "connected": 8, "disconnected": 2, "total_traffic": 1024000000}, "users": {"total": 100, "active": 95, "expired": 3, "limited": 2, "disabled": 0, "total_usage": 512000000000}, "node_usage": [ {"node_id": "node1", "traffic": 500000000} ] } ``` ``` -------------------------------- ### User Lifecycle Management API Source: https://context7.com/sm1ky/marzneshin_api/llms.txt A comprehensive set of endpoints to manage the entire lifecycle of a user, from creation and modification to suspension, reactivation, and eventual removal. ```APIDOC ## User Management Endpoints ### Description These endpoints facilitate the complete management of user accounts, including creation, monitoring, modification, and deletion. ### Method POST, GET, PUT, DELETE ### Endpoints - `/users` (POST, GET) - `/users/{username}` (GET, PUT, DELETE) - `/users/{username}/usage` (GET) - `/users/{username}/enable` (PUT) - `/users/{username}/disable` (PUT) - `/users/{username}/reset_usage` (POST) - `/users/{username}/set_owner` (PUT) - `/users/{username}/revoke_subscription` (POST) ### Parameters #### Path Parameters - **username** (string) - Required - The unique identifier for the user. #### Query Parameters - **start** (string) - Optional - The start date for usage statistics (ISO 8601 format). - **end** (string) - Optional - The end date for usage statistics (ISO 8601 format). #### Request Body (for POST `/users`) - **username** (string) - Required - The desired username for the new user. - **expire_strategy** (string) - Required - Strategy for expiration ('fixed_date', 'none'). - **expire_date** (string) - Optional - The expiration date in ISO 8601 format if `expire_strategy` is 'fixed_date'. - **data_limit** (integer) - Optional - The data limit in bytes for the user. - **data_limit_reset_strategy** (string) - Optional - Strategy for data limit reset ('month', 'none'). - **note** (string) - Optional - A descriptive note for the user. - **service_ids** (array of integers) - Optional - IDs of services associated with the user. #### Request Body (for PUT `/users/{username}`) - **data_limit** (integer) - Optional - New data limit in bytes. - **expire_date** (string) - Optional - New expiration date in ISO 8601 format. - **note** (string) - Optional - Updated descriptive note. #### Request Body (for PUT `/users/{username}/set_owner`) - **owner_username** (string) - Required - The username of the new owner. ### Request Example ```python import asyncio from datetime import datetime, timedelta from marzneshin.api import MarzneshinAPI from marzneshin.models import UserCreate, UserModify async def manage_user_lifecycle(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Create user new_user = UserCreate(username='test_user', expire_date=(datetime.now() + timedelta(days=30)).isoformat(), data_limit=10*1024*1024*1024) user = await api.add_user(new_user) # Monitor usage user_info = await api.get_user('test_user') # Upgrade user plan upgrade = UserModify(username='test_user', data_limit=20*1024*1024*1024) await api.modify_user('test_user', upgrade) # Disable user await api.disable_user('test_user') # Enable user await api.enable_user('test_user') # Remove user await api.remove_user('test_user') asyncio.run(manage_user_lifecycle()) ``` ### Response #### Success Response (200, 201, 204) Responses vary depending on the action. Creation typically returns the created user object. Modification and deletion often return a success status or no content. Usage statistics return a usage object. #### Response Example (User Creation) ```json { "username": "customer_001", "key": "some_unique_key", "used_traffic": 0, "data_limit": 10737418240, "expire_date": "2023-12-15T10:30:00Z", "is_active": true, "is_disabled": false } ``` #### Response Example (Usage Statistics) ```json { "start_date": "2023-11-01T00:00:00Z", "end_date": "2023-11-30T23:59:59Z", "used_traffic": 5120000000 } ``` ``` -------------------------------- ### Manage User Operations with Marzneshin API Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Performs various user control operations including disabling, enabling, resetting data usage, revoking subscriptions, and removing users. Requires the MarzneshinAPI library and an active API connection. Errors during operations are caught and printed. ```python import asyncio from marzneshin.api import MarzneshinAPI async def manage_user(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') try: # Disable user (suspend access) await api.disable_user('john_doe') print("User disabled") # Enable user (restore access) await api.enable_user('john_doe') print("User enabled") # Reset data usage counter await api.reset_user_data_usage('john_doe') print("Usage reset to 0") # Revoke subscription (generates new subscription key) result = await api.revoke_user_subscription('john_doe') print(f"New subscription key: {result['key']}") # Delete user completely await api.remove_user('john_doe') print("User removed") except Exception as e: print(f"Error: {e}") asyncio.run(manage_user()) ``` -------------------------------- ### Modify User Source: https://context7.com/sm1ky/marzneshin_api/llms.txt Update existing user properties including services, data limits, and expiration settings. ```APIDOC ## PUT /api/users/{username} ### Description Update existing user properties including services, data limits, and expiration settings. ### Method PUT ### Endpoint `/api/users/{username}` ### Parameters #### Path Parameters - **username** (str) - Required - The username of the user to modify. #### Request Body - **UserModify** (object) - Required - User modification data. - **expire_strategy** (str) - Optional - The expiration strategy ('fixed_date', 'never'). - **expire_date** (str) - Optional - The expiration date in ISO format. - **data_limit** (int) - Optional - The data limit in bytes. - **data_limit_reset_strategy** (str) - Optional - Strategy for resetting data limit ('month', 'day', 'no_reset'). - **note** (str) - Optional - A note for the user. - **service_ids** (list[int]) - Optional - A list of service IDs to assign to the user. ### Request Example ```python import asyncio from datetime import datetime, timedelta from marzneshin.api import MarzneshinAPI from marzneshin.models import UserModify async def modify_user_subscription(): api = MarzneshinAPI('http://127.0.0.1:3500', 'admin', 'admin') # Update user with new expiration and increased data limit updated_data = UserModify( expire_strategy='fixed_date', expire_date=(datetime.now() + timedelta(days=60)).isoformat(), data_limit=21474836480, # 20GB in bytes data_limit_reset_strategy='no_reset', note='Upgraded to premium plan', service_ids=[1, 2, 3, 4] # Add service 4 ) try: result = await api.modify_user('john_doe', updated_data) print(f"User updated: {result['username']}") print(f"New expiration: {result['expire_date']}") print(f"New data limit: {result['data_limit']} bytes") return result except Exception as e: print(f"Error modifying user: {e}") return None asyncio.run(modify_user_subscription()) ``` ### Response #### Success Response (200) - **username** (str) - The username of the modified user. - **expire_date** (str) - The updated expiration date. - **data_limit** (int) - The updated data limit in bytes. #### Response Example ```json { "username": "john_doe", "expire_date": "2025-01-24T10:00:00Z", "data_limit": 21474836480 } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.