Skip to content

A production-ready Telegram bot for managing Outline VPN access keys with user approval workflow and automatic expiry management.

Notifications You must be signed in to change notification settings

Mhr1375/vpn-bot

Repository files navigation

VPN Bot - Telegram Outline VPN Manager

A production-ready Telegram bot for managing Outline VPN access keys with user approval workflow and automatic expiry management.

Features

  • 🔐 Two-tier user system: Admin approval required for new users
  • 🖥️ Multi-server support: Manage multiple Outline VPN servers
  • Automatic expiry: Scheduled cleanup of expired keys
  • 📊 Traffic quotas: 30GB, 50GB, or 100GB options
  • 📅 Validity periods: 1 week or 1 month
  • 📝 Comprehensive audit logging: Track all user and admin actions
  • 🚀 Production ready: Docker support, health checks, proper error handling

Architecture

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Telegram Bot  │    │  Outline Servers │    │    Database     │
│                 │    │                 │    │                 │
│  • User mgmt    │◄──►│  • Key creation │    │  • Users        │
│  • Commands     │    │  • Key deletion │    │  • Servers      │
│  • Workflows    │    │  • Data limits  │    │  • Access Keys  │
│                 │    │                 │    │  • Audit Logs   │
└─────────────────┘    └─────────────────┘    └─────────────────┘
         ▲                                              ▲
         │                                              │
         ▼                                              ▼
┌─────────────────┐                          ┌─────────────────┐
│   Scheduler     │                          │  Health Check   │
│                 │                          │                 │
│  • Auto expiry  │                          │  • Status API   │
│  • Notifications│                          │  • Statistics   │
│  • Cleanup      │                          │  • Monitoring   │
└─────────────────┘                          └─────────────────┘

User Roles

Admin

  • Single admin user (configured via ADMIN_TG_ID)
  • Approve/block users
  • Add/remove Outline servers
  • View server list and statistics

Sales Users

  • Must be approved by admin before access
  • Create VPN connections with custom settings
  • View their active/expired connections
  • Receive notifications about expiry

Commands

User Commands

  • /start - Register and get started
  • /new - Create a new VPN connection
  • /mykeys - View your VPN connections
  • /help - Show help information

Admin Commands

  • /approve <user_id> - Approve a pending user
  • /block <user_id> - Block a user
  • /addserver - Add a new VPN server (interactive)
  • /removeserver <server_id> - Remove a server
  • /servers - List all servers

Quick Start

Prerequisites

1. Clone and Setup

git clone <repository-url>
cd VPN_BOT

# Copy environment template
cp env.example .env

# Edit configuration
nano .env

2. Configure Environment

Edit .env file:

BOT_TOKEN=your_telegram_bot_token_here
ADMIN_TG_ID=your_telegram_user_id
DB_URL=sqlite+aiosqlite:///bot.db
TZ=UTC
LOG_LEVEL=INFO
HEALTH_CHECK_PORT=8000

3. Install Dependencies

# Using pip
pip install -r requirements.txt

# Or using poetry (if you prefer)
poetry install

4. Run the Bot

python run.py

Docker Deployment

Development (SQLite)

# Build and run with SQLite
docker-compose up --build

Production (PostgreSQL)

  1. Update .env for PostgreSQL:
BOT_TOKEN=your_telegram_bot_token_here
ADMIN_TG_ID=your_telegram_user_id
DB_URL=postgresql+asyncpg://vpn_user:your_password@postgres:5432/vpn_bot
POSTGRES_PASSWORD=your_secure_password
TZ=UTC
LOG_LEVEL=INFO
HEALTH_CHECK_PORT=8000
  1. Run with PostgreSQL:
docker-compose up --build

Configuration

Environment Variables

Variable Description Default Required
BOT_TOKEN Telegram bot token from @BotFather -
ADMIN_TG_ID Telegram user ID of the admin -
DB_URL Database connection URL sqlite+aiosqlite:///bot.db
TZ Timezone for timestamps UTC
LOG_LEVEL Logging level (DEBUG/INFO/WARNING/ERROR) INFO
HEALTH_CHECK_PORT Port for health check API 8000

Database URLs

# SQLite (development)
DB_URL=sqlite+aiosqlite:///bot.db

# PostgreSQL (production)
DB_URL=postgresql+asyncpg://user:password@host:port/database

# PostgreSQL with Docker Compose
DB_URL=postgresql+asyncpg://vpn_user:password@postgres:5432/vpn_bot

Usage Workflow

1. Initial Setup (Admin)

  1. Start the bot and verify admin access
  2. Add Outline servers using /addserver
  3. Provide server details:
    • Name: Human-readable server name
    • API URL: Outline server API endpoint
    • Certificate SHA256: Server certificate fingerprint

2. User Registration

  1. New users start with /start
  2. Bot automatically notifies admin with approve/block buttons
  3. Admin approves or blocks users
  4. Approved users can create VPN connections

3. VPN Creation Process

  1. User runs /new command
  2. Interactive wizard:
    • Choose server from available list
    • Select validity period (1 week/1 month)
    • Pick traffic quota (30GB/50GB/100GB)
  3. Bot creates Outline key and provides connection URL
  4. User copies URL to Outline app

4. Key Management

  • Users can view their keys with /mykeys
  • Scheduler automatically disables expired keys
  • Users receive notifications about expiry
  • All actions are logged for audit purposes

Monitoring

Health Check API

The bot exposes a health check API on port 8000:

# Check bot health
curl http://localhost:8000/health

# Response
{
  "status": "healthy",
  "scheduler": "running",
  "statistics": {
    "users": {"total": 10, "pending": 2, "sales": 7, "blocked": 1},
    "servers": {"total": 3, "active": 3, "inactive": 0},
    "keys": {"total": 25, "active": 15, "expired": 5, "disabled": 5},
    "recent_activity": 12,
    "timestamp": "2024-01-01T12:00:00"
  }
}

Logs

# View logs in Docker
docker-compose logs -f vpn-bot

# Log files (if running locally)
tail -f bot.log

Database Schema

Users Table

  • id (BigInteger, PK) - Telegram user ID
  • username, first_name, last_name - User info
  • role - pending/sales/admin/blocked
  • created_at, updated_at - Timestamps

Servers Table

  • id (Integer, PK) - Auto-increment ID
  • name - Human-readable name
  • api_url - Outline API endpoint
  • cert_sha256 - Certificate fingerprint
  • is_active - Boolean status

Access Keys Table

  • id (Integer, PK) - Auto-increment ID
  • outline_key_id - ID from Outline API
  • owner_id - Foreign key to Users
  • server_id - Foreign key to Servers
  • access_url - ss:// connection URL
  • traffic_quota - 30GB/50GB/100GB
  • validity_period - 1week/1month
  • expires_at - Expiration timestamp
  • disabled_at - Disable timestamp (if disabled)
  • disabled_reason - Reason for disabling

Audit Logs Table

  • id (Integer, PK) - Auto-increment ID
  • user_id - Who performed the action
  • action - What action was performed
  • target_type, target_id - What was acted upon
  • details - Additional context
  • created_at - When the action occurred

Security Considerations

  1. Environment Variables: Never commit .env to version control
  2. Certificate Verification: Implement proper cert pinning for production
  3. Database Access: Use strong passwords and restrict network access
  4. Audit Logging: All actions are logged for accountability
  5. User Validation: Admin approval required for all new users

Troubleshooting

Common Issues

  1. Bot not responding

    • Check bot token validity
    • Verify network connectivity
    • Check logs for errors
  2. Database errors

    • Ensure database is accessible
    • Check connection string format
    • Verify credentials
  3. Outline API errors

    • Verify server URLs are accessible
    • Check certificate fingerprints
    • Ensure API endpoints are correct
  4. Scheduler not working

    • Check scheduler logs
    • Verify timezone configuration
    • Ensure bot has notification permissions

Debug Mode

Enable debug logging:

LOG_LEVEL=DEBUG

Manual Database Operations

# Connect to PostgreSQL
docker exec -it vpn-bot-postgres psql -U vpn_user -d vpn_bot

# View tables
\dt

# Check users
SELECT id, username, role, created_at FROM users;

# Check active keys
SELECT ak.id, u.username, s.name, ak.expires_at 
FROM access_keys ak 
JOIN users u ON ak.owner_id = u.id 
JOIN servers s ON ak.server_id = s.id 
WHERE ak.disabled_at IS NULL;

Development

Project Structure

VPN_BOT/
├── bot/
│   ├── __init__.py
│   ├── main.py              # Entry point
│   ├── config.py            # Configuration
│   ├── database.py          # Database setup
│   ├── models.py            # SQLAlchemy models
│   ├── outline.py           # Outline API client
│   ├── scheduler.py         # Background tasks
│   ├── utils.py             # Utilities and decorators
│   ├── health.py            # Health check API
│   └── handlers/
│       ├── __init__.py
│       ├── admin.py         # Admin commands
│       └── sales.py         # User commands
├── requirements.txt         # Python dependencies
├── Dockerfile              # Container definition
├── docker-compose.yml      # Multi-container setup
├── run.py                  # Simple entry point
├── env.example             # Environment template
├── README.md               # This file
└── .gitignore              # Git ignore rules

Running Tests

# Install dev dependencies
pip install pytest pytest-asyncio

# Run tests
pytest tests/

# Run with coverage
pytest --cov=bot tests/

Code Quality

# Format code
black bot/

# Lint code
ruff check bot/

# Type checking
mypy bot/

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make changes with proper tests
  4. Ensure code quality (black, ruff, mypy)
  5. Submit a pull request

License

[Add your license here]

Support

For issues and questions:

  1. Check the troubleshooting section
  2. Review logs for error messages
  3. Open an issue with detailed information

Built with ❤️ for secure VPN management

About

A production-ready Telegram bot for managing Outline VPN access keys with user approval workflow and automatic expiry management.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published