Skip to main content

andro-cfw

PyPI Python License: MIT Languages

English | فارسی


🎯 What does this library do?

In countries like Iran where api.telegram.org is network-filtered, developers need a VPN or a foreign server to run their Telegram bots.

andro-cfw solves this with a simple trick: it deploys a Cloudflare Worker as a reverse proxy between your bot and Telegram:

Your Bot (Python / JS / PHP)  ←→  Cloudflare Worker (unfiltered)  ←→  api.telegram.org

Cloudflare's edge network is reachable from restricted regions even when Telegram's API is not, so your bot talks to the Worker and the Worker talks to Telegram.


✨ Key Features

  • 🔒 Zero VPN Required — No VPN needed on your dev machine, server, or during webhook setup.
  • ☁️ 100% Serverless Cloud Bots — Run real Telegram bots 24/7 directly inside Cloudflare Workers (0 laptop or server required).
  • 🐍 1-Line Auto-Patcher (andro_cfw.patch()) — Universal auto-detection and patching for telebot, ptb, aiogram, pyrogram, and hydrogram.
  • 🔀 Multi-Account Load Balancing — Pool several Cloudflare accounts' free-tier quotas (100k req/day per account) with automatic failover and daily auto-resets.
  • Snippet & Webhook Generator (andro-cfw serverless) — 1-command deployment of 100% serverless bots with interactive prompts.
  • 🔍 Live Latency & Health Checks (andro-cfw check) — Test live connection speed and Keep-Alive ping latency across deployed workers.
  • 📊 Live Browser Usage Dashboard (New in v3.0.1) — Just open your worker URL in a browser: a beautiful real-time panel shows today's request count, remaining quota, and a countdown to the next daily reset — zero configuration required.
  • 🔐 Encrypted Session Storage — Local session files are encrypted with Fernet (AES-128 + HMAC).

📦 Installation & Setup

python -m venv .venv
source .venv/bin/activate       # Windows: .venv\Scripts\activate
pip install andro-cfw

Registered Executable / PATH Setup

If running andro-cfw in your terminal gives command not found, register it safely into your User PATH:

python -m andro_cfw.cli setup-path

📖 Complete Guide: 100% Serverless Telegram Bots on Cloudflare

You can run your Telegram bot 100% serverless on Cloudflare Edge with 24/7 uptime, ~5ms response latency, and zero server costs (using Cloudflare's free 100,000 requests/day tier).


Method A: Zero-Code 1-Command Serverless Bot (andro-cfw serverless)

Deploy a fully functional 24/7 serverless bot in under 30 seconds:

  1. Run the deployment command:
    andro-cfw serverless
    
  2. Enter your Telegram Bot Token from @BotFather when prompted:
    [andro-cfw] Enter your Telegram Bot Token from @BotFather: 7123456789:AAFgX...
    
  3. Done! andro-cfw will deploy the Cloudflare Worker, configure the Webhook, and register it with Telegram automatically — with zero VPN required.

Built-in Serverless Commands:

  • /start or /help — Welcome card with edge performance & latency metrics.
  • /ping — Responds with pong 🏓 (< 5ms Edge Latency).
  • /status — Displays live Cloudflare Worker status & health.
  • /echo <text> — Echoes back any text message.

Method B: Full Custom TypeScript / JavaScript Worker Bot

If you want to build a full custom serverless bot with interactive buttons, database calls, or custom logic in JavaScript/TypeScript:

1. worker.ts Code:

export interface Env {
  BOT_TOKEN?: string;
}

const TELEGRAM_ORIGIN = "https://api.telegram.org";

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);

    // 1. Webhook Update Handler (POST /webhook)
    if (request.method === "POST" && url.pathname.includes("/webhook")) {
      try {
        // Extract token from query parameter or Env
        const token = url.searchParams.get("token") || env.BOT_TOKEN;
        const update = (await request.json()) as any;

        if (update && update.message && update.message.text && token) {
          const chatId = update.message.chat.id;
          const text = update.message.text.trim();

          let replyText = "";

          // Custom Bot Command Logic
          if (text === "/start") {
            replyText = "👋 Hello! I am running 100% Serverless on Cloudflare Edge!";
          } else if (text === "/ping") {
            replyText = "🏓 Pong from Cloudflare Worker!";
          } else if (text.startsWith("/echo ")) {
            replyText = `📢 You said: ${text.slice(6)}`;
          } else {
            replyText = `🤖 Received your message: "${text}"`;
          }

          // Reply back to Telegram
          const replyUrl = `${TELEGRAM_ORIGIN}/bot${token}/sendMessage`;
          await fetch(replyUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              chat_id: chatId,
              text: replyText,
              parse_mode: "Markdown",
            }),
          });
        }
      } catch (err) {
        console.error("Webhook processing error:", err);
      }
      return new Response("OK", { status: 200 });
    }

    // 2. Reverse Proxy Pass-through for local/external bots
    const targetUrl = TELEGRAM_ORIGIN + url.pathname + url.search;
    return fetch(targetUrl, {
      method: request.method,
      headers: request.headers,
      body: ["GET", "HEAD"].includes(request.method) ? undefined : request.body,
      // @ts-ignore
      duplex: "half",
    });
  },
};

Method C: Python Bot via 1-Line Patcher (andro_cfw.patch())

If you prefer writing your bot logic in Python using telebot, pyrogram, aiogram, or python-telegram-bot:

import telebot
import andro_cfw

# 1-Line Auto-Patcher: Routes 100% of Telegram API calls through Cloudflare Worker
session = andro_cfw.patch()

bot = telebot.TeleBot("YOUR_BOT_TOKEN_FROM_BOTFATHER")

@bot.message_handler(commands=["start", "help"])
def send_welcome(message):
    bot.reply_to(
        message,
        "🤖 **Hello from behind the filter!**\n\n"
        f"🌐 **Worker URL**: `{session.worker_url}`\n"
        "🔒 **Status**: Unfiltered & Running Smoothly!"
    )

if __name__ == "__main__":
    print(f"🚀 Bot starting behind Cloudflare Worker ({session.worker_url})...")
    bot.infinity_polling(timeout=20, long_polling_timeout=20)

Method D: PHP / External Webhook Backend Mode (FORWARD_WEBHOOK_URL)

If you have an existing PHP, Node.js, Python, or Go webhook bot hosted on your own server or cPanel, you can use Cloudflare Worker as a Webhook Filter Bypass:

  1. In your Worker's wrangler.toml or Cloudflare Dashboard environment variables, set:
    [vars]
    FORWARD_WEBHOOK_URL = "https://your-server.com/my_bot_webhook.php"
    
  2. Whenever Telegram sends a Webhook update to your Cloudflare Worker, Cloudflare automatically strips the network filter and forwards the payload straight to your PHP backend!

🐍 Framework Snippet Generator (andro-cfw snippet)

Generate copy-paste ready starter code for your framework:

# Print starter snippet for Telebot
andro-cfw snippet -f telebot

# Generate ready-to-run bot.py for Aiogram / Pyrogram / PTB / Hydrogram
andro-cfw snippet -f aiogram -o bot.py
andro-cfw snippet -f pyrogram -o bot.py
andro-cfw snippet -f hydrogram -o bot.py
andro-cfw snippet -f ptb -o bot.py

🔍 Worker Health & Latency Check (andro-cfw check)

Test live network connectivity, HTTP response code, and Keep-Alive latency (ms) across all deployed workers:

andro-cfw check

Output example:

  Worker [0]: account-1
    URL     : https://andro-cfw-12345678.workers.dev
    Status  : HTTP 200 OK (59.1 ms)
    Quota   : [available]

📊 Live Usage Dashboard (New in v3.0.1)

Every worker deployed by andro-cfw now doubles as its own monitoring panel. Just open the worker URL (the same https://andro-cfw-xxxxxxxx.workers.dev link printed by andro-cfw init) in any web browser:

  • Today's request count vs. the Cloudflare Workers Free plan's 100,000 requests/day quota.
  • Remaining quota and a live percentage-used progress bar (green → amber → red as you approach the limit).
  • Countdown timer until the quota automatically resets at 00:00 UTC.
  • Zero setup: a small Cloudflare Workers KV namespace (<worker-name>-usage) is automatically created for you during andro-cfw init / add-account / serverless and bound to the worker.

Programmatic tools (like andro-cfw check, curl, or uptime monitors) still get the original lightweight plain-text 200 OK response — the rich dashboard only renders for real browser visits (detected via the Accept: text/html header).

Note: usage tracking is best-effort. If KV provisioning isn't available on your Cloudflare account (e.g. certain restricted/free-tier edge cases) the worker still deploys and works exactly as before — the dashboard just falls back to a "tracking unavailable" placeholder instead of live numbers.


📋 CLI Reference

Command Description
andro-cfw init Log into Cloudflare and deploy a single proxy worker.
andro-cfw init --accounts 3 Log into 3 Cloudflare accounts and deploy a load-balanced worker pool.
andro-cfw serverless Deploy a 100% serverless 24/7 Telegram bot to Cloudflare Edge.
andro-cfw add-account Add one more Cloudflare account/worker to an existing session.
andro-cfw snippet -f telebot Generate ready-to-run Python code for Telebot, PTB, Aiogram, Pyrogram, or Hydrogram.
andro-cfw check Test live network connectivity and ping response times of deployed worker(s).
andro-cfw status Show the worker(s) saved for this project, and per-account health.
andro-cfw setup-path Safely add andro-cfw executable directory to User PATH.
andro-cfw remove Delete the deployed worker(s) and local cfw.session.

🔐 Security Notes

  • cfw.session is encrypted with Fernet (AES-128-CBC + HMAC). Key stored in ~/.andro_cfw/key.
  • Add cfw.session to .gitignore.
  • The generated worker is a pure pass-through proxy: it does not log, store, or inspect bot tokens or updates.

📄 License

MIT

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

andro_cfw-3.0.2.tar.gz (45.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

andro_cfw-3.0.2-py3-none-any.whl (38.1 kB view details)

Uploaded Python 3

File details

Details for the file andro_cfw-3.0.2.tar.gz.

File metadata

  • Download URL: andro_cfw-3.0.2.tar.gz
  • Upload date:
  • Size: 45.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for andro_cfw-3.0.2.tar.gz
Algorithm Hash digest
SHA256 c81013bcd455c29eff2bbca02225bb09834c815888a189b69b7275264afa164c
MD5 91277317dbd242ad91be64e8f6d78282
BLAKE2b-256 48f9bcc7980655cde714c1d12f8eb3ece6bf489bce0713e607a0f632f252420b

See more details on using hashes here.

Provenance

The following attestation bundles were made for andro_cfw-3.0.2.tar.gz:

Publisher: release-and-changelog.yml on Andromeda-Collective/andro-cfw

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file andro_cfw-3.0.2-py3-none-any.whl.

File metadata

  • Download URL: andro_cfw-3.0.2-py3-none-any.whl
  • Upload date:
  • Size: 38.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for andro_cfw-3.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 9e0f2bafcb5e6410f57c84028f5acd3c69d06b45b1465774b778a28519c00369
MD5 490450baeaef1a557795277e39ba52c0
BLAKE2b-256 d6bba76f2df280e56988c52edb8f18b5e05ad4df5c1a1210021680db7325bf56

See more details on using hashes here.

Provenance

The following attestation bundles were made for andro_cfw-3.0.2-py3-none-any.whl:

Publisher: release-and-changelog.yml on Andromeda-Collective/andro-cfw

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

3.0.2 This release

2 files

0.3.4

2 files

0.3.0

2 files

0.2.1

2 files

0.2.0

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page