How hexdevop/aiogram_sqlalchemy_replication works
Project Type and Purpose
• This is a lightweight, monolithic Telegram bot template built with aiogram v3. It demonstrates asynchronous message handling and MySQL replication for read‑write separation and high availability.
• Key use cases: receiving updates from Telegram, processing them via handlers, storing/retrieving data in a master‑replica MySQL setup, and sending responses with custom keyboards.
High‑Level Architectural Components
a. Telegram Bot API (External Service)
• Long‑polling or webhook endpoint that delivers updates to your bot.
b. Bot Core (main.py, config.py, settings.json)
• Initializes the aiogram Dispatcher, registers middlewares, filters, handlers, and the database engine.
c. Dispatcher & Event Loop (aiogram framework)
• Routes incoming updates through filters → middlewares → handlers.
d. Filters (bot/filters)
• chat_type.py: pre‑handler logic that selects only certain chat types.
e. Middlewares (bot/middlewares)
• database.py: attaches a DB session/connection to each update’s context.
f. Handlers (bot/handlers)
• Default handlers for errors and blocks.
• Channel‑specific handlers.
• Chat handlers.
• User handlers (deep_link, main/start).
g. UI Components (bot/keyboards)
• factory.py: centralized keyboard creation.
• inline.py, reply.py: define button layouts.
h. Finite State Machine (bot/states.py)
• Tracks multi‑step user interactions.
i. Database Engine (bot/database/engine)
• manager.py: sets up SQLAlchemy engines for master (writes) and replicas (reads).
• routing.py: custom session/connection router that sends reads to replicas and writes to master.
j. ORM Models (bot/database/models)
• base.py: common declarative base.
• default.py: sample models/datatypes.
k. Data Storage (MySQL Master + Replicas)
• Master handles INSERT/UPDATE/DELETE.
• One or more replicas handle SELECT queries.
l. External Dependencies
• aiogram, SQLAlchemy, MySQL driver.
Relationships and Data Flows
• Telegram API → Bot Core (main.py) → Dispatcher
• Incoming Update → Filter(chat_type) → Middleware(DB session) → Handler
• Handler business logic → invokes ORM via session
• Writes → master engine via routing
• Reads → replica engine via routing
• Handler builds response using keyboards and sends back to Telegram API.
• The FSM module coordinates multi‑step dialogs by storing state in memory or DB.
• Settings.json & config.py provide DB credentials, replica addresses, bot token.
Architectural Patterns and Principles
• Layered Architecture: presentation (Telegram), application (Dispatcher + Handlers), data (ORM + MySQL).
• Dependency Injection via aiogram’s middleware (inject DB session).
• Read‑write splitting for scalability and fault tolerance.
• Modular handlers grouped by domain (user, channels, default).