Summary. Below — why five services instead of one, how the AI moderator learns, and where the complexity is hidden.
Why five services. A monolith is simpler but bad at partial failure. Worker dies → Collector keeps recording history, Admin Bot stays alive, state is still visible via Telegram. Moderator dies → auto-reply still works. Core API falls → the others aren't affected. Each service owns its systemd unit, its log, its restart policy.
Worker — brain of the auto-reply. A Telethon session on behalf of the user (not a bot) listens to every incoming DM. Each message triggers a cascade: auto-reply globally enabled? contact in the Personal folder or covered by a rule? reply mode not off? daily limit not exhausted? minimum interval since the last reply elapsed? If every check passes — the reply is generated via AI (Claude → Grok → Local fallback) and sent through the same Telethon session. If AI fails entirely, a template is sent.
Admin Bot — the console. An aiogram bot the owner uses for everything: toggle auto-reply, add/remove rules per contact, view conversation history, edit the prompt, change limits, switch mode. From the admin bot you can restart the worker (systemctl restart worker) — no SSH needed.
Moderator — the self-learning channel moderator. The most interesting piece. The /scan command reads the last 500 channel posts via Telethon. AI (Claude) analyses and produces a summary: what the channel is about, the tone, what's on and off-topic. The summary lives in the DB. When a new message appears in the discussion group, AI compares it against the summary → outputs OK / SPAM / HATE / OFFTOPIC. SPAM / HATE / OFFTOPIC are auto-deleted; OK stays.
Without /scan the moderator runs on a default "general moderation" prompt; after /scan it adapts to the specific channel: on a fishing channel, talk about tax strategies is OFFTOPIC; on an investing channel — OK.
Antiflood. Tracked in memory, not in DB (faster). Each user_id → list of recent timestamps. If more than M messages in N seconds → mute for K minutes. Limits configurable via Admin Bot.
Database. PostgreSQL 14, database ai_tg_core, user aiuser. Seven tables: peers (contacts with in_personal flag), messages (history), auto_reply_rules (per-contact rules), auto_reply_state (reply state), settings, reply_counts, chat_triggers (per-chat moderator triggers).
Open source. Repository: https://github.com/georgegoldman48-svg/tg-auto-reply — public, full architecture documented in README.md.