|
1 | 1 | # Telegram Abridger Userbot |
2 | 2 |
|
3 | | -[English version](README_en.md) |
| 3 | +**English** · [中文](README.zh-CN.md) · [Русский](README.ru.md) |
4 | 4 |
|
5 | | -## Что делает бот |
6 | | - |
7 | | -Юзербот входит в Telegram от имени пользователя и следит за входящими сообщениями во всех чатах, которые не заглушены и не находятся в архиве (чаты с topics игнорируются). |
8 | | - |
9 | | -Для каждого отправителя ведётся скользящее окно `COOLDOWN_INTERVAL` секунд: |
10 | | - |
11 | | -- Все входящие сообщения автоматически отмечаются прочитанными и накапливаются в буфер |
12 | | -- Когда окно истекает, буфер склеивается через `MESSAGE_CONCAT_STRING` и отправляется в тот же чат без уведомления (silently); если задан `SUMMARY_PREFIX`, он добавляется в начало (`%d` → число сообщений) |
13 | | -- Если отправитель превышает `MESSAGE_FREQUENCY_LIMIT` сообщений за окно, он сразу заглушается на `MUTE_TIMEOUT` секунд, а накопленный буфер отправляется досрочно |
14 | | -- Если за `COOLDOWN_INTERVAL` в том же чате были исходящие сообщения (т.е. пользователь сам отвечал), суммари не отправляется — это нормальный ход разговора |
| 5 | +A self-account (MTProto) userbot that watches incoming messages, buffers them per sender over a sliding window, and—when a sender floods the window—joins the buffered messages into one silent summary and mutes the sender's notifications. If you reply in the chat yourself, the summary is suppressed: the conversation is clearly active. |
15 | 6 |
|
16 | 7 | ## Requirements |
17 | 8 |
|
18 | | -- Python 3.10+ |
19 | | -- `telethon` |
| 9 | +- Python 3.11+ |
| 10 | +- [uv](https://docs.astral.sh/uv/) |
20 | 11 | - Telegram API credentials (`API_ID`, `API_HASH`) |
21 | 12 |
|
22 | | -### Получение API_ID и API_HASH |
| 13 | +### Getting API_ID and API_HASH |
23 | 14 |
|
24 | | -1. Открыть https://my.telegram.org и войти по номеру телефона |
25 | | -2. Перейти в **API development tools** |
26 | | -3. Создать приложение (название и платформа — любые) |
27 | | -4. Скопировать `App api_id` → `API_ID` и `App api_hash` → `API_HASH` |
| 15 | +1. Go to https://my.telegram.org and sign in with your phone number |
| 16 | +2. Navigate to **API development tools** |
| 17 | +3. Create an application (name and platform can be anything) |
| 18 | +4. Copy `App api_id` → `API_ID` and `App api_hash` → `API_HASH` |
28 | 19 |
|
29 | | -### Config (env vars or `.env`) |
| 20 | +### Configuration (environment variables or `.env`) |
30 | 21 |
|
31 | 22 | | Variable | Default | Description | |
32 | | -|---|---|---| |
33 | | -| `API_ID` | — | Telegram API ID | |
34 | | -| `API_HASH` | — | Telegram API Hash | |
35 | | -| `COOLDOWN_INTERVAL` | `300` | Окно наблюдения в секундах | |
36 | | -| `MESSAGE_FREQUENCY_LIMIT` | `5` | Макс. сообщений за окно до mute | |
37 | | -| `MESSAGE_CONCAT_STRING` | `, ` | Разделитель при склейке сообщений | |
38 | | -| `MUTE_TIMEOUT` | `3600` | Длительность mute в секундах | |
39 | | -| `SUMMARY_PREFIX` | _(нет)_ | Префикс перед склеенным сообщением; `%d` заменяется числом сообщений (например, `"Собрано %d сообщений:\n"`) | |
| 23 | +| --- | --- | --- | |
| 24 | +| `API_ID` | — | Telegram API ID (required) | |
| 25 | +| `API_HASH` | — | Telegram API hash (required) | |
| 26 | +| `COOLDOWN_INTERVAL` | `300` | Observation window in seconds | |
| 27 | +| `MESSAGE_FREQUENCY_LIMIT` | `5` | Max messages per window before muting | |
| 28 | +| `MESSAGE_CONCAT_STRING` | `, ` | Delimiter used to join buffered messages | |
| 29 | +| `MUTE_TIMEOUT` | `3600` | Mute duration in seconds | |
| 30 | +| `SUMMARY_PREFIX` | _(none)_ | Optional prefix prepended to the summary; `%d` is replaced with the message count (e.g. `"I've put together your %d messages:\n"`) | |
| 31 | +| `SESSION` | `userbot` | Telethon session name or path; auth is stored at `$SESSION.session` | |
40 | 32 |
|
41 | 33 | ## Usage |
42 | 34 |
|
43 | 35 | ```bash |
44 | | -cp .env.example .env # заполни API_ID и API_HASH |
| 36 | +cp .env.example .env # fill in API_ID and API_HASH |
45 | 37 | uv run bot.py |
46 | 38 | ``` |
47 | 39 |
|
48 | | -`uv` сам установит зависимости из inline-метаданных скрипта (PEP 723) в изолированное окружение. |
| 40 | +`uv run` resolves and installs the dependencies from `pyproject.toml`/`uv.lock` into an isolated environment automatically — no manual setup is needed. |
| 41 | + |
| 42 | +On first run, Telethon will prompt for your phone number and a confirmation code, then write a `*.session` file. That file holds your authentication secret — keep it private and never commit it. |
| 43 | + |
| 44 | +## Running in a container |
| 45 | + |
| 46 | +The image builds dependencies in a `uv` stage and ships a slim, non-root runtime. The session is persisted on the `/data` volume so authentication survives restarts. |
| 47 | + |
| 48 | +```bash |
| 49 | +# Build |
| 50 | +docker build --tag telegram-abridger --file Containerfile . |
| 51 | + |
| 52 | +# First run: authenticate interactively, persisting the session to a named volume |
| 53 | +docker run --interactive --tty \ |
| 54 | + --env-file .env \ |
| 55 | + --volume abridger-session:/data \ |
| 56 | + telegram-abridger |
| 57 | + |
| 58 | +# Subsequent runs (already authenticated) |
| 59 | +docker run --detach --restart unless-stopped \ |
| 60 | + --env-file .env \ |
| 61 | + --volume abridger-session:/data \ |
| 62 | + telegram-abridger |
| 63 | +``` |
| 64 | + |
| 65 | +The image sets `SESSION=/data/userbot`; leave `SESSION` unset in your `.env` so the session lands on the volume. |
| 66 | + |
| 67 | +## How it works |
| 68 | + |
| 69 | +The userbot monitors incoming messages from non-muted, non-archived chats (forum/topics chats are excluded). For each sender it maintains a sliding window of `COOLDOWN_INTERVAL` seconds: |
49 | 70 |
|
50 | | -При первом запуске Telethon запросит номер телефона и код подтверждения. |
| 71 | +- Incoming messages are marked as read and added to a per-sender buffer |
| 72 | +- If a sender exceeds `MESSAGE_FREQUENCY_LIMIT` messages within the window, they are muted for `MUTE_TIMEOUT` seconds via Telegram's notification settings and their buffer is flushed immediately |
| 73 | +- Buffered messages are concatenated with `MESSAGE_CONCAT_STRING` and sent silently in the same chat; if `SUMMARY_PREFIX` is set, it is prepended to the summary (`%d` → message count) |
| 74 | +- Buffers are also flushed periodically once a sender's window goes quiet |
| 75 | +- If you sent any message in the same chat within `COOLDOWN_INTERVAL`, the summary is suppressed — the conversation is already active |
| 76 | + |
| 77 | +## Development |
| 78 | + |
| 79 | +```bash |
| 80 | +uv sync # install runtime + dev dependencies |
| 81 | +uv run pytest # run the test suite |
| 82 | +uv run ruff check . && uv run ruff format --check . |
| 83 | +uv run mypy bot.py |
| 84 | +``` |
51 | 85 |
|
52 | | -## Output / Result Files |
| 86 | +## Output / result files |
53 | 87 |
|
54 | | -- `userbot.session` — файл сессии Telethon (не коммитить) |
55 | | -- Логи выводятся в stdout |
| 88 | +- `$SESSION.session` (default `userbot.session`) — Telethon session file (do not commit) |
| 89 | +- Logs go to stdout |
0 commit comments