### Install xtlsapi via pip Source: https://github.com/hiddify/xtlsapi/blob/main/README.md Install the library using the Python package manager. ```bash pip install xtlsapi ``` -------------------------------- ### Install Project in Develop Mode Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Install the xtlsapi project in development mode using the Makefile. ```bash make install ``` -------------------------------- ### Makefile Targets Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Overview of the available targets in the Makefile, including installation, formatting, linting, testing, and documentation building. ```bash Targets: help: ## Show the help. install: ## Install the project in dev mode. fmt: ## Format code using black & isort. lint: ## Run pep8, black, mypy linters. test: lint ## Run tests and generate coverage report. watch: ## Run tests on every change. clean: ## Clean unused files. virtualenv: ## Create a virtual environment. release: ## Create a new tag for release. docs: ## Build the documentation. switch-to-poetry: ## Switch to poetry package manager. init: ## Initialize the project based on an application template. ``` -------------------------------- ### Makefile Targets Source: https://github.com/hiddify/xtlsapi/blob/main/ABOUT_THIS_TEMPLATE.md A list of available targets in the Makefile for managing project utilities such as installation, formatting, linting, testing, cleaning, virtual environment creation, release tagging, documentation building, and switching package managers. ```makefile help: ## Show the help. install: ## Install the project in dev mode. fmt: ## Format code using black & isort. lint: ## Run pep8, black, mypy linters. test: lint ## Run tests and generate coverage report. watch: ## Run tests on every change. clean: ## Clean unused files. virtualenv: ## Create a virtual environment. release: ## Create a new tag for release. docs: ## Build the documentation. switch-to-poetry: ## Switch to poetry package manager. init: ## Initialize the project based on an application template. ``` -------------------------------- ### Get Inbound Traffic Statistics Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves and prints the upload traffic for a specific inbound tag. Calculates and prints total inbound traffic (upload + download) if both are available. ```python inbound_upload = xray_client.get_inbound_upload_traffic(inbound_tag) if inbound_upload: print(f"Inbound '{inbound_tag}' upload: {utils.human_readable_bytes(inbound_upload)}") # Output: Inbound 'vless-tcp' upload: 2.3 GB # Calculate total inbound traffic inbound_download = xray_client.get_inbound_download_traffic(inbound_tag) if inbound_upload and inbound_download: total = inbound_upload + inbound_download print(f"Total traffic: {utils.human_readable_bytes(total)}") ``` -------------------------------- ### Get User Upload Traffic Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves total upload traffic for a user by email. The optional `reset` parameter clears the counter after reading. ```python from xtlsapi import XrayClient, utils xray_client = XrayClient('127.0.0.1', 10085) user_email = 'user@example.com' # Get upload traffic in bytes upload_bytes = xray_client.get_client_upload_traffic(user_email) if upload_bytes: readable = utils.human_readable_bytes(upload_bytes) print(f"Upload traffic for {user_email}: {readable}") # Output: Upload traffic for user@example.com: 256.5 MB else: print(f"No traffic data found for {user_email}") ``` -------------------------------- ### Get Inbound Traffic Statistics Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieve upload and download traffic statistics for a specific inbound tag. Calculates and displays total traffic in a human-readable format. ```APIDOC ## Get Inbound Traffic Statistics ### Description Retrieves upload and download traffic statistics for a specific inbound tag. Calculates and displays total traffic in a human-readable format. ### Method GET (Implied by function call) ### Endpoint Not directly exposed as an HTTP endpoint, but functions interact with the Xray API. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xtlsapi import XrayClient, utils xray_client = XrayClient('127.0.0.1', 10085) inbound_tag = 'vless-tcp' inbound_upload = xray_client.get_inbound_upload_traffic(inbound_tag) inbound_download = xray_client.get_inbound_download_traffic(inbound_tag) if inbound_upload and inbound_download: total = inbound_upload + inbound_download print(f"Inbound '{inbound_tag}' upload: {utils.human_readable_bytes(inbound_upload)}") print(f"Total traffic: {utils.human_readable_bytes(total)}") ``` ### Response #### Success Response (200) Traffic statistics (numeric values for upload and download). #### Response Example ``` Inbound 'vless-tcp' upload: 2.3 GB Total traffic: 5.1 GB ``` ``` -------------------------------- ### Get User Download Traffic Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves total download traffic for a user by email. Optionally resets the traffic counter after reading. Returns None if the user is not found. ```python from xtlsapi import XrayClient, utils xray_client = XrayClient('127.0.0.1', 10085) user_email = 'user@example.com' # Get download traffic in bytes download_bytes = xray_client.get_client_download_traffic(user_email) if download_bytes: # Convert to human-readable format readable = utils.human_readable_bytes(download_bytes) print(f"Download traffic for {user_email}: {readable}") # Output: Download traffic for user@example.com: 1.25 GB else: print(f"No traffic data found for {user_email}") # Get traffic and reset counter download_bytes = xray_client.get_client_download_traffic(user_email, reset=True) print(f"Traffic before reset: {utils.human_readable_bytes(download_bytes)}") ``` -------------------------------- ### stats_online - Get User Online Status Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves the online count or status for a specific user. Useful for monitoring user connections. ```APIDOC ## stats_online - Get User Online Status ### Description Retrieves the online count or status for a specific user. Useful for monitoring user connections. ### Method GET (Implied by function call) ### Endpoint Not directly exposed as an HTTP endpoint, but functions interact with the Xray API. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xtlsapi import XrayClient xray_client = XrayClient('127.0.0.1', 10085) user_email = 'user@example.com' # Get online status online_count = xray_client.stats_online(user_email) print(f"User {user_email} online connections: {online_count}") ``` ### Response #### Success Response (200) - **online_count** (integer) - The number of active connections for the user. #### Response Example ``` User user@example.com online connections: 2 ``` ``` -------------------------------- ### Get Inbound Upload Traffic Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves total upload traffic for a specific inbound connection tag. Use with download traffic for complete endpoint statistics. ```python from xtlsapi import XrayClient, utils xray_client = XrayClient('127.0.0.1', 10085) inbound_tag = 'vless-tcp' ``` -------------------------------- ### Get User Online Status Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves the online count for a specific user, useful for monitoring current connections. Requires the user's email for identification. ```python from xtlsapi import XrayClient xray_client = XrayClient('127.0.0.1', 10085) user_email = 'user@example.com' # Get online status online_count = xray_client.stats_online(user_email) print(f"User {user_email} online connections: {online_count}") # Output: User user@example.com online connections: 2 ``` -------------------------------- ### stats_online_ip_list - Get User Online IP Addresses Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves a dictionary of IP addresses currently connected for a specific user. Maps IP addresses to their last cleanup timestamp. ```APIDOC ## stats_online_ip_list - Get User Online IP Addresses ### Description Retrieves a dictionary of IP addresses currently connected for a specific user. Maps IP addresses to their last cleanup timestamp. ### Method GET (Implied by function call) ### Endpoint Not directly exposed as an HTTP endpoint, but functions interact with the Xray API. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xtlsapi import XrayClient xray_client = XrayClient('127.0.0.1', 10085) user_email = 'user@example.com' # Get online IPs for user online_ips = xray_client.stats_online_ip_list(user_email) print(f"Online IPs for {user_email}:") for ip, timestamp in online_ips.items(): print(f" {ip}: last cleanup at {timestamp}") # Get count of unique IPs ip_count = len(online_ips) print(f"Total unique IPs: {ip_count}") ``` ### Response #### Success Response (200) - **online_ips** (object) - A dictionary where keys are IP addresses (string) and values are last cleanup timestamps (integer). #### Response Example ```json { "192.168.1.100": 1699459200, "10.0.0.50": 1699459180 } ``` ``` -------------------------------- ### Get User Online IP Addresses Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves a dictionary of IP addresses currently connected for a specific user, mapping IPs to their last cleanup timestamp. Useful for tracking connections and implementing IP-based restrictions. Also provides the count of unique IPs. ```python from xtlsapi import XrayClient xray_client = XrayClient('127.0.0.1', 10085) user_email = 'user@example.com' # Get online IPs for user online_ips = xray_client.stats_online_ip_list(user_email) print(f"Online IPs for {user_email}:") for ip, timestamp in online_ips.items(): print(f" {ip}: last cleanup at {timestamp}") # Output: # Online IPs for user@example.com: # 192.168.1.100: last cleanup at 1699459200 # 10.0.0.50: last cleanup at 1699459180 # Get count of unique IPs ip_count = len(online_ips) print(f"Total unique IPs: {ip_count}") ``` -------------------------------- ### Get Inbound Download Traffic Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves total download traffic for a specific inbound connection tag. Useful for monitoring traffic on proxy endpoints. Can optionally reset the counter. ```python from xtlsapi import XrayClient, utils xray_client = XrayClient('127.0.0.1', 10085) inbound_tag = 'vmess-ws' # Get inbound download traffic inbound_download = xray_client.get_inbound_download_traffic(inbound_tag) if inbound_download: print(f"Inbound '{inbound_tag}' download: {utils.human_readable_bytes(inbound_download)}") # Output: Inbound 'vmess-ws' download: 15.7 GB else: print(f"No traffic data for inbound: {inbound_tag}") # Get traffic and reset the counter inbound_download = xray_client.get_inbound_download_traffic(inbound_tag, reset=True) ``` -------------------------------- ### Initialize Project with Template Source: https://github.com/hiddify/xtlsapi/blob/main/ABOUT_THIS_TEMPLATE.md Run this command to initialize the project by selecting and applying an application template (e.g., Flask, FastAPI, Click, Typer). ```bash $ make init Which template do you want to apply? [flask, fastapi, click, typer]? > flask Generating a new project with Flask ... ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Build the project's documentation locally using the 'docs' target in the Makefile. Ensure new changes are documented. ```bash make docs ``` -------------------------------- ### MkDocs CLI Commands Source: https://github.com/hiddify/xtlsapi/blob/main/docs/index.md Common commands for project initialization, development, and building. ```bash mkdocs new [dir-name] ``` ```bash mkdocs serve ``` ```bash mkdocs build ``` ```bash mkdocs -h ``` -------------------------------- ### Makefile Usage Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Display the help message for the Makefile, listing available targets and their descriptions. ```bash make ``` -------------------------------- ### Create Virtual Environment Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Use the Makefile to create a Python virtual environment for the project. ```bash make virtualenv ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Activate the created virtual environment using the provided command. ```bash source .venv/bin/activate ``` -------------------------------- ### Initialize SingboxClient Connection Source: https://context7.com/hiddify/xtlsapi/llms.txt Establishes a gRPC connection to a Sing-box proxy server API. This client is specifically for Sing-box. ```python from xtlsapi import SingboxClient # Connect to Sing-box API singbox_client = SingboxClient('127.0.0.1', 10086) # Ready for stats queries print(f"Connected to Sing-box at {singbox_client.host}:{singbox_client.port}") ``` -------------------------------- ### Format Code Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Format the project's code using black and isort by running the 'fmt' target in the Makefile. ```bash make fmt ``` -------------------------------- ### Display Project Version Source: https://github.com/hiddify/xtlsapi/blob/main/ABOUT_THIS_TEMPLATE.md Use this command to display the project's version without needing to import the module. This is useful for CI, logs, and debugging. ```bash cat xtlsapi/VERSION ``` -------------------------------- ### SingboxClient - Initialize Connection Source: https://context7.com/hiddify/xtlsapi/llms.txt Provides a gRPC connection to Sing-box proxy servers, offering traffic statistics functionality. ```APIDOC ## SingboxClient - Initialize Connection ### Description Provides a gRPC connection to Sing-box proxy servers. It offers traffic statistics functionality similar to `XrayClient` but is specifically designed for the Sing-box server implementation. ### Method Instantiate `SingboxClient` ### Endpoint N/A (Client-side connection) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xtlsapi import SingboxClient # Connect to Sing-box API singbox_client = SingboxClient('127.0.0.1', 10086) # Ready for stats queries print(f"Connected to Sing-box at {singbox_client.host}:{singbox_client.port}") ``` ### Response #### Success Response (200) N/A (Client-side connection) #### Response Example N/A ``` -------------------------------- ### Complete User Management with xtlsapi Source: https://context7.com/hiddify/xtlsapi/llms.txt Demonstrates the full lifecycle of a VLESS client, including creation, traffic monitoring, and removal. Ensure the Xray client is accessible at '127.0.0.1:10085' and the inbound tag 'vless-ws' is configured. ```python from xtlsapi import XrayClient, utils, exceptions def main(): # Initialize client xray = XrayClient('127.0.0.1', 10085) # Configuration inbound_tag = 'vless-ws' uuid = utils.generate_random_user_id() email = f'{uuid}@myproxy.com' print(f"Managing user: {email}") print(f"UUID: {uuid}") print("-" * 50) try: # 1. Add new VLESS client xray.add_client( inbound_tag=inbound_tag, user_id_or_password=uuid, email=email, protocol='vless', flow='xtls-rprx-vision' ) print(f"[+] User created successfully") # 2. Monitor traffic (initially zero for new user) download = xray.get_client_download_traffic(email) upload = xray.get_client_upload_traffic(email) print(f"[i] Download: {utils.human_readable_bytes(download or 0)}") print(f"[i] Upload: {utils.human_readable_bytes(upload or 0)}") # 3. Check inbound traffic inbound_down = xray.get_inbound_download_traffic(inbound_tag) inbound_up = xray.get_inbound_upload_traffic(inbound_tag) print(f"[i] Inbound total download: {utils.human_readable_bytes(inbound_down or 0)}") print(f"[i] Inbound total upload: {utils.human_readable_bytes(inbound_up or 0)}") # 4. Check online status try: online_ips = xray.stats_online_ip_list(email) print(f"[i] Online IPs: {len(online_ips)}") except: print("[i] Online stats not available") # 5. Remove user xray.remove_client(inbound_tag, email) print(f"[-] User removed successfully") except exceptions.EmailAlreadyExists as e: print(f"[!] User {e.email} already exists") except exceptions.InboundNotFound as e: print(f"[!] Inbound '{e.inbound_tag}' not found") except exceptions.XRayException as e: print(f"[!] Error: {e.details}") except Exception as e: print(f"[!] Unexpected error: {e}") if __name__ == '__main__': main() ``` -------------------------------- ### Initialize XrayClient Connection Source: https://context7.com/hiddify/xtlsapi/llms.txt Establishes a gRPC connection to an Xray core API endpoint. Ensure the API is configured in your Xray server. ```python from xtlsapi import XrayClient, utils, exceptions # Connect to Xray core API xray_client = XrayClient('127.0.0.1', 10085) # The client is now ready for traffic stats and client management print(f"Connected to Xray at {xray_client.host}:{xray_client.port}") ``` -------------------------------- ### Manage Xray clients and traffic stats Source: https://github.com/hiddify/xtlsapi/blob/main/README.md Initialize the XrayClient to retrieve traffic statistics, add or remove clients, and restart the logger. ```python from xtlsapi import XrayClient, utils, exceptions xray_client = XrayClient('1.2.3.4', 1234) user_id = utils.generate_random_user_id() user_email = utils.generate_random_email() inbound_tag = 'inbound-tag' # Get stats print(utils.human_readable_bytes(xray_client.get_client_download_traffic('user-email@mail.com'))) print(utils.human_readable_bytes(xray_client.get_client_upload_traffic('user-email@mail.com'))) print(utils.human_readable_bytes(xray_client.get_inbound_download_traffic(inbound_tag))) print(utils.human_readable_bytes(xray_client.get_inbound_upload_traffic(inbound_tag))) # Add & Remove client user = xray_client.add_client(inbound_tag, user_id, user_email) if user: print(user) xray_client.remove_client(inbound_tag, user_email) # restart logger xray_client.restart_logger() ``` -------------------------------- ### XrayClient - Initialize Connection Source: https://context7.com/hiddify/xtlsapi/llms.txt Establishes a gRPC connection to an Xray core server for management operations. Requires the host address and port number of the Xray API endpoint. ```APIDOC ## XrayClient - Initialize Connection ### Description Establishes a gRPC connection to an Xray core server for management operations. It requires the host address and port number of the Xray API endpoint configured in your Xray server. ### Method Instantiate `XrayClient` ### Endpoint N/A (Client-side connection) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xtlsapi import XrayClient, utils, exceptions # Connect to Xray core API xray_client = XrayClient('127.0.0.1', 10085) # The client is now ready for traffic stats and client management print(f"Connected to Xray at {xray_client.host}:{xray_client.port}") ``` ### Response #### Success Response (200) N/A (Client-side connection) #### Response Example N/A ``` -------------------------------- ### Run Project Tests Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Execute the project's tests to ensure everything is functioning correctly. This command also runs linters. ```bash make test ``` -------------------------------- ### Run Linter Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Run the linters (pep8, black, mypy) for the project using the 'lint' target in the Makefile. ```bash make lint ``` -------------------------------- ### MkDocs Project Layout Source: https://github.com/hiddify/xtlsapi/blob/main/docs/index.md Standard file structure for an MkDocs project. ```text mkdocs.yml # The configuration file. docs/ index.md # The documentation homepage. ... # Other markdown pages, images and other files. ``` -------------------------------- ### Create New Release Tag Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Create a new Git tag for a release and push it to the remote repository. This action triggers automatic release creation on GitHub and PyPI. ```bash make release ``` -------------------------------- ### Handle Xray API Exceptions Source: https://context7.com/hiddify/xtlsapi/llms.txt Demonstrates how to handle specific exceptions like EmailAlreadyExists, EmailNotFound, and InboundNotFound when managing clients. All exceptions inherit from XRayException. ```python from xtlsapi import XrayClient, exceptions xray_client = XrayClient('127.0.0.1', 10085) def manage_user(inbound_tag: str, email: str, user_id: str): try: # Attempt to add a new user xray_client.add_client(inbound_tag, user_id, email, protocol='vless') print(f"User {email} added successfully") except exceptions.EmailAlreadyExists as e: # User already exists - handle gracefully print(f"User {e.email} already exists, skipping...") except exceptions.InboundNotFound as e: # Invalid inbound tag print(f"Error: Inbound '{e.inbound_tag}' not found in Xray config") raise except exceptions.XRayException as e: # General Xray error print(f"Xray error occurred: {e.details}") raise def cleanup_user(inbound_tag: str, email: str): try: xray_client.remove_client(inbound_tag, email) print(f"User {email} removed") except exceptions.EmailNotFound as e: # User doesn't exist - may have been already removed print(f"User {e.email} not found, may have been already removed") except exceptions.InboundNotFound as e: print(f"Error: Inbound '{e.inbound_tag}' does not exist") # Usage manage_user('vless-ws', 'newuser@example.com', 'uuid-here') cleanup_user('vless-ws', 'olduser@example.com') ``` -------------------------------- ### Clone xtlsapi Repository Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Clone your forked repository of xtlsapi to your local machine. ```bash git clone git@github.com:YOUR_GIT_USERNAME/xtlsapi.git ``` -------------------------------- ### add_client - Add New Proxy Client Source: https://context7.com/hiddify/xtlsapi/llms.txt Adds a new client/user to an existing inbound connection. Supports multiple protocols (VLESS, VMess, Trojan, Shadowsocks) with protocol-specific parameters. Handles potential exceptions like EmailAlreadyExists and InboundNotFound. ```APIDOC ## add_client - Add New Proxy Client ### Description Adds a new client/user to an existing inbound connection. Supports multiple protocols (VLESS, VMess, Trojan, Shadowsocks) with protocol-specific parameters. Handles potential exceptions like EmailAlreadyExists and InboundNotFound. ### Method POST (Implied by function call) ### Endpoint Not directly exposed as an HTTP endpoint, but functions interact with the Xray API. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **inbound_tag** (string) - Required - The tag of the inbound connection to add the client to. - **user_id_or_password** (string) - Required - The user ID (for VLESS/VMess) or password (for Trojan/Shadowsocks). - **email** (string) - Required - A unique email identifier for the user. - **protocol** (string) - Required - The protocol to use (e.g., 'vless', 'vmess', 'trojan', 'shadowsocks'). - **flow** (string) - Optional - XTLS flow for VLESS (e.g., 'xtls-rprx-vision'). - **alter_id** (integer) - Optional - Alter ID for VMess. - **cipher** (string) - Optional - Cipher for Shadowsocks (e.g., 'chacha20_poly1305'). ### Request Example ```python from xtlsapi import XrayClient, utils, exceptions xray_client = XrayClient('127.0.0.1', 10085) # Generate random credentials user_id = utils.generate_random_user_id() user_email = utils.generate_random_email() inbound_tag = 'vless-ws' try: # Add VLESS client user = xray_client.add_client( inbound_tag=inbound_tag, user_id_or_password=user_id, email=user_email, protocol='vless', flow='xtls-rprx-vision' ) print(f"Added VLESS user: {user}") # Add VMess client vmess_user = xray_client.add_client( inbound_tag='vmess-ws', user_id_or_password=user_id, email='vmess-user@example.com', protocol='vmess', alter_id=0 ) print(f"Added VMess user: {vmess_user}") # Add Trojan client trojan_password = 'secure-password-123' trojan_user = xray_client.add_client( inbound_tag='trojan-tcp', user_id_or_password=trojan_password, email='trojan-user@example.com', protocol='trojan' ) print(f"Added Trojan user with password: {trojan_user}") # Add Shadowsocks client ss_password = 'shadowsocks-password' ss_user = xray_client.add_client( inbound_tag='ss-tcp', user_id_or_password=ss_password, email='ss-user@example.com', protocol='shadowsocks', cipher='chacha20_poly1305' ) print(f"Added Shadowsocks user: {ss_user}") except exceptions.EmailAlreadyExists as e: print(f"User already exists: {e.email}") except exceptions.InboundNotFound as e: print(f"Inbound not found: {e.inbound_tag}") except exceptions.XRayException as e: print(f"XRay error: {e.details}") ``` ### Response #### Success Response (200) - **user** (object) - An object representing the newly added user, containing their configuration details. #### Response Example ```json { "id": "generated-uuid", "email": "random-email@example.com", "protocol": "vless", "flow": "xtls-rprx-vision", "streamSettings": { ... } } ``` ``` -------------------------------- ### Create a New Branch for Contributions Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Create a new Git branch to work on your contributions following the project's workflow. ```bash git checkout -b my_contribution ``` -------------------------------- ### Add New Proxy Client Source: https://context7.com/hiddify/xtlsapi/llms.txt Adds a new client/user to an existing inbound connection, supporting VLESS, VMess, Trojan, and Shadowsocks protocols. Handles potential exceptions like 'EmailAlreadyExists' or 'InboundNotFound'. ```python from xtlsapi import XrayClient, utils, exceptions xray_client = XrayClient('127.0.0.1', 10085) # Generate random credentials user_id = utils.generate_random_user_id() # UUID for VLESS/VMess user_email = utils.generate_random_email() # Random email identifier inbound_tag = 'vless-ws' try: # Add VLESS client (default protocol) user = xray_client.add_client( inbound_tag=inbound_tag, user_id_or_password=user_id, email=user_email, protocol='vless', flow='xtls-rprx-vision' # Optional XTLS flow ) print(f"Added VLESS user: {user}") # Add VMess client vmess_user = xray_client.add_client( inbound_tag='vmess-ws', user_id_or_password=user_id, email='vmess-user@example.com', protocol='vmess', alter_id=0 ) print(f"Added VMess user: {vmess_user}") # Add Trojan client trojan_password = 'secure-password-123' trojan_user = xray_client.add_client( inbound_tag='trojan-tcp', user_id_or_password=trojan_password, email='trojan-user@example.com', protocol='trojan' ) print(f"Added Trojan user with password: {trojan_user}") # Add Shadowsocks client ss_password = 'shadowsocks-password' ss_user = xray_client.add_client( inbound_tag='ss-tcp', user_id_or_password=ss_password, email='ss-user@example.com', protocol='shadowsocks', cipher='chacha20_poly1305' # Options: aes_128_gcm, aes_256_gcm, chacha20_poly1305, xchacha20_poly1305 ) print(f"Added Shadowsocks user: {ss_user}") except exceptions.EmailAlreadyExists as e: print(f"User already exists: {e.email}") except exceptions.InboundNotFound as e: print(f"Inbound not found: {e.inbound_tag}") except exceptions.XRayException as e: print(f"XRay error: {e.details}") ``` -------------------------------- ### Push Changes to Fork Source: https://github.com/hiddify/xtlsapi/blob/main/CONTRIBUTING.md Push your committed changes to your forked repository on the 'my_contribution' branch. ```bash git push origin my_contribution ``` -------------------------------- ### Query Statistics with Pattern Source: https://context7.com/hiddify/xtlsapi/llms.txt Queries statistics matching a specific pattern, allowing flexible retrieval of multiple statistics. Returns a list of stat objects containing name and value pairs. Can be used with a 'reset=True' option. ```python from xtlsapi import XrayClient xray_client = XrayClient('127.0.0.1', 10085) # Query all user traffic stats user_stats = xray_client.stats_query("user>>>") for stat in user_stats: print(f"{stat.name}: {stat.value}") # Output: # user>>>user1@example.com>>>traffic>>>uplink: 1234567 # user>>>user1@example.com>>>traffic>>>downlink: 9876543 # user>>>user2@example.com>>>traffic>>>uplink: 456789 # user>>>user2@example.com>>>traffic>>>downlink: 5432109 # Query all inbound stats inbound_stats = xray_client.stats_query("inbound>>>") # Query with reset stats = xray_client.stats_query("user>>>", reset=True) ``` -------------------------------- ### Restart Xray Logger Source: https://context7.com/hiddify/xtlsapi/llms.txt Restarts the Xray logger service. Useful for applying logging configuration changes or rotating log files without a full service restart. Catches XRayException for errors. ```python from xtlsapi import XrayClient, exceptions xray_client = XrayClient('127.0.0.1', 10085) try: xray_client.restart_logger() print("Logger restarted successfully") except exceptions.XRayException as e: print(f"Failed to restart logger: {e.details}") ``` -------------------------------- ### Generate Random Identifiers and Data Source: https://context7.com/hiddify/xtlsapi/llms.txt Provides utility functions for generating random user IDs (UUIDs), emails, names, tags, and available ports. Also includes a function to convert byte values to a human-readable format. ```python from xtlsapi import utils # Generate random UUID for VLESS/VMess user_id = utils.generate_random_user_id() print(f"Generated UUID: {user_id}") # Output: Generated UUID: 9623a083b4bf4dac83c202ba9b948714 # Generate random email for user identification email = utils.generate_random_email() print(f"Generated email: {email}") # Output: Generated email: a1b2c3d4e5f6g7h8@vump.com # Custom domain email email = utils.generate_random_email(tld='myproxy.com', hex_count=4) print(f"Custom email: {email}") # Output: Custom email: a1b2c3d4@myproxy.com # Generate random name name = utils.generate_random_name(hex_count=8) print(f"Random name: {name}") # Output: Random name: a1b2c3d4e5f6g7h8 # Generate random tag tag = utils.generate_random_tag() print(f"Random tag: {tag}") # Output: Random tag: Ab_cD-eFgHiJkLmN # Generate random available port port = utils.generate_random_port() print(f"Available port: {port}") # Output: Available port: 54321 # Convert bytes to human-readable format bytes_value = 1572864000 readable = utils.human_readable_bytes(bytes_value) print(f"{bytes_value} bytes = {readable}") # Output: 1572864000 bytes = 1.46 GB # Handle zero/None bytes print(utils.human_readable_bytes(0)) # Output: 0 B print(utils.human_readable_bytes(None)) # Output: 0 B ``` -------------------------------- ### restart_logger - Restart Xray Logger Source: https://context7.com/hiddify/xtlsapi/llms.txt Restarts the Xray logger service to apply configuration changes or rotate log files. ```APIDOC ## restart_logger ### Description Restarts the Xray logger service. This is useful when you need to apply logging configuration changes or rotate log files without restarting the entire Xray service. ### Response - **Success** - Returns nothing upon successful restart. - **Errors** - Raises `XRayException` if the operation fails. ``` -------------------------------- ### get_inbound_download_traffic Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves the total download traffic (in bytes) for a specific inbound connection identified by its tag. The optional `reset` parameter clears the traffic counter after reading. ```APIDOC ## get_inbound_download_traffic ### Description Retrieves the total download traffic (in bytes) for a specific inbound connection identified by its tag. This is useful for monitoring overall traffic on specific proxy endpoints. The optional `reset` parameter clears the traffic counter after reading. ### Method `get_inbound_download_traffic` ### Endpoint N/A (Client-side method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xtlsapi import XrayClient, utils xray_client = XrayClient('127.0.0.1', 10085) inbound_tag = 'vmess-ws' # Get inbound download traffic inbound_download = xray_client.get_inbound_download_traffic(inbound_tag) if inbound_download: print(f"Inbound '{inbound_tag}' download: {utils.human_readable_bytes(inbound_download)}") # Output: Inbound 'vmess-ws' download: 15.7 GB else: print(f"No traffic data for inbound: {inbound_tag}") # Get traffic and reset the counter inbound_download = xray_client.get_inbound_download_traffic(inbound_tag, reset=True) ``` ### Response #### Success Response (200) - **download_bytes** (integer) - Total download traffic in bytes for the specified inbound connection. #### Response Example ```json { "download_bytes": 16856070144 } ``` ``` -------------------------------- ### get_client_download_traffic Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves the total download traffic (in bytes) for a specific user. The optional `reset` parameter clears the traffic counter after reading. ```APIDOC ## get_client_download_traffic ### Description Retrieves the total download traffic (in bytes) for a specific user identified by their email address. The optional `reset` parameter clears the traffic counter after reading. Returns `None` if the user is not found or an error occurs. ### Method `get_client_download_traffic` ### Endpoint N/A (Client-side method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xtlsapi import XrayClient, utils xray_client = XrayClient('127.0.0.1', 10085) user_email = 'user@example.com' # Get download traffic in bytes download_bytes = xray_client.get_client_download_traffic(user_email) if download_bytes: # Convert to human-readable format readable = utils.human_readable_bytes(download_bytes) print(f"Download traffic for {user_email}: {readable}") # Output: Download traffic for user@example.com: 1.25 GB else: print(f"No traffic data found for {user_email}") # Get traffic and reset counter download_bytes = xray_client.get_client_download_traffic(user_email, reset=True) print(f"Traffic before reset: {utils.human_readable_bytes(download_bytes)}") ``` ### Response #### Success Response (200) - **download_bytes** (integer) - Total download traffic in bytes for the specified user. #### Response Example ```json { "download_bytes": 1342177280 } ``` ``` -------------------------------- ### stats_query - Query Statistics with Pattern Source: https://context7.com/hiddify/xtlsapi/llms.txt Queries statistics matching a specific pattern. Returns a list of stat objects containing name and value pairs. Can be used to query user or inbound statistics. ```APIDOC ## stats_query - Query Statistics with Pattern ### Description Queries statistics matching a specific pattern. Returns a list of stat objects containing name and value pairs. Can be used to query user or inbound statistics. ### Method GET (Implied by function call) ### Endpoint Not directly exposed as an HTTP endpoint, but functions interact with the Xray API. ### Parameters #### Path Parameters None #### Query Parameters - **pattern** (string) - Required - The pattern to match statistics against (e.g., "user>>>", "inbound>>>"). - **reset** (boolean) - Optional - If true, resets the statistics after querying. #### Request Body None ### Request Example ```python from xtlsapi import XrayClient xray_client = XrayClient('127.0.0.1', 10085) # Query all user traffic stats user_stats = xray_client.stats_query("user>>>") for stat in user_stats: print(f"{stat.name}: {stat.value}") # Query all inbound stats inbound_stats = xray_client.stats_query("inbound>>>") # Query with reset stats = xray_client.stats_query("user>>>", reset=True) ``` ### Response #### Success Response (200) - **stats** (list) - A list of stat objects, where each object has `name` (string) and `value` (number) properties. #### Response Example ```json [ {"name": "user>>>user1@example.com>>>traffic>>>uplink", "value": 1234567}, {"name": "user>>>user1@example.com>>>traffic>>>downlink", "value": 9876543} ] ``` ``` -------------------------------- ### get_inbound_upload_traffic Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves the total upload traffic (in bytes) for a specific inbound connection identified by its tag. The optional `reset` parameter clears the traffic counter after reading. ```APIDOC ## get_inbound_upload_traffic ### Description Retrieves the total upload traffic (in bytes) for a specific inbound connection identified by its tag. Combined with download traffic, this provides complete traffic statistics for proxy endpoints. The optional `reset` parameter clears the traffic counter after reading. ### Method `get_inbound_upload_traffic` ### Endpoint N/A (Client-side method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xtlsapi import XrayClient, utils xray_client = XrayClient('127.0.0.1', 10085) inbound_tag = 'vless-tcp' # Get inbound upload traffic inbound_upload = xray_client.get_inbound_upload_traffic(inbound_tag) if inbound_upload: print(f"Inbound '{inbound_tag}' upload: {utils.human_readable_bytes(inbound_upload)}") # Output: Inbound 'vless-tcp' upload: 5.2 GB else: print(f"No traffic data for inbound: {inbound_tag}") # Get traffic and reset the counter inbound_upload = xray_client.get_inbound_upload_traffic(inbound_tag, reset=True) ``` ### Response #### Success Response (200) - **upload_bytes** (integer) - Total upload traffic in bytes for the specified inbound connection. #### Response Example ```json { "upload_bytes": 5581504000 } ``` ``` -------------------------------- ### Remove Proxy Client Source: https://context7.com/hiddify/xtlsapi/llms.txt Removes a client from an inbound connection using their email. Handles EmailNotFound and InboundNotFound exceptions. ```python from xtlsapi import XrayClient, exceptions xray_client = XrayClient('127.0.0.1', 10085) user_email = 'user@example.com' inbound_tag = 'vless-ws' try: xray_client.remove_client(inbound_tag, user_email) print(f"Successfully removed user: {user_email}") except exceptions.EmailNotFound as e: print(f"User not found: {e.email}") except exceptions.InboundNotFound as e: print(f"Inbound not found: {e.inbound_tag}") except exceptions.XRayException as e: print(f"XRay error: {e.details}") ``` -------------------------------- ### get_client_upload_traffic Source: https://context7.com/hiddify/xtlsapi/llms.txt Retrieves the total upload traffic (in bytes) for a specific user. The optional `reset` parameter clears the counter after reading. ```APIDOC ## get_client_upload_traffic ### Description Retrieves the total upload traffic (in bytes) for a specific user identified by their email address. Similar to download traffic, the optional `reset` parameter clears the counter after reading. ### Method `get_client_upload_traffic` ### Endpoint N/A (Client-side method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from xtlsapi import XrayClient, utils xray_client = XrayClient('127.0.0.1', 10085) user_email = 'user@example.com' # Get upload traffic in bytes upload_bytes = xray_client.get_client_upload_traffic(user_email) if upload_bytes: readable = utils.human_readable_bytes(upload_bytes) print(f"Upload traffic for {user_email}: {readable}") # Output: Upload traffic for user@example.com: 256.5 MB else: print(f"No traffic data found for {user_email}") ``` ### Response #### Success Response (200) - **upload_bytes** (integer) - Total upload traffic in bytes for the specified user. #### Response Example ```json { "upload_bytes": 268435456 } ``` ``` -------------------------------- ### remove_client - Remove Proxy Client Source: https://context7.com/hiddify/xtlsapi/llms.txt Removes an existing client or user from a specific inbound connection using their email address. ```APIDOC ## remove_client ### Description Removes an existing client/user from an inbound connection by their email address. Raises `EmailNotFound` if the user doesn't exist, or `InboundNotFound` if the inbound tag is invalid. ### Parameters - **inbound_tag** (string) - Required - The tag of the inbound connection. - **user_email** (string) - Required - The email address of the user to remove. ### Response - **Success** - Returns nothing upon successful removal. - **Errors** - Raises `EmailNotFound` or `InboundNotFound` exceptions. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.