1
0
Fork 0
mirror of https://github.com/EDeev/chatping_abobot.git synced 2026-10-07 20:49:45 +03:00

README: версия 4 — PostgreSQL, ограничения больших чатов, /settings, /top, /month, учёт бота в группах, развёртывание

This commit is contained in:
Деев Егор Викторович 2026-10-06 11:26:12 +00:00
parent a2a0adcf8e
commit af372fbdf0
2 changed files with 104 additions and 48 deletions

View file

@ -18,16 +18,22 @@ The bot speaks Russian.
**Status:** personal project, running since 2021 · bot [@chat_abobot](https://t.me/chat_abobot) · over **Status:** personal project, running since 2021 · bot [@chat_abobot](https://t.me/chat_abobot) · over
20,000 users from 45 chats in the bot's database (October 2026) 20,000 users from 45 chats in the bot's database (October 2026)
**Stack:** Python 3.12 · aiogram 3 · pymorphy3 · pyenchant · SpeechRecognition · gTTS · SQLite · Docker **Stack:** Python 3.10+ · aiogram 3 · PostgreSQL (asyncpg) · pymorphy3 · pyenchant · SpeechRecognition · gTTS · Docker
## Features ## Features
- **Name mentions.** Words of a message are reduced to their base form (pymorphy3) and compared with - **Name mentions.** Words of a message are reduced to their base form (pymorphy3) and compared with
members' names, so any grammatical case of a name mentions the right person. A custom name can be set with `/edit`. Names are also found members' names, so any grammatical case of a name mentions the right person. A custom name can be set with `/edit`. Names are also found
in voice notes up to a minute long. in voice notes up to a minute long.
- **`/all`** mentions every member. - **`/all`** mentions every member. A long list is split into several messages.
- **Big chats (over 100 members).**
- `/all` is for admins only, at most once in 5 minutes, and only for people who wrote in the last 30 days.
- The same person is mentioned by name at most once a minute.
- **All-time and monthly statistics** (`/stat_group`, `/stat_user`): messages, replies, commands, links, - **All-time and monthly statistics** (`/stat_group`, `/stat_user`): messages, replies, commands, links,
media, stickers, voice and video notes. Monthly numbers reset at the start of each month. media, stickers, voice and video notes. Months are kept, so `/month 2026-09` shows any month's summary
and `/top` shows the most active members for the month or all time (`/top all`).
- **`/settings`** — per-chat switches: name mentions, names in voice notes (audio goes to Google), text
events, deleting service messages. Admins can change them.
- **Wrong keyboard layout.** A message like `ghbdtn` is repeated as «привет». English words are recognized - **Wrong keyboard layout.** A message like `ghbdtn` is repeated as «привет». English words are recognized
with a dictionary (pyenchant) and left alone. with a dictionary (pyenchant) and left alone.
- **Voice.** `/recognize` as a reply to a voice note transcribes it; «Озвучь - текст» turns text into a - **Voice.** `/recognize` as a reply to a voice note transcribes it; «Озвучь - текст» turns text into a
@ -39,37 +45,56 @@ The bot speaks Russian.
- mock fights; - mock fights;
- picture reactions. - picture reactions.
Turned off with `/stop_bot`. Turned off with `/stop_bot` or in `/settings`.
- Deleting service messages (joins, leaves, title and photo changes) when the bot is an admin. - Deleting service messages (joins, leaves, title and photo changes) when the bot is an admin.
- **Tracking the bot in groups.** The bot records which groups it is in and with which rights: Telegram
events plus a check on start and every 6 hours. Changes are kept as history. If the bot is removed, the
group's statistics stay; only the mark that the bot is no longer there changes.
## Running ## Running
```bash ```bash
git clone https://github.com/EDeev/chatping_abobot.git && cd chatping_abobot git clone https://github.com/EDeev/chatping_abobot.git && cd chatping_abobot
cp .env.example .env # BOT_TOKEN from @BotFather cp .env.example .env # BOT_TOKEN from @BotFather
docker compose up -d docker compose up -d # the bot and PostgreSQL
``` ```
Prebuilt image: `docker pull ghcr.io/edeev/chatping_abobot` or `docker pull dcr.deev.su/edeev/chatping_abobot`. Prebuilt image: `docker pull ghcr.io/edeev/chatping_abobot` or `docker pull dcr.deev.su/edeev/chatping_abobot`.
The SQLite databases are created on first start. Tables are created on first start (`code/schema.sql`).
Without Docker you need Python 3.12, the enchant system library and an English dictionary Without Docker you need:
(`apt install libenchant-2-2 hunspell-en-us`). Then: `pip install -r requirements.txt` and - Python 3.10+;
`cd code && BOT_TOKEN=… python bot.py`. - PostgreSQL;
- the enchant system library with an English dictionary (`apt install libenchant-2-2 hunspell-en-us`).
Then: `pip install -r requirements.txt` and `cd code && BOT_TOKEN=… DATABASE_URL=postgresql://… python bot.py`.
Migrating data from the old version (four SQLite databases):
`python scripts/migrate_sqlite.py --sqlite-dir path/to/db --dsn postgresql://…`. The script checks the
totals after the transfer.
## Deployment
[@chat_abobot](https://t.me/chat_abobot) runs on a home server as a systemd service: its own venv, settings in
`/etc/abobot.env`, PostgreSQL on the same server. The nightly backup dumps the database, and the statistics
feed a Metabase dashboard.
## How it works ## How it works
``` ```
code/bot.py entry point and monthly statistics reset code/bot.py entry point, error reports to a tech chat, checking the bot's status in groups
code/handlers.py message, command, voice and event handlers code/handlers/ routers: help, settings, stats, mentions, voice, events, chat (bot in groups, service messages)
code/script.py statistics, name lookup, keyboard layout, text reversal code/db.py PostgreSQL queries
code/sql.py four SQLite databases: groups, users, all-time and monthly statistics code/schema.sql schema: chats, users, members, chat_stats and member_stats by period, bot_status_history
data/ event pictures and the greeting code/nlp.py base forms of names, keyboard layout, reversal, escaping
scripts/ migration from SQLite
data/ event pictures and the greeting
``` ```
Member statistics live in a separate table per chat — that is how the bot's production databases are All-time and current-month counters grow in a single query (`INSERT … ON CONFLICT DO UPDATE`), so
built. Counters are incremented in a single query, so simultaneous messages are not lost. Speech recognition simultaneous messages are not lost. Database calls are asynchronous and speech recognition and synthesis
and synthesis (Google Web Speech and gTTS) run in a separate thread, so the bot never freezes. (Google Web Speech and gTTS) run in a separate thread, so the bot never freezes. Messages use HTML markup and
user text is escaped.
## Development ## Development
@ -78,12 +103,15 @@ pip install -r requirements-dev.txt
ruff check --select E9,F,B code tests && pytest ruff check --select E9,F,B code tests && pytest
``` ```
What the tests cover: The tests need PostgreSQL (`TEST_DATABASE_URL`). What they cover:
- statistics counters; - counters by period;
- mentions and `/all`; - mentions and big-chat limits;
- the monthly reset; - splitting `/all`;
- keyboard layout, reversal and escaping; - the bot's status in groups and its history;
- loading of the bot's handlers. - migration from SQLite;
- keyboard layout and escaping.
CI runs them on Python 3.10 and 3.12.
The Docker image is built on `v*` tags and published to GitHub Packages and `dcr.deev.su`. The Docker image is built on `v*` tags and published to GitHub Packages and `dcr.deev.su`.

View file

@ -13,19 +13,25 @@ Telegram-бот для групповых чатов. Он:
- распознаёт и озвучивает голосовые; - распознаёт и озвучивает голосовые;
- устраивает шуточные ивенты. - устраивает шуточные ивенты.
**Статус:** личный проект, работает с 2021 года · бот [@chat_abobot](https://t.me/chat_abobot) · в базе **Статус:** личный проект, работает с 2021 года, версия 4 · бот [@chat_abobot](https://t.me/chat_abobot) · в базе
бота больше 20 000 пользователей из 45 чатов (октябрь 2026) бота больше 20 000 пользователей из 45 чатов (октябрь 2026)
**Стек:** Python 3.12 · aiogram 3 · pymorphy3 · pyenchant · SpeechRecognition · gTTS · SQLite · Docker **Стек:** Python 3.10+ · aiogram 3 · PostgreSQL (asyncpg) · pymorphy3 · pyenchant · SpeechRecognition · gTTS · Docker
## Возможности ## Возможности
- **Упоминания по имени.** Слова сообщения приводятся к начальной форме (pymorphy3) и сравниваются с - **Упоминания по имени.** Слова сообщения приводятся к начальной форме (pymorphy3) и сравниваются с
именами участников, поэтому участницу Машу позовут и «Маша», и «позови Машу», и «с Машей». Своё имя именами участников, поэтому участницу Машу позовут и «Маша», и «позови Машу», и «с Машей». Своё имя
для упоминаний можно задать командой `/edit`. Имена ищутся и в голосовых до минуты. для упоминаний можно задать командой `/edit`. Имена ищутся и в голосовых до минуты.
- **`/all`** — упомянуть всех участников. - **`/all`** — упомянуть всех участников. Длинный список делится на несколько сообщений.
- **Статистика за всё время и за месяц** (`/stat_group`, `/stat_user`): сообщения, ответы, команды, - **Большие чаты (больше 100 участников).**
ссылки, медиа, стикеры, голосовые и кружочки. Месячная обнуляется в начале месяца. - `/all` — только для администраторов, не чаще раза в 5 минут и только для писавших за 30 дней.
- Одного человека по имени бот зовёт не чаще раза в минуту.
- **Статистика за всё время и по месяцам** (`/stat_group`, `/stat_user`): сообщения, ответы, команды,
ссылки, медиа, стикеры, голосовые и кружочки. Месяцы хранятся, поэтому `/month 2026-09` покажет итоги
любого месяца, а `/top` — самых активных за месяц или за всё время (`/top all`).
- **`/settings`** — переключатели для чата: упоминания по имени, поиск имён в голосовых (голос уходит в
Google), текстовые ивенты, удаление служебных сообщений. Менять могут администраторы.
- **Неправильная раскладка.** Сообщение вида `ghbdtn` бот повторит как «привет». Английские слова он - **Неправильная раскладка.** Сообщение вида `ghbdtn` бот повторит как «привет». Английские слова он
отличает по словарю (pyenchant) и не трогает. отличает по словарю (pyenchant) и не трогает.
- **Голос.** `/recognize` ответом на голосовое — расшифровка; «Озвучь - текст» — голосовое из текста. - **Голос.** `/recognize` ответом на голосовое — расшифровка; «Озвучь - текст» — голосовое из текста.
@ -36,37 +42,56 @@ Telegram-бот для групповых чатов. Он:
- «Подраться с …»; - «Подраться с …»;
- «Чмокнуть» и другие действия с картинками. - «Чмокнуть» и другие действия с картинками.
Отключаются командой `/stop_bot`. Отключаются командой `/stop_bot` или в `/settings`.
- Удаление служебных сообщений (вход, выход, смена названия и фото) — если у бота права администратора. - Удаление служебных сообщений (вход, выход, смена названия и фото) — если у бота права администратора.
- **Учёт бота в группах.** Бот записывает, в каких группах состоит и с какими правами: события Telegram
плюс сверка при запуске и раз в 6 часов. История изменений хранится. Если бота исключили, статистика
группы не удаляется — меняется только отметка, что бота там больше нет.
## Запуск ## Запуск
```bash ```bash
git clone https://github.com/EDeev/chatping_abobot.git && cd chatping_abobot git clone https://github.com/EDeev/chatping_abobot.git && cd chatping_abobot
cp .env.example .env # BOT_TOKEN от @BotFather cp .env.example .env # BOT_TOKEN от @BotFather
docker compose up -d docker compose up -d # бот и PostgreSQL
``` ```
Готовый образ: `docker pull ghcr.io/edeev/chatping_abobot` или `docker pull dcr.deev.su/edeev/chatping_abobot`. Готовый образ: `docker pull ghcr.io/edeev/chatping_abobot` или `docker pull dcr.deev.su/edeev/chatping_abobot`.
Базы SQLite создаются при первом запуске. Таблицы создаются при первом запуске (`code/schema.sql`).
Без Docker нужны Python 3.12, системная библиотека enchant и английский словарь Без Docker нужны:
(`apt install libenchant-2-2 hunspell-en-us`). Затем: `pip install -r requirements.txt` и - Python 3.10+;
`cd code && BOT_TOKEN=… python bot.py`. - PostgreSQL;
- системная библиотека enchant с английским словарём (`apt install libenchant-2-2 hunspell-en-us`).
Затем: `pip install -r requirements.txt` и `cd code && BOT_TOKEN=… DATABASE_URL=postgresql://… python bot.py`.
Перенос данных старой версии (четыре базы SQLite):
`python scripts/migrate_sqlite.py --sqlite-dir путь/к/db --dsn postgresql://…`. Скрипт сверяет суммы после
переноса.
## Развёртывание
[@chat_abobot](https://t.me/chat_abobot) работает на домашнем сервере как systemd-служба: свой venv, настройки
в `/etc/abobot.env`, база — PostgreSQL на том же сервере. Ночной бэкап снимает дамп базы, статистика
выводится в дашборд Metabase.
## Как устроено ## Как устроено
``` ```
code/bot.py запуск и ежемесячное обнуление статистики code/bot.py запуск, отправка ошибок в технический чат, сверка статуса бота в группах
code/handlers.py обработчики сообщений, команд, голосовых и ивентов code/handlers/ роутеры: help, settings, stats, mentions, voice, events, chat (бот в группах, служебные сообщения)
code/script.py учёт статистики, поиск имён, раскладка, переворот текста code/db.py запросы к PostgreSQL
code/sql.py четыре базы SQLite: группы, пользователи, статистика за всё время и за месяц code/schema.sql схема: chats, users, members, chat_stats и member_stats по периодам, bot_status_history
data/ картинки ивентов и приветствие code/nlp.py имена в начальной форме, раскладка, переворот, экранирование
scripts/ перенос данных из SQLite
data/ картинки ивентов и приветствие
``` ```
Статистика участников хранится в отдельной таблице на каждый чат — так устроены рабочие базы бота. Счётчики за всё время и за текущий месяц растут одним запросом (`INSERT … ON CONFLICT DO UPDATE`),
Счётчики увеличиваются одним запросом, поэтому одновременные сообщения не теряются. Распознавание и синтез поэтому одновременные сообщения не теряются. Запросы к базе асинхронные, а распознавание и синтез речи
речи (Google Web Speech и gTTS) идут в отдельном потоке, чтобы бот не замирал. (Google Web Speech и gTTS) идут в отдельном потоке — бот не замирает. Разметка сообщений — HTML,
пользовательский текст экранируется.
## Разработка ## Разработка
@ -75,12 +100,15 @@ pip install -r requirements-dev.txt
ruff check --select E9,F,B code tests && pytest ruff check --select E9,F,B code tests && pytest
``` ```
Что проверяют тесты: Тестам нужен PostgreSQL (`TEST_DATABASE_URL`). Что они проверяют:
- счётчики статистики; - счётчики по периодам;
- упоминания и `/all`; - упоминания и ограничения больших чатов;
- обнуление месячной статистики; - деление `/all` на сообщения;
- раскладку, переворот и экранирование; - статус бота в группах и историю;
- что обработчики бота загружаются. - перенос из SQLite;
- раскладку и экранирование.
CI прогоняет их на Python 3.10 и 3.12.
Docker-образ собирается по тегу `v*` и публикуется в GitHub Packages и `dcr.deev.su`. Docker-образ собирается по тегу `v*` и публикуется в GitHub Packages и `dcr.deev.su`.