Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Required
BOT_TOKEN=your_telegram_bot_token_here
SUPER_ADMIN_ID=your_telegram_id_here

# Optional
PAYMENT_CARD=your_card_number
FORCE_CHANNEL=@your_channel
WEB_PORT=10674
BASE_URL=http://your-server:10674
12 changes: 12 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
__pycache__/
*.pyc
*.pyo
.env
config.json
bot.db
*.sqlite
uploads/
logs/
backups/
temp/
.yt-dlp/
79 changes: 79 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Telegram Bot v4.0 — Modular Architecture

A feature-rich Telegram bot with VPN config distribution, media downloading, proxy service, file-to-link, VIP subscriptions, and full admin panel.

## Features

- **VPN Config Distribution** — Free and VIP tiers with cooldown and usage tracking
- **Media Download** — YouTube, Instagram, TikTok, Twitter video/audio download with queue system
- **Proxy Service** — Aggregates free HTTP/HTTPS/SOCKS4/SOCKS5 proxies from multiple sources, auto-refreshes, REST API endpoint, live proxy checker
- **Speed Test** — One-click download speed test using Cloudflare and Hetzner endpoints
- **File to Link** — Upload any file, get a direct download link (7-day expiry)
- **VIP System** — Silver/Gold/Diamond plans with payment receipts and wallet purchases
- **Wallet** — Balance management, referral bonuses, VIP purchases
- **Referral System** — Invite friends, earn wallet credit
- **Admin Panel** — User management, broadcast, stats, config management, discount codes, wallet charge, weekly analytics dashboard
- **HTTP Streaming Server** — Direct file downloads via HTTP, proxy list API

## Project Structure

```
bot/
├── __init__.py # Package init
├── config.py # Configuration (env vars, config.json, constants)
├── database.py # Async SQLite database layer (aiosqlite)
├── helpers.py # Utilities (formatting, QR, rate limiting, validation)
├── keyboards.py # Inline keyboard builders
├── decorators.py # Guard decorator (auth, rate limit, ban check)
├── server.py # HTTP streaming server + proxy API
├── main.py # App entry point, handler registration
└── handlers/
├── start.py # /start command
├── main_menu.py # Profile, help, referral, claim, VIP, wallet
├── youtube.py # Media download (YouTube, Instagram, TikTok)
├── file.py # File-to-link
├── proxy.py # Proxy service (fetch, check, list, manage)
└── admin.py # Admin panel (configs, users, broadcast, stats)
```

## Setup

1. Clone the repo
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Copy `.env.example` to `.env` and fill in your values:
```bash
cp .env.example .env
```
4. Run:
```bash
python run.py
```

## Configuration

Edit `config.json` (auto-generated on first run) to customize:
- VIP plan pricing and durations
- Download limits and queue sizes
- Rate limiting
- Proxy update intervals
- Referral bonuses

## Proxy API

The bot exposes a REST API at `/api/proxies` for programmatic proxy access:
```
GET /api/proxies?protocol=http&limit=50
```

## Architecture Highlights

- **Async database** via `aiosqlite` — non-blocking DB operations
- **Persistent DB connection** with WAL mode and 8 MB cache
- **Separated concerns** — each module handles one domain
- **Guard decorator** — centralized auth, rate limiting, ban checking
- **Queue system** for media downloads with progress tracking
- **Concurrent updates** enabled for better throughput
- **Periodic jobs** — proxy refresh, daily reports, file cleanup
6 changes: 6 additions & 0 deletions bot/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
"""
Telegram Bot - Restructured v4.0
Modular architecture with separated DB, proxy support, and optimized performance.
"""

__version__ = "4.0.0"
138 changes: 138 additions & 0 deletions bot/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"""
Centralized configuration loader.
Reads from .env and config.json, merges defaults, and exposes typed constants.
"""

import os
import sys
import json
from pathlib import Path

from dotenv import load_dotenv

load_dotenv()

# ── Telegram ──────────────────────────────────────
BOT_TOKEN: str = os.getenv("BOT_TOKEN", "")
SUPER_ADMIN_ID: int = int(os.getenv("SUPER_ADMIN_ID", "0"))
PAYMENT_CARD: str = os.getenv("PAYMENT_CARD", "")
FORCE_CHANNEL: str = os.getenv("FORCE_CHANNEL", "")

if not BOT_TOKEN:
print("BOT_TOKEN is not set in .env")
sys.exit(1)

# ── Web / streaming server ────────────────────────
WEB_SERVER_HOST: str = "0.0.0.0"
WEB_SERVER_PORT: int = int(os.getenv("WEB_PORT", "10674"))
BASE_DOWNLOAD_URL: str = os.getenv("BASE_URL", f"http://localhost:{WEB_SERVER_PORT}")
COOKIE_FILE: str = os.path.join(os.path.expanduser("~"), ".yt-dlp", "cookies.txt")

# ── Directories ───────────────────────────────────
for _d in ("uploads", "logs", "backups", "temp"):
Path(_d).mkdir(exist_ok=True)
Path(COOKIE_FILE).parent.mkdir(exist_ok=True)

# ── Config JSON ───────────────────────────────────
DEFAULT_CONFIG: dict = {
"database": "bot.db",
"claim_cooldown_hours": 6,
"max_yt_size_mb": 500,
"max_file_size_mb": 2000,
"yt_sleep_interval": 2,
"max_queue_size": 50,
"referral_bonus": 5000,
"enable_qr_code": True,
"welcome_message": "به ربات خوش اومدی!",
"rate_limit_per_minute": 25,
"max_broadcast_delay": 0.05,
"daily_report_hour": 8,
"proxy_update_interval_minutes": 30,
"proxy_check_timeout": 8,
"proxy_max_results": 30,
"vip_levels": {
"silver": {
"name": "Silver",
"price": 50000,
"days": 30,
"max_yt_quality": "720",
"max_configs": 3,
"wallet_bonus": 0,
},
"gold": {
"name": "Gold",
"price": 120000,
"days": 90,
"max_yt_quality": "1080",
"max_configs": 5,
"wallet_bonus": 10000,
},
"diamond": {
"name": "Diamond",
"price": 250000,
"days": 180,
"max_yt_quality": "1080",
"max_configs": 10,
"wallet_bonus": 30000,
},
},
"discount_codes": {},
}

CONFIG_PATH = Path("config.json")
if not CONFIG_PATH.exists():
CONFIG_PATH.write_text(json.dumps(DEFAULT_CONFIG, indent=4, ensure_ascii=False), encoding="utf-8")

with open(CONFIG_PATH, "r", encoding="utf-8") as _f:
CONFIG: dict = json.load(_f)

for _k, _v in DEFAULT_CONFIG.items():
CONFIG.setdefault(_k, _v)

# ── Typed shortcuts ───────────────────────────────
DB_NAME: str = CONFIG["database"]
CLAIM_COOLDOWN: int = CONFIG["claim_cooldown_hours"]
MAX_YT_SIZE_MB: int = CONFIG["max_yt_size_mb"]
MAX_FILE_SIZE: int = CONFIG["max_file_size_mb"]
YT_SLEEP: int = CONFIG["yt_sleep_interval"]
MAX_QUEUE: int = CONFIG["max_queue_size"]
REFERRAL_BONUS: int = CONFIG["referral_bonus"]
ENABLE_QR: bool = CONFIG["enable_qr_code"]
WELCOME_MSG: str = CONFIG["welcome_message"]
VIP_LEVELS: dict = CONFIG["vip_levels"]
RATE_LIMIT: int = CONFIG.get("rate_limit_per_minute", 25)
DISCOUNT_CODES: dict = CONFIG.get("discount_codes", {})
PROXY_UPDATE_INTERVAL: int = CONFIG.get("proxy_update_interval_minutes", 30)
PROXY_CHECK_TIMEOUT: int = CONFIG.get("proxy_check_timeout", 8)
PROXY_MAX_RESULTS: int = CONFIG.get("proxy_max_results", 30)

VALID_PERMS = frozenset({
"can_manage_configs",
"can_manage_payments",
"can_broadcast",
"can_block_users",
"can_give_vip",
})

# ── Conversation states ───────────────────────────
(
STATE_NONE,
STATE_WAITING_RECEIPT,
STATE_ADDING_CONFIG,
STATE_DELETING_CONFIG,
STATE_BROADCASTING,
STATE_WAITING_FILE,
STATE_WAITING_YT_URL,
STATE_MANAGE_ADMIN,
STATE_SET_COOKIE,
STATE_WAITING_CONFIG_TEXT,
STATE_SEARCHING_USER,
STATE_GIVE_VIP,
STATE_BAN_USER,
STATE_UNBAN_USER,
STATE_WAITING_DISCOUNT,
STATE_ADD_DISCOUNT,
STATE_WALLET_CHARGE,
STATE_CHECKING_PROXY,
STATE_ADMIN_WALLET_CHARGE,
) = range(19)
Loading