# clemsau/telegram-gpt architecture

> Architecture diagram of the GitHub repository clemsau/telegram-gpt, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-03-09). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/clemsau/telegram-gpt
- Repository: https://github.com/clemsau/telegram-gpt

## Overview

This is a **self-hosted Telegram chatbot bot** written in Python. It acts as an **integration service** between:

- **Telegram Bot API** (receives updates/messages, sends replies)
- **OpenAI API (ChatGPT / GPT-3.5)** (generates responses; likely also Whisper or similar for voice if implemented via OpenAI)
- Optional **local runtime concerns** (env config, containerization)

##### File structure analysis → map files to architectural components
Top-level:
- `Dockerfile` → container packaging/runtime
- `pyproject.toml`, `requirements.txt` → dependency management/build metadata
- `assets/demo.gif` → documentation asset
- `src/` → application code

`src/` (core runtime):
- `bot.py` → likely the **entrypoint** that:
- initializes Telegram bot client
- wires handlers
- starts polling or webhook loop
- `handlers.py` → **Telegram update/message handlers**:
- text messages
- mentions logic (toggle “answer on mentions”)
- voice messages handling
- streaming output orchestration (edit message / send partials)
- `openai_utils.py` → **OpenAI integration layer**:
- building prompts/messages
- calling chat completion endpoints
- streaming token handling
- voice transcription if present
- `config.py` → **configuration**:
- reads `TELEGRAM_TOKEN`, `OPENAI_API_KEY`, `ALLOWED_USERS`
- mention-toggle flag (if configurable)
- `entity.py` → **domain objects / DTOs**:
- message/session structures, request/response objects, maybe conversation state
- `src/.env.example` → environment template
- `src/__init__.py` → package marker

This is effectively a small **layered architecture**:
- Presentation/Integration: Telegram handlers (`bot.py`, `handlers.py`)
- Service layer: OpenAI client utilities (`openai_utils.py`)
- Config & domain: (`config.py`, `entity.py`)

From README features:
- “GPT-3.5 chatbot” → OpenAI chat completions
- “Handle voice messages” → voice pipeline: Telegram voice → file download → transcription → prompt → response
- “Message streaming” → streaming responses from OpenAI → streamed back to Telegram (message edits or multiple sends)
- “Toggleable answer on mentions” → group chat gating logic
- “ALLOWED_USERS” → authorization guard before OpenAI calls (cost control)

Deployment notes:
- runs as a low-resource long-running process
- can run bare metal or in Docker (so include runtime boundary)

##### Telegram Client Surface
- “Telegram Users / Group Chats” (actors)
- “Telegram Bot API” (external system)

##### Bot Runtime (this repo)
- “bot.py (Runner/Dispatcher)”
- “handlers.py (Update Handlers)”
- “config.py (Env Config + Access Control)”
- “entity.py (Conversation/Message Models)”
- “openai_utils.py (OpenAI Client + Streaming + Transcription)”

##### OpenAI
- “OpenAI Chat Completions API”
- (If voice is done via OpenAI) “OpenAI Transcription API”

##### Infrastructure / Ops (optional but recommended)
- “Docker Container” (if deployed via Dockerfile)
- “Environment Variables / .env” (configuration source)

##### Streaming response flow (feature-critical)
Same as above, but step (7) becomes a stream:
- OpenAI → `openai_utils.py`: “token stream / chunks”
- `openai_utils.py` → `handlers.py`: “on_chunk callbacks / generator”
- `handlers.py` → Telegram Bot API: “editMessageText (progressive)”
A note: Telegram has rate limits; handler likely batches edits.

##### Chat mention gating
A decision diamond in `handlers.py`:
- If “answer-on-mentions enabled” and chat is group:
- only proceed if bot is mentioned or replied-to
Else ignore.

##### Architectural patterns / principles actually present
Call these out visually (small labels near components):

- **Event-driven dispatcher**: Telegram updates trigger handler functions
- **Integration-layer separation**: OpenAI calls isolated in `openai_utils.py`
- **Configuration via environment**: `config.py` sourcing `.env` / env vars
- **Guardrails**: `ALLOWED_USERS` authorization before expensive API calls
- **Streaming pipeline**: generator/callback-based chunk propagation to Telegram edits

##### Technologies that matter
- Python app (likely `python-telegram-bot` or similar, depending on requirements.txt)
- OpenAI API (Chat Completions; maybe Transcriptions)
- Docker runtime (optional boundary)
- Env vars `.env`

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% =========================================================
    %% Combined Diagram (single Mermaid document; mostly vertical)
    %% =========================================================

    %% =========================
    %% C4 L1 - Context Diagram
    %% =========================
    subgraph L1["C4 L1 - Context Diagram"]
        User["Telegram Users<br/>(DMs & Group Chats)"]:::actor
        TG["Telegram Bot API<br/>(Updates + send/edit + File API)"]:::external

        subgraph Repo["Self-hosted Bot System (this repo)"]
            Runtime["Python Bot Runtime<br/>(Long-running process)"]:::system
        end

        OAI["OpenAI Platform"]:::external
        OAIChat["OpenAI Chat Completions API"]:::external
        OAITranscribe["OpenAI Transcription API<br/>(Voice → text)"]:::external

        User -->|"messages/voice"| TG
        TG -->|"update payloads"| Runtime
        Runtime -->|"sendMessage/editMessageText"| TG
        TG -->|"delivered replies"| User

        Runtime -->|"HTTPS:chat.completions"| OAIChat
        OAIChat -->|"assistant response/stream chunks"| Runtime

        Runtime -->|"HTTPS:transcriptions"| OAITranscribe
        OAITranscribe -->|"transcribed text"| Runtime

        OAI --- OAIChat
        OAI --- OAITranscribe
    end

    %% ============================================
    %% C4 L2/L3 - Container/Component (src/) Diagram
    %% ============================================
    subgraph L2["C4 L2/L3 - Container/Component (src/) Diagram"]
        subgraph RB["Runtime Boundary"]
            direction TB

            subgraph Deploy["Deployment Options"]
                direction TB
                Docker["Docker Container"]:::ops
                Host["Host Process<br/>(python src/bot.py)"]:::ops
            end

            subgraph CB["Config Boundary"]
                direction TB
                Env["Environment Variables / .env<br/>TELEGRAM_TOKEN<br/>OPENAI_API_KEY<br/>ALLOWED_USERS"]:::config
                EnvExample[".env.example (template)"]:::config
            end

            subgraph BR["Bot Runtime (src/)"]
                direction TB
                Bot["bot.py<br/>(Runner/Dispatcher)"]:::module
                Handlers["handlers.py<br/>(Update Handlers)"]:::module

                subgraph Policies["Policies / Guards"]
                    direction TB
                    AuthGate{"ALLOWED_USERS<br/>authorized?"}:::decision
                    MentionGate{"Group chat?<br/>mentions/reply gating?"}:::decision
                end

                OpenAIUtils["openai_utils.py<br/>(OpenAI Client + Streaming + Transcription)"]:::module
                Config["config.py<br/>(Env parsing + feature toggles)"]:::module
                Entity["entity.py<br/>(DTOs / Conversation models)"]:::module
                Init["__init__.py"]:::module
            end

            subgraph ES["External Services"]
                direction TB
                Telegram["Telegram Bot API"]:::external
                OpenAIChat2["OpenAI Chat Completions API"]:::external
                OpenAITranscribe2["OpenAI Transcription API"]:::external
            end
        end

        %% Wiring / bootstrap
        Env -->|"read env"| Config
        EnvExample -.->|"docs/reference"| Env
        Config -->|"tokens + flags"| Bot
        Bot -->|"register handlers"| Handlers
        Bot -->|"polling/webhook loop"| Telegram

        %% Update flow
        Telegram -->|"Update payload"| Bot
        Bot -->|"dispatch(Update)"| Handlers
        Handlers -->|"load policy/settings"| Config
        Handlers -->|"DTOs/state"| Entity

        %% Guardrails
        Handlers -->|"check user_id"| AuthGate
        AuthGate -->|"allow"| MentionGate
        AuthGate -->|"deny (no OpenAI call)"| Telegram

        MentionGate -->|"allow"| OpenAIUtils
        MentionGate -->|"ignore"| Telegram

        %% OpenAI chat + streaming
        OpenAIUtils -->|"HTTPS:chat.completions<br/>messages[] + params"| OpenAIChat2
        OpenAIChat2 -->|"response or stream chunks"| OpenAIUtils
        OpenAIUtils -->|"generator/callback chunks"| Handlers
        Handlers -->|"sendMessage (initial) + editMessageText (progressive)<br/>rate-limited batching"| Telegram

        %% Voice pipeline
        Handlers -->|"getFile + download<br/>audio/ogg bytes"| Telegram
        Handlers -->|"transcribe(audio_bytes)"| OpenAIUtils
        OpenAIUtils -->|"HTTPS:transcriptions<br/>audio upload"| OpenAITranscribe2
        OpenAITranscribe2 -->|"transcribed text"| OpenAIUtils
        OpenAIUtils -->|"use transcript as prompt"| OpenAIChat2

        %% Ops/dev artifacts
        Make["Makefile"]:::ops
        DockerfileNode["Dockerfile"]:::ops
        Pyproject["pyproject.toml"]:::ops
        Reqs["requirements.txt"]:::ops
        Readme["README.md"]:::docs
        Demo["assets/demo.gif"]:::docs

        Make -.->|"build/run shortcuts"| Docker
        DockerfileNode -.->|"image build recipe"| Docker
        Pyproject -.->|"build metadata"| Host
        Reqs -.->|"pip install"| Host
        Readme -.->|"usage/features"| Host
        Demo -.->|"demo asset"| Readme
    end

    %% ==================================
    %% Sequence (as flow) - Streaming Text
    %% ==================================
    subgraph SeqStream["Sequence - Streaming text message flow (progressive edits)"]
        direction TB
        S1["1) User sends text message"]:::docs
        S2["2) Telegram delivers Update payload"]:::docs
        S3["3) bot.py dispatch(Update)"]:::docs
        S4["4) handlers.py loads config + runs mention/auth gates"]:::docs
        S5["5) openai_utils.py calls chat.completions (stream=true)"]:::docs
        S6["6) Stream chunks -> batched edits -> final edit"]:::docs

        S1 --> S2 --> S3 --> S4 --> S5 --> S6
    end

    %% ==============================
    %% Sequence (as flow) - Voice Flow
    %% ==============================
    subgraph SeqVoice["Sequence - Voice message flow (download → transcribe → chat)"]
        direction TB
        V1["1) User sends voice message (ogg/opus)"]:::docs
        V2["2) Update payload (voice) -> bot.py -> handlers.py"]:::docs
        V3["3) handlers.py getFile + downloadFile -> audio bytes"]:::docs
        V4["4) openai_utils.py transcriptions -> transcript text"]:::docs
        V5["5) openai_utils.py chat.completions -> response"]:::docs
        V6["6) handlers.py sendMessage(reply)"]:::docs

        V1 --> V2 --> V3 --> V4 --> V5 --> V6
    end

    %% =================
    %% Click events
    %% =================
    click Runtime "https://github.com/clemsau/telegram-gpt/tree/main/src/"
    click User "https://github.com/clemsau/telegram-gpt/blob/main/README.md"
    click TG "https://github.com/clemsau/telegram-gpt/blob/main/README.md"
    click OAI "https://github.com/clemsau/telegram-gpt/blob/main/README.md"

    click DockerfileNode "https://github.com/clemsau/telegram-gpt/tree/main/Dockerfile"
    click Make "https://github.com/clemsau/telegram-gpt/tree/main/Makefile"
    click Pyproject "https://github.com/clemsau/telegram-gpt/blob/main/pyproject.toml"
    click Reqs "https://github.com/clemsau/telegram-gpt/blob/main/requirements.txt"
    click Readme "https://github.com/clemsau/telegram-gpt/blob/main/README.md"
    click Demo "https://github.com/clemsau/telegram-gpt/blob/main/assets/demo.gif"
    click Bot "https://github.com/clemsau/telegram-gpt/blob/main/src/bot.py"
    click Handlers "https://github.com/clemsau/telegram-gpt/blob/main/src/handlers.py"
    click OpenAIUtils "https://github.com/clemsau/telegram-gpt/blob/main/src/openai_utils.py"
    click Config "https://github.com/clemsau/telegram-gpt/blob/main/src/config.py"
    click Entity "https://github.com/clemsau/telegram-gpt/blob/main/src/entity.py"
    click EnvExample "https://github.com/clemsau/telegram-gpt/blob/main/src/.env.example"
    click Init "https://github.com/clemsau/telegram-gpt/blob/main/src/__init__.py"

    %% =================
    %% Styles
    %% =================
    classDef actor fill:#E8F4FF,stroke:#1D4ED8,stroke-width:1px,color:#0B1F44
    classDef external fill:#F3F4F6,stroke:#6B7280,stroke-width:1px,color:#111827
    classDef system fill:#DBEAFE,stroke:#2563EB,stroke-width:1.5px,color:#0B1F44
    classDef module fill:#FFFFFF,stroke:#2563EB,stroke-width:1px,color:#0B1F44
    classDef decision fill:#FEF3C7,stroke:#B45309,stroke-width:1px,color:#111827
    classDef config fill:#ECFDF5,stroke:#059669,stroke-width:1px,color:#064E3B
    classDef ops fill:#EEF2FF,stroke:#4F46E5,stroke-width:1px,color:#1E1B4B
    classDef docs fill:#FFF7ED,stroke:#C2410C,stroke-width:1px,color:#7C2D12
```
