Telegram Bot Architecture
Relevant source files
The following files were used as context for generating this wiki page:
The Telegram Bot Architecture of CodeBot is designed as a multi-layered system for managing, saving, and sharing code snippets. It leverages the python-telegram-bot framework to handle user interactions, integrated with a MongoDB backend for persistence and various external services for extended functionality like GitHub synchronization and image generation.
The architecture follows a modular approach, separating presentation (Telegram handlers), application logic (services), and data access (repositories). This structure allows for features such as automatic language detection, version control for snippets, and advanced batch processing of code files.
Sources: GUIDES/ARCHITECTURE_ANALYSIS_PART1.md:12-20, main.py:1-40
High-Level System Components
The system is divided into several functional layers that communicate to process user commands and manage data.
The diagram illustrates the flow from user input through the processing layer to core services and storage backends.
Sources: GUIDES/ARCHITECTURE.md:17-43, main.py:100-150
Layer Descriptions
| Layer | Responsibility | Key Files |
|---|---|---|
| Presentation | Handles Telegram API updates, message routing, and user interface elements (buttons, menus). | main.py, bot_handlers.py |
| Application | Implements business logic such as code normalization, language detection, and ZIP creation. | conversation_handlers.py, services/ |
| Infrastructure | Provides database connectivity, external API integrations (GitHub, Google Drive), and logging. | database/, main.py |
Sources: PROMPTS_WEBAPP_LAYERING.md:20-45, GUIDES/ARCHITECTURE_ANALYSIS_PART1.md:65-120
Command Execution Flow
Command processing involves permission checks, argument validation, and metric collection before executing the core logic.
The flowchart details the sequential steps taken by the bot when a user issues a command.
Sources: GUIDES/ARCHITECTURE.md:4-15
Handler Types
The bot uses different handler types to manage various interaction modes:
- Command Handlers: Handle direct slash commands (e.g.,
/show,/save). - Message Handlers: Catch text input or documents for processing (e.g., code snippets, ZIP files).
- Callback Query Handlers: Process interactions with inline buttons.
- Conversation Handlers: Manage multi-step stateful flows (e.g., the saving flow).
Sources: main.py:1100-1250, conversation_handlers.py:1300-1350
Data Management and Persistence
The bot utilizes a Repository Pattern to abstract database operations, primarily targeting MongoDB for storing user data and code snippets.
Core Entities
- CodeSnippet: Represents a versioned code file with associated metadata (language, tags, description).
- User: Stores user preferences, session data, and activity statistics.
- Lock: A distributed lock mechanism stored in MongoDB to ensure only one bot instance is active.
Sources: main.py:750-800, GUIDES/ARCHITECTURE_ANALYSIS_PART1.md:150-170
Database Operations Flow
Sequence of events during a snippet save operation demonstrating the separation of concerns.
Sources: GUIDES/ARCHITECTURE_ANALYSIS_PART1.md:173-210, conversation_handlers.py:110-150
Distributed Lock Mechanism
To prevent multiple bot instances from polling the same updates (which leads to telegram.error.Conflict), the architecture includes a MongoDB-based distributed lock.
State machine representing the distributed lock lifecycle to ensure singleton bot execution.
Sources: main.py:750-1050
| Component | Function | Default Value |
|---|---|---|
| Lease Seconds | Duration the lock remains valid without a refresh. | 10 seconds |
| Heartbeat Interval | Frequency of lease renewal attempts. | 3 seconds |
| Acquire Wait | Range of delay before retrying lock acquisition. | 15-45 seconds |
Sources: main.py:900-950
Advanced Features Architecture
Image Generation Flow
The bot can generate stylized PNG images from code snippets using the CodeImageGenerator.
- Trigger: User issues
/image <filename>. - Settings: Bot fetches user preferences (theme, font, style) from MongoDB.
- Generation: The service processes the raw code into an image buffer.
- Output: The buffer is sent to the user as a Telegram photo and optionally saved to Google Drive.
Sources: bot_handlers.py:30-100, bot_handlers.py:1200-1280
Batch Processing
Batch operations allow users to analyze or validate multiple files simultaneously. The batch_processor manages these as "Jobs," providing asynchronous status updates to the user.
Sources: conversation_handlers.py:1450-1550
Summary
The CodeBot architecture is characterized by a robust distributed management system and a clear separation of logic. By utilizing stateful conversations and a repository-backed persistence layer, it provides a stable environment for code management within Telegram. The inclusion of distributed locking and health monitoring ensures high availability and consistency across deployments.