Skip to content

Latest commit

 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Multi-tenant Telegram CRM — Managed Bots + Rich Messages 🤖📊

CI

A multi-tenant Telegram CRM platform built on two brand-new Telegram Bot API features (2026) that almost no freelance portfolio has yet:

  • Managed Bots (Bot API 9.6, 3 Apr 2026) — one manager bot provisions per-customer child bots via getManagedBotToken / t.me/newbot/{manager}/{suggested} / KeyboardButtonRequestManagedBot. Native multi-tenancy.
  • Rich Messages (Bot API 10.1, 11 Jun 2026)sendRichMessage + sendRichMessageDraft stream structured AI replies (bold, lists, code, blockquotes) to the client.

Each tenant gets its own bot running FSM flows (lead capture, FAQ), replies streamed as Rich Messages, and an isolated row in a multi-tenant FastAPI admin dashboard with analytics. Child-bot tokens are encrypted at rest (Fernet); every admin action is audit-logged; every query is tenant-isolated.

Built with simple composable patterns over framework bloat (per Anthropic's "Building Effective Agents") — StatesGroup FSM, plain SQLAlchemy, no agent-framework soup.

Architecture

                 ┌──────────────────────────────────────────────┐
                 │                   Process                     │
   Telegram ───▶ │  Manager bot (aiogram)                        │
                 │   /start  /demo  /provision                   │
                 │   managed_bot_created → store + spawn child    │
                 │                                               │
                 │  Child-bot supervisor (1 polling task/tenant) │
                 │   each child: fixed tenant_id (middleware)    │
                 │   flows: lead capture · FAQ · onboarding      │
                 │   replies: Rich Message streaming (10.1)      │
                 │                                               │
                 │  FastAPI admin (uvicorn, same process)        │
                 │   tenants · leads · analytics · FAQ CRUD      │
                 │   session auth · audit log · tenant isolation │
                 └───────────────┬───────────────────────────────┘
                                 │
                       PostgreSQL (Neon) + Fernet-encrypted tokens

Two multi-tenancy paths, both shipped:

  • Real/provision opens Telegram's Managed Bots wizard; on managed_bot_created the platform fetches the child token, encrypts it, stores Tenant+ChildBot, and spawns a polling task.
  • Simulated (DEMO_MODE=true)/demo lists demo tenants; the manager bot then acts as the chosen tenant's bot (tenant_id in FSM state). Demoable in a single chat without creating real child bots.

Stack

aiogram 3.29.0 (Bot API 10.1) · FastAPI + Jinja2 · SQLAlchemy 2 async + asyncpg/aiosqlite · cryptography (Fernet) · pydantic-settings · pytest/pytest-asyncio/httpx · Docker + Render.

Run locally

python -m venv .venv && source .venv/bin/activate   # Windows: .venv\Scripts\activate
pip install -r requirements.txt
cp .env.example .env          # fill MANAGER_BOT_TOKEN from @BotFather
python -m app                 # bot (long-polling) + admin on http://localhost:8000

Open http://localhost:8000/login (password from ADMIN_PASSWORD, default admin). In Telegram: /demo → pick a tenant → /start → «Оставить заявку» or «Задать вопрос».

Deploy (Render + Neon)

  1. Create a free Postgres on Neon → copy the connection string.
  2. Render → Blueprints → select this repo → Apply.
  3. In the Render dashboard set MANAGER_BOT_TOKEN, DATABASE_URL (postgresql+asyncpg://…?sslmode=require), ADMIN_PASSWORD. ENCRYPTION_KEY/SESSION_SECRET auto-generate.

Tests

python -m pytest -q      # 27 tests: rich builder, demo LLM, crypto, provisioning,
                         # multi-tenant isolation, FSM lead flow, admin endpoints

Key suite: test_tenancy_isolation (tenant A can't see B's data), test_fsm_lead (full lead state machine), test_provisioning (token encrypted at rest), test_admin (HTTP-layer isolation).

Project structure

app/
  config.py            # settings (env)
  models.py            # Tenant, ChildBot, Lead, FaqItem, AuditLog (tenant_id everywhere)
  database.py          # engine, SessionLocal, get_db, audit helper
  crypto.py            # Fernet encrypt/decrypt for child-bot tokens
  seed.py              # demo tenants + sample leads/FAQ
  llm.py               # demo-mode RAG-lite + Rich builders + streaming chunks
  web.py               # FastAPI admin (auth, isolation, analytics, FAQ CRUD)
  bot/
    manager.py         # manager dispatcher: /demo, /provision, managed_bot_created
    child.py           # child-bot factory (fixed tenant_id)
    supervisor.py      # one polling task per active child bot
    provisioning.py    # store_provisioned_bot (tested service)
    tenancy.py         # tenant resolution (real vs simulated)
    middleware.py      # TenantMiddleware (injects tenant_id)
    rich.py            # Rich Message builder + sendRichMessageDraft streaming
    scenes/            # common, lead, faq, onboarding (StatesGroup FSM)
  __main__.py          # uvicorn + bot polling in one process
tests/                 # 27 tests

Notes / roadmap

  • MVP ships: provisioning (real + simulated), lead capture, FAQ (RAG-lite), Rich Message streaming, multi-tenant admin + analytics, audit log, tests, CI, deploy.
  • Phase 2: booking FSM, channel auto-posting scheduler, Redis FSM, richer analytics.
  • Phase 3: tenant subscription payments (Stripe + Telegram Stars), moderation queue, token rotation, webhooks instead of per-bot polling.
  • Real Managed Bots provisioning requires the owning account's can_manage_bots; the simulated /demo path needs no special account and is the live portfolio demo.

About

Multi-tenant Telegram CRM on Managed Bots (Bot API 9.6) + Rich Messages (10.1). aiogram 3.29, FastAPI admin, multi-tenant isolation, streaming replies, encrypted tokens, 29 tests.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages