How allecosay/respmanager works
1. Overall shape
This is a Telegram assistant built around a long-lived Telethon user session, not the Telegram Bot API. Its core job is to ingest group messages into PostgreSQL, maintain several derived state tables, and answer commands or trigger autonomous replies using an LLM via OpenRouter.
2. Startup and runtime boundary
app/main.py is the application entrypoint. It wires together env-based runtime settings, YAML-backed feature configs, logging, the PostgreSQL session, the Telethon client, and the background services. The container startup also runs Alembic migrations, so schema changes are part of normal deployment.
3. Telegram ingress layer
app/telegram_client/ wraps Telethon with a project-specific client and adapter layer. Raw Telegram updates are converted into internal types, then handed to message ingestion, command handling, reaction processing, and pollers. The Telethon session is persisted under config/ so restarts do not require a new login.
4. Command handling path
app/bot/command_handlers.py and app/bot/commands.py parse /ai, /tldr, /stats, /help, /whitelist, and related commands. These handlers are thin orchestration code: they perform access checks, call the relevant service, and format the reply for Telegram. The formatting module keeps the chat-facing output separate from business logic.
5. Access control and authorization
app/auth/ manages admin and whitelist policy using YAML-backed storage. This is the gate in front of sensitive commands and AI access. The repository is explicitly designed to refuse unsafe startup modes unless the allowlist is intentional.
6. Persistence model
app/db/models.py, repositories.py, and session.py form the persistence boundary. PostgreSQL stores the canonical message history plus derived tables for reactions, activity reply state, memory profiles, bot identity profiles, and statistics-related data. The Alembic versions show the system evolving around message reactions, reply state, memory, and identity features.
7. AI answer pipeline
/ai is served by app/services/ai_answer_service.py. It uses context_builder.py and the various LLM config modules to assemble a thread-aware prompt from nearby messages and cross-thread context, then calls app/llm/openrouter_client.py. This is the main read path from stored chat history into the external LLM service.
8. Summarization and context services
/tldr is implemented by app/services/tldr_service.py, which summarizes recent message windows rather than doing general question answering. app/llm/context_builder.py, thread_activity.py, and related helpers define how much history is considered and how thread boundaries influence the context sent to the model.
9. Autonomous background behavior
Three poller-driven subsystems operate off the stored chat history:
- reaction_poller / reaction_service watch reaction snapshots and may post an LLM-generated response when thresholds are met.
- activity_poller / activity_service detect lively chats and can inject spontaneous replies or follow-ups.
- memory_poller / memory_service refresh long-term per-chat memory and user profiles based on activity, keywords, and staleness.
These are separate from command handling and are designed to survive restarts by persisting state in PostgreSQL.
10. Statistics pipeline
app/services/stats_service.py, stats_report.py, stats_renderer.py, and stats_image_renderer.py build /stats output from existing database rows. This path does not call the LLM. It can render either as an image chart or as ASCII/text, depending on configuration, and it pulls from the same message, reaction, command, and usage history maintained elsewhere.
11. Auxiliary services
There are a few smaller but important side systems: auto_delete_config.py controls cleanup of bot replies after posting; bot_identity_service.py and avatar_service.py manage bot identity/profile behavior; telegram_links.py and utils/telegram.py encapsulate Telegram-specific link and formatting logic; and image_generation_client.py supports image-producing workflows where needed.
12. Configuration topology
Secrets and deployment settings live in .env, while behavior is mostly driven by hot-reloaded YAML under config/. The YAML files split policy by domain: prompts, context limits, reactions, activity, memory, stats, auto-delete, identity, and access lists. That separation is a major architectural boundary: runtime credentials and infrastructure settings are distinct from feature behavior.
13. Key data flow for diagramming
The most important end-to-end flow is: Telegram event → Telethon adapter → ingestion/command/poller service → PostgreSQL read/write → optional OpenRouter call → Telegram reply. The second major flow is the autonomous one: database state and pollers → eligibility/rule evaluation → LLM or formatted output → Telegram message/reaction/state update.
14. Operational boundaries
The app is containerized with Docker Compose and expects PostgreSQL plus a Telegram-auth bootstrap container. Tests cover config parsing, adapter conversion, formatting, pollers, and the service logic, which suggests a design that keeps Telegram I/O, persistence, and business rules cleanly separated.
Main entry points: main.py Main · repositories.py Repositories · command_handlers.py Handlers · telethon_adapter.py Adapter
Components 31
Runtime
Application startup and shared runtime wiring
- Main · Bootstraps config, database, Telegram client, and background services
app/main.py - Runtime cfg · Environment-driven runtime settings
app/llm/runtime_config.py
Telegram
Telegram client boundary and update ingress
- Telethon client · Project-specific wrapper around the long-lived Telegram session
app/telegram_client/client.py - Adapter · Converts raw Telegram updates into internal event types
app/telegram_client/telethon_adapter.py - Ingestion · Persists incoming chat messages and derived state
app/services/message_ingestion.py
Bot
Command handling and chat-facing output
- Handlers · Dispatches and executes Telegram commands
app/bot/command_handlers.py - Commands · Parses supported slash commands
app/bot/commands.py - Formatting · Builds chat-facing replies and message text
app/bot/formatting.py
Policy
Access control and YAML-backed feature settings
- Access control · Admin and whitelist checks for sensitive actions
app/auth/access_control.py - YAML store · Loads policy and allowlist data from YAML
app/auth/yaml_store.py
Persistence
Database schema, session, and repositories
- DB session · Database connection and transactional session boundary
app/db/session.py - Models · Canonical message, reaction, memory, identity, and stats tables
app/db/models.py - Repositories · Repository layer for persisted chat state
app/db/repositories.py - Migrations · Alembic migration history for PostgreSQL schema changes
app/db/migrations/versions/0001_initial_schema.py
LLM
Context assembly and external model calls
- AI answer · Answers /ai using stored chat context and OpenRouter
app/services/ai_answer_service.py - TL;DR · Summarizes recent message windows for /tldr
app/services/tldr_service.py - Context builder · Builds thread-aware context from nearby and related messages
app/llm/context_builder.py - OpenRouter · External model API client
app/llm/openrouter_client.py
Autonomy
Background pollers that react to stored chat state
- Reaction poller · Watches reaction snapshots and triggers reactions workflows
app/services/reaction_poller.py - Reaction svc · Evaluates thresholds and may generate replies from reactions
app/services/reaction_service.py - Activity poller · Detects lively chats and schedules spontaneous follow-ups
app/services/activity_poller.py - Activity svc · Decides when a chat is active enough for autonomous responses
app/services/activity_service.py - Memory poller · Refreshes long-term chat memory and user profiles
app/services/memory_poller.py - Memory svc · Maintains per-chat memory and profile state
app/services/memory_service.py
Stats
Reporting and rendering pipeline
- Stats svc · Builds /stats output from stored usage and chat rows
app/services/stats_service.py - Stats report · Assembles statistics data from database history
app/services/stats_report.py - Stats renderer · Renders stats as formatted text or ASCII
app/services/stats_renderer.py - Stats image · Renders stats as charts/images
app/services/stats_image_renderer.py
Identity
Bot identity, avatar, and media helpers
- Identity svc · Manages bot identity/profile behavior
app/services/bot_identity_service.py - Avatar svc · Handles avatar-related behavior for the bot identity
app/services/avatar_service.py - Image gen · External image generation support
app/services/image_generation_client.py
Connections 40
- Main → Runtime cfg: loads · Reads deployment and runtime settings
- Main → DB session: opens · Creates the PostgreSQL session boundary
- Main → Telethon client: starts · Initializes the long-lived Telegram session
- Main → Handlers: wires · Connects command processing into runtime
- Main → Ingestion: wires · Connects message ingestion into runtime
- Main → Reaction poller: starts · Launches background reaction scanning
- Main → Activity poller: starts · Launches background activity scanning
- Main → Memory poller: starts · Launches background memory refresh
- Telethon client → Adapter: uses · Normalizes raw Telegram updates
- Adapter → Ingestion: emits · Forwards message events for storage
- Adapter → Handlers: emits · Routes command updates
- Adapter → Reaction poller: feeds · Provides reaction snapshots and update context
- Handlers → Commands: parses · Interprets slash command input
- Handlers → Access control: checks · Enforces admin and whitelist policy
- Handlers → Formatting: formats · Builds user-facing replies
- Access control → YAML store: reads · Loads allowlists and policy state
- Ingestion → DB session: writes · Persists incoming messages and derived rows
- Ingestion → Repositories: uses · Stores data through repositories
- Repositories → Models: maps · Implements the persistence model
- Models → Migrations: evolves · Schema changes track model growth
- AI answer → Context builder: builds · Assembles thread-aware prompt context
- AI answer → OpenRouter: calls · Sends prompt to external model service
- AI answer → Repositories: reads · Pulls nearby and cross-thread chat history
- TL;DR → Context builder: uses · Selects summarization context window
- TL;DR → Repositories: reads · Loads recent messages for summarization
- Reaction poller → Reaction svc: drives · Hands reaction snapshots to workflow logic
- Reaction svc → Repositories: reads/writes · Evaluates reaction state and records outcomes
- Reaction svc → OpenRouter: may call · Generates LLM-based reaction replies when needed
- Activity poller → Activity svc: drives · Feeds activity evaluation loop
- Activity svc → Repositories: reads/writes · Uses stored activity and reply state
- Activity svc → OpenRouter: may call · Can generate autonomous follow-up replies
- Memory poller → Memory svc: drives · Feeds memory refresh loop
- Memory svc → Repositories: reads/writes · Maintains long-term memory and profiles
- Stats svc → Stats report: builds · Aggregates usage and chat history
- Stats report → Repositories: reads · Consumes persisted message, command, and reaction rows
- Stats svc → Stats renderer: renders · Produces text/ASCII output
- Stats svc → Stats image: renders · Produces chart/image output
- Identity svc → Repositories: reads/writes · Stores and loads identity profiles
- Avatar svc → Identity svc: supports · Feeds identity/avatar behavior
- Avatar svc → Image gen: may call · Requests generated imagery when needed