High-Level Architecture
Relevant source files
The following files were used as context for generating this wiki page:
The Telegram History Bot is a Cloudflare Worker-based application that collects, stores, and analyzes Telegram chat messages. The bot persists messages for 7 days in Cloudflare KV, aggregates per-user metrics via Durable Objects, and utilizes Cloudflare Workers AI or OpenAI for generating summaries and performing legal/profanity analysis.
Sources: AGENTS.md:3-6, README.md:8-16
Core System Components
The architecture relies on Cloudflare's serverless stack to maintain low costs while handling high message volumes. The system separates concerns between message ingestion, stateful counter management, and complex AI processing pipelines.
| Component | Technology | Purpose |
|---|---|---|
| Worker Entry | Cloudflare Workers | Handles Telegram webhooks, authenticates requests, and routes commands. |
| Short-term Storage | Cloudflare KV | Stores message history for 7 days using daily blocks for fast retrieval. |
| Stateful Processing | Durable Objects | Manages per-user message counters and orchestrates complex analysis queues. |
| Long-term Storage | Cloudflare D1 | Archives violation history, statistics, and historical summaries beyond the KV TTL. |
| AI Processing | Workers AI / OpenAI | Executes text summarization, profanity detection, and criminal code analysis. |
Sources: AGENTS.md:3-6, 12-25, README.md:8-16
Inbound Message Flow
When a user sends a message in a monitored Telegram chat, the worker validates the HMAC-SHA256 signature to ensure the request originates from Telegram. Validated messages are recorded in KV storage and forwarded to analysis modules.
This diagram shows the sequence from webhook reception to persistence across storage layers.
Sources: AGENTS.md:66-73, README.md:8-16, src/durable-objects/criminal-code-analyzer-do.ts:138-160
Optimized Summary System
The bot implements an optimized summary system to handle large message volumes that exceed standard LLM context windows. It utilizes a strategy selector to choose between direct, parallel, or hierarchical processing based on message count and estimated tokens.
Hierarchical Processing
For large datasets, the HierarchicalProcessor executes a three-stage pipeline:
- Stage 1: Per-chunk Preprocessing: Segments messages into chunks and generates JSON-formatted per-user summaries.
- Stage 2: Aggregation: Merges per-user summaries from all chunks into a unified dataset, tracking total message counts.
- Stage 3: Final Summarization: Generates a structured final summary from the aggregated synthetic data.
Sources: src/features/summary/optimization/hierarchical-processor.ts:26-50, 117-152, README.md:38-43
The diagram represents the multi-stage processing required to stay within token budgets while maintaining summary quality.
Sources: src/features/summary/optimization/hierarchical-processor.ts:26-115
Criminal Code Analysis Pipeline
Criminal analysis is handled by a dedicated Durable Object (CriminalCodeAnalyzerDO) to manage stateful queues and prevent rate-limiting issues.
Semantic Prefiltering and RAG
To optimize costs, the system uses a semantic prefilter before calling expensive legal analysis models.
- Prefilter: A "nano" LLM model identifies potential risks (threats, incitement, extremism).
- Legal-RAG: If the prefilter identifies a risk, the system retrieves relevant legal references from the D1 database.
- Final Judge: A high-capacity model (e.g., GPT-4/5) acts as a "Final Judge" to verify the violation against retrieved legal text and chat context.
Sources: src/durable-objects/criminal-code-analyzer-do.ts:318-364, 497-515, 626-658
This flowchart illustrates the multi-tier filtering logic used to ensure accuracy in legal analysis.
Sources: src/durable-objects/criminal-code-analyzer-do.ts:389-440
Storage Schema and Retention
The system maintains specific TTL and archival rules to balance performance with storage constraints.
| Data Type | Storage Engine | Retention Policy | Key Pattern / Scope |
|---|---|---|---|
| Message History | KV | 7 Days (TTL: 604800s) | msg:{chat}:{ts}:{id} |
| Per-User Counters | Durable Objects | Live | Chat ID Scope |
| Summaries | D1 | Ephemeral (30 Days) | summaries table |
| Violation History | D1 | Persistent | criminal_violations table |
| Analysis Cache | KV / D1 | 24 Hours to 30 Days | criminal_cache:{hash} |
Sources: AGENTS.md:70-74, README.md:12-16, src/durable-objects/criminal-code-analyzer-do.ts:940-985
Conclusion
The High-Level Architecture of the Telegram History Bot prioritizes scalability through Cloudflare's distributed infrastructure. By combining ephemeral KV storage with structured D1 databases and stateful Durable Objects, the system handles real-time message analysis and complex AI summarization while strictly adhering to security and privacy guidelines such as PII stripping and HMAC validation.
Sources: AGENTS.md:3-6, 66-74