A Telegram bot for issuing VLESS keys on your own VPS automates VPN access management, allowing you to distribute over 100+ configurations to family members or a small team without manual setup for each key, saving 3-5 hours per week on administration and significantly reducing errors during manual generation and data transfer.
Owning your own VPN server on a VPS offers extensive capabilities for ensuring privacy and bypassing geo-restrictions. However, when it comes to providing access not just for yourself but also for several friends, relatives, or colleagues, manually managing each VLESS key, traffic limits, and expiration dates quickly becomes a chore. This is where a Telegram bot for issuing VPN keys comes in handy. It transforms a complex process into a few clicks, significantly simplifying server administration and making it accessible even to those without deep technical knowledge.
Why use a Telegram bot for VPN key distribution on your VPS?
The primary reason for using a bot to manage VPN keys is automation and scalability. Imagine needing to provide VPN access to dozens of users. Manually generating VLESS keys, setting traffic or time limits, and then individually sending each config takes an enormous amount of time. This also increases the risk of errors and inconsistencies. Automated config distribution via a Telegram bot solves these problems, allowing you to focus on more critical tasks rather than routine administration.
Save time and reduce admin workload with a VPN bot
Without a bot, every request for a new key, access renewal, or limit change requires the administrator to manually log into the server, interact with a management panel (e.g., Marzban or 3x-ui), generate the key, and send it to the user. On average, one such cycle takes 5 to 15 minutes, depending on the task's complexity and the administrator's experience. With 20-30 active users and periodic requests, this can consume several hours per week. The bot, however, performs these operations instantly, 24/7, without human intervention. This is especially relevant for those who provide VPN access as a service or for a large team requiring prompt access management.
User convenience and centralized VPN key management
For end-users, obtaining a VLESS key via a Telegram bot is an extremely simple and intuitive process. They just need to send a command to the bot, and within seconds, they receive a ready-to-use config or a link to it. There's no need to contact the administrator, wait for a response, or decipher complex instructions. All keys, their statuses, limits, and expiration dates are stored in a single bot database, ensuring centralized management. The administrator can view a list of active users, their traffic consumption, subscription expiration dates, and perform renewals, blocks, or key revocations at any time.
For those just starting their journey into self-hosted VPNs, we recommend checking out our complete guide to VPN on your own VPS, which will help lay a solid foundation.
How do Telegram bots automate VLESS config distribution?
The operational principle of Telegram bot VPN keys is based on interaction with the VPN server's management panel API. Most modern panels, such as Marzban or 3x-ui, provide an API through which users can be programmatically managed, keys generated, limits set, and statistics retrieved. The bot acts as an intermediary: it receives commands from the user in Telegram, transforms them into requests to the VPN management panel API, receives a response, and formats it for sending back to the user.
Telegram API and VPN panel API: The bot's architecture
A typical architecture includes several key components:
- Telegram Bot API: The bot is registered in Telegram via BotFather, receiving a unique token. Through this API, the bot receives messages from users and sends them replies.
- Server running the bot: This is your VPS, where a Python interpreter (or another programming language), libraries for interacting with the Telegram API and VPN panel API, and the bot's code itself are installed.
- VPN management panel: For example, Marzban or 3x-ui, installed on the same or a different VPS. It manages the Xray server and provides an HTTP API for interaction.
- Bot database: Typically SQLite, PostgreSQL, or MongoDB, where information about Telegram users, their associated VLESS keys, statuses, expiration dates, limits, and other settings is stored. This allows the bot to "remember" state and manage subscriptions.
When a user sends a command, for example, /get_key, the bot processes it, communicates with the VPN panel via its API (e.g., POST /api/user to create a new user), retrieves the VLESS config, saves its information to its database, and sends the config to the user in Telegram.
Looking for a reliable server for your projects?
VPS from $10/month and dedicated servers from $9/month with NVMe, DDoS protection, and 24/7 support.
View offers →VLESS key lifecycle management with a Telegram bot
- Request: The user sends a command to the bot (e.g.,
/start,/get_trial). - Generation: The bot, after checking permissions or payment, contacts the VPN panel API to create a new user with specified parameters (VLESS protocol, limits, expiration date).
- Issuance: The bot sends the generated VLESS key or subscription link to the user in Telegram. Information about the issued key (Telegram user ID, key ID in the panel, issue date, expiration date, traffic) is saved in the bot's database.
- Monitoring: The bot can periodically request traffic statistics for each key from the VPN panel or check the remaining validity period.
- Renewal: The user sends a renewal command. The bot updates the expiration date or limits via the VPN panel API and updates its own database.
- Revocation/Blocking: The administrator or user (if such a function is provided) can revoke or block a key. The bot sends a request to the VPN panel API to delete or deactivate the user and updates its database.
Popular Telegram bots for Marzban and 3x-ui VPN panels
Several ready-made solutions and frameworks exist for creating a VPN server management bot. Among them, projects focused on the popular Marzban and 3x-ui panels stand out, having become de facto standards for deploying multi-user VPNs based on Xray/VLESS. These panels provide a convenient web interface and a powerful API, making them an ideal foundation for automation.
Marzban Telegram bot: Advanced VPN management features
Marzban is a powerful Xray management panel that offers a wide range of functions for creating and managing VLESS, VMess, Trojan, and Shadowsocks proxies. It has a well-documented API, allowing for easy integration with Telegram bots. Several open-source projects offer ready-made solutions or templates for creating a Marzban bot. Such bots typically support:
- Automatic generation of VLESS keys with specified parameters (speed, traffic, expiration date).
- User management: creation, modification, deletion, blocking.
- Issuance of trial access with limited duration or traffic.
- Subscription renewals and limit changes.
- Retrieving traffic usage statistics for each user.
- Support for multiple protocols and ports.
- Integration with payment systems for automated VPN subscription issuance.
Example Marzban API request for user creation:
POST /api/user
Authorization: Bearer YOUR_MARZBAN_API_TOKEN
Content-Type: application/json
{
"username": "user_telegram_id",
"data_limit": 10737418240, // 10 GB in bytes
"expire": 1678886400, // Unix timestamp for expiration
"inbounds": {
"vless": {
"flow": "xtls-rprx-vision"
}
}
}
You can learn more about the panel itself in the article Marzban on VPS: Xray panel installation and multi-user setup.
3x-ui Telegram bot: Simplicity and functionality
3x-ui is another popular Xray management panel, known for its ease of installation and use. It also provides an API, though less extensive than Marzban's, but sufficient for basic VLESS key management operations. Bots for 3x-ui typically focus on the following functions:
- Generation of VLESS keys.
- Setting and modifying traffic limits.
- Setting and modifying expiration dates.
- Retrieving a list of users and their statuses.
- Deleting users.
Due to its lightweight nature and simplicity, 3x-ui is often chosen for small projects or individual use where a complex billing system is not required. A bot for 3x-ui can be implemented with minimal code, making it an excellent choice for those who want to quickly launch an automated key issuance system. Managing traffic limits and quotas for users in 3x-ui and Marzban is an important aspect, which you can read about here: User limits and quotas in 3x-ui and Marzban.
Need a dedicated server?
Compare prices from top providers. Configure and order in minutes.
How to set up and configure a Telegram bot for VPN keys on your VPS
Deploying a Telegram bot VPN keys on your own VPS is a crucial step towards full automation of VPN access management. The process involves several stages: VPS preparation, installation of necessary dependencies, deployment of the bot's code, and its launch. For example, let's consider a typical Python bot installation that interacts with the Marzban API.
Preparing your VPS and installing dependencies for the VPN bot
Before deploying the bot, ensure your VPS meets the minimum requirements (typically 1 vCPU, 512 MB RAM, 10 GB disk for the bot itself, not including the VPN server). The VPS should have a Linux-based operating system installed (e.g., Ubuntu 20.04+ or Debian 11+). You will need Python 3.8+ and pip.
# Обновление системы
sudo apt update && sudo apt upgrade -y
# Установка Python3 и pip
sudo apt install python3 python3-pip -y
# Создание виртуального окружения (рекомендуется)
mkdir ~/vpn_bot && cd ~/vpn_bot
python3 -m venv venv
source venv/bin/activate
# Установка библиотек для бота (примерно)
pip install python-telegram-bot requests SQLAlchemy
You will also need to obtain your Telegram bot's API token via BotFather and your Marzban/3x-ui panel's API token (usually generated in the panel settings).
Configuring and launching your Telegram VPN bot
After installing the dependencies, you will need to configure the bot. This is typically done via a configuration file (e.g., config.ini or config.py), where the following parameters are specified:
TELEGRAM_BOT_TOKEN: The token obtained from BotFather.MARZBAN_API_URLили3XUI_API_URL: The address of your panel API (e.g.,https://your_marzban_ip:8000/api).MARZBAN_API_TOKENили3XUI_API_TOKEN: The API token for authorization on the panel.ADMIN_TELEGRAM_ID: Your Telegram ID for receiving notifications and administering the bot.- Database settings (e.g., path to the SQLite file).
Example config.py file:
# config.py
TELEGRAM_BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
MARZBAN_API_URL = "https://your_marzban_domain_or_ip:8000/api"
MARZBAN_API_TOKEN = "YOUR_MARZBAN_JWT_TOKEN"
ADMIN_TELEGRAM_ID = [123456789, 987654321] # List of administrator IDs
DATABASE_URL = "sqlite:///bot_database.db"
After saving the configuration, you can launch the bot. For stable operation, it is recommended to use systemd for automatic startup and restart of the bot.
# Пример systemd service файла: /etc/systemd/system/vpn_bot.service
[Unit]
Description=Telegram VPN Bot
After=network.target
[Service]
User=your_user
WorkingDirectory=/home/your_user/vpn_bot
ExecStart=/home/your_user/vpn_bot/venv/bin/python /home/your_user/vpn_bot/main.py
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
# Активация и запуск сервиса
sudo systemctl daemon-reload
sudo systemctl enable vpn_bot
sudo systemctl start vpn_bot
sudo systemctl status vpn_bot
Telegram VPN bot features: From trial access to key revocation
A modern Telegram bot VPN keys boasts rich functionality that allows for full automation of VPN access management. This includes not just key issuance, but also a full spectrum of capabilities for flexible subscription control.
Managing VPN subscriptions: Trials, renewals, and data limits
One of the most sought-after features is the ability to provide trial access. This allows new users to test the VPN service before committing to a full subscription. The bot can automatically issue VLESS keys with a limited validity period (e.g., 3 days) or a traffic limit (e.g., 1 GB). Upon expiration of the trial period, the bot can notify the user and offer them to purchase a full subscription.
- Trial access issuance: The
/trialcommand generates a key for 1-3 days with a 1-5 GB limit. - Subscription renewal: Users can renew their access by selecting a tariff plan through the bot. The bot updates the expiration date and traffic limits for the corresponding key via the panel API.
- Setting traffic limits: Individual traffic limits (e.g., 50 GB/month) and speed limits can be set for each user. The bot will monitor consumption and automatically block access or reduce speed upon reaching the limit.
- Setting time limits: In addition to traffic, a subscription validity period can be set (e.g., 30 days). The bot automatically deactivates the key upon expiration.
This flexibility allows the administrator to create diverse tariff plans and efficiently manage server resources.
Revoking VPN keys and managing active sessions
The ability to revoke a key or block user access is critically important for security and control. The bot should provide the administrator with a convenient interface to perform these operations:
- Key revocation: The administrator can send a command to the bot (e.g.,
/revoke user_id) to immediately deactivate a user's VLESS key. This is useful if a user violates terms of service or a subscription has been canceled. - Blocking/unblocking: Temporary blocking of access without completely deleting the key. For example, if a user exceeds their limit, they can be temporarily blocked until their subscription is renewed.
- Viewing active sessions: Some bots can display information about active connections to the VPN server for each key, allowing the administrator to see who is currently using the VPN.
Additionally, the bot can be configured to automatically notify users about impending subscription expiration or traffic exhaustion, which significantly improves the user experience and reduces the number of inquiries to the administrator.
For a deeper understanding of how to automate key issuance and management, the article on self-hosted VLESS subscription on a VPS, which covers auto-updating configs, may be helpful.
Optimal VPS resources for a VPN management bot
One significant advantage of running a VPN server management bot is its low resource consumption. In most cases, the bot can comfortably coexist on the same VPS as the VPN server itself without noticeably impacting its performance. This allows for optimizing hosting costs by using a single server for multiple tasks.
Why can a VPN bot run on the same server as the VPN itself?
Telegram bots, especially those written in Python, are lightweight applications. They spend most of their time in an idle state, consuming minimal CPU and RAM resources. Bot activity occurs only when processing user requests or performing periodic tasks (e.g., checking expiring subscriptions). These operations typically take fractions of a second and do not create significant load. The VPN server itself (Xray) is a much more resource-intensive component, consuming CPU and network traffic depending on the number of active users and their activity.
Key reasons for the bot's low resource consumption:
- Event-driven architecture: The bot activates only upon receiving a message or on a timer.
- Minimal disk operations: The bot's database (often SQLite) is small and infrequently updated.
- Low CPU load: Processing commands and API requests to panels does not require intensive computations.
- Negligible RAM consumption: For most bots, 50-100 MB of RAM is sufficient.
Recommended VPS specs for a VPN server with a bot
For 50 concurrent users, 4 vCPU, 8 GB RAM, and an 80 GB NVMe disk are sufficient.
| VPN Users | vCPU | RAM | Disk | Bandwidth | Price (approx.) |
|---|---|---|---|---|---|
| up to 10 | 1-2 | 1-2 GB | 20-40 GB NVMe/SSD | 100 Mbps | $5-10/мес |
| 10-25 | 2 | 2-4 GB | 40-60 GB NVMe/SSD | 250 Mbps | $10-20/мес |
| 25-50 | 4 | 4-8 GB | 60-80 GB NVMe/SSD | 500 Mbps | $20-40/мес |
| 50-100 | 4-6 | 8-16 GB | 80-160 GB NVMe/SSD | 1 Gbps | $40-80/мес |
| 100+ | 6-8+ | 16-32+ GB | 160+ GB NVMe | 1-10 Gbps | $80+/мес |
As seen in the table, even for a significant number of VPN users, the VPS requirements remain quite moderate. A bot running on Python will occupy only a small fraction of these resources, making its co-location with the VPN server an economically advantageous solution. It is important to choose a VPS with a fast disk (NVMe) and sufficient RAM for comfortable operation of the VPN and management panel.
Need a dedicated server?
Compare prices from top providers. Configure and order in minutes.
Security and data storage: Backing up your VPN bot's database
Data security and reliable operation of a Telegram bot for issuing VPN keys are critically important aspects. Improper storage of confidential information or lack of backups can lead to user data leaks, loss of subscription information, or complete service inoperability.
Protecting API tokens and sensitive data
The most sensitive data are the Telegram bot's API token and the VPN management panel's API token (Marzban/3x-ui). These tokens grant full control over the bot and the VPN server, respectively. Follow these recommendations:
- Do not store tokens publicly: Never commit tokens to public Git repositories. Use environment variables or secured configuration files (e.g., a
.envfile that is ignored by Git). - Restrict access to configuration files: Ensure that only the user under whom the bot is running has read permissions for the configuration file.
- Use HTTPS for the panel API: If the VPN management panel is accessible via HTTP, configure Nginx or another reverse proxy to use HTTPS to protect data transfer between the bot and the panel.
- Configure a firewall: Restrict access to the VPN management panel's API ports only from the IP address of your VPS where the bot is running.
- Regularly update dependencies: Timely updates of Python, libraries, and the bot's code itself will help patch known vulnerabilities.
Bot state management and database backup strategies
The bot stores important information about users, their subscriptions, expiration dates, and consumed traffic in its database. Losing this database means losing all subscription data and the need to restore everything manually. Therefore, regular backups of the bot's database are mandatory.
If the bot uses SQLite (the most common option for small projects), the database is stored in a single file (e.g., bot_database.db). To back up, simply copy this file to a secure location.
# Пример скрипта для бэкапа SQLite базы данных
#!/bin/bash
DB_PATH="/home/your_user/vpn_bot/bot_database.db"
BACKUP_DIR="/home/your_user/backups/vpn_bot_db"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${BACKUP_DIR}/bot_database_${TIMESTAMP}.db"
mkdir -p $BACKUP_DIR
cp $DB_PATH $BACKUP_FILE
# Удаление старых бэкапов (оставить 7 последних)
find $BACKUP_DIR -name "bot_database_*.db" -mtime +7 -delete
echo "Backup created: $BACKUP_FILE"
This script can be configured to run on a schedule via cron (e.g., daily at 3 AM).
# Добавление задачи в crontab
crontab -e
# Добавить строку:
0 3 * * * /bin/bash /home/your_user/vpn_bot/backup_script.sh >> /var/log/vpn_bot_backup.log 2>&1
For more reliable storage, it is recommended to use remote storage (S3-compatible services, Google Drive, Dropbox) or other VPS instances to store backups. You can learn more about backups in the article Automated VPN config backup from a VPS.
Frequently Asked Questions about Telegram VPN Bots
Here we've compiled answers to the most frequent questions regarding the use of a Telegram bot for issuing VLESS keys.
Can one Telegram bot manage multiple VPN servers?
Yes, it is entirely possible. If the bot is designed with multi-server architecture support, it can manage several Marzban or 3x-ui panels located on different VPS instances. This is convenient for load balancing or providing access to VPN servers in various geographical locations. This usually requires additional settings in the bot's configuration, where API tokens and addresses of all managed panels are specified. Some projects allow binding a user to a specific server or automatically selecting a less loaded one.
What programming languages are used for VPN bots?
The most popular language for developing Telegram bots is Python, thanks to its simplicity, extensive libraries (such as python-telegram-bot and requests), and large community. However, bots can also be written in other languages, such as Node.js (with libraries like node-telegram-bot-api), Go, PHP, or Ruby. The choice of language often depends on the developer's preferences and the specifics of the VPN panels used, as well as the availability of ready-made SDKs for their APIs.
Does a VPN bot require a dedicated IP address?
A dedicated IP address is not required for the Telegram bot itself to function. The bot interacts with the Telegram API via outbound HTTPS connections, and with the VPN panel—also via outbound connections or an internal IP if they are on the same VPS. However, for the VPN server itself (Marzban, 3x-ui, Xray) to operate, a dedicated public IP address on your VPS is a mandatory condition to ensure the VPN service's accessibility from the internet. Without a public IP, users will not be able to connect to your VPN.
How much does a VPS cost for a VPN and a bot?
The cost of a VPS for running a VPN server and a bot can range from $5 to $80+ per month, depending on the number of users and required resources. For a small number of users (up to 10-15 people), a VPS with 1-2 vCPU, 1-2 GB RAM, and a 20-40 GB NVMe disk is sufficient, costing approximately $5-10/month. For 50-100 users, a more powerful server with 4-6 vCPU, 8-16 GB RAM, and an 80+ GB NVMe disk will be needed, with costs potentially reaching $40-80/month. The bot itself barely increases the total cost, as its requirements are minimal.
Conclusion
Utilizing a Telegram bot for issuing VLESS keys on your own VPS is not just a convenience, but an effective tool for automating and scaling VPN access management. It significantly reduces administration time, simplifies the process for end-users, and provides centralized control over subscriptions. We recommend implementing such a solution, especially if you manage access for more than 5-10 users, to optimize resources and enhance the overall efficiency of your VPN service.
Ready to choose a server?
VPS and dedicated servers in 72+ countries with instant activation and full root access.
Get started now →