Add a Telegram bot client with setup tooling for admin alerts
Bot API client (apps/integration/telegram.py):
- sendMessage, getMe, getUpdates over requests, no extra dependencies
- Telegram API errors are surfaced with the provider description
("chat not found", "bot was blocked") instead of a bare HTTP status
- messages longer than the Bot API limit are truncated with a marker
Notifications:
- notifications.py now goes through the client; failures are logged and
never break the exchange
Setup helpers:
- telegram_check: verifies the token, prints the bot name, sends a test
message, and suggests chats when chat_id is missing
- telegram_chats: lists chats that wrote to the bot, --apply saves the
chat_id when exactly one chat is known
- admin action "Detect chat_id from bot messages" does the same in the UI,
with explicit messages for no chats, many chats and API errors
- admin help text explains the BotFather -> /start -> test flow
Docs: Telegram setup section, command reference and limitations
(4096-char limit, negative chat_id for groups/channels, no internet =
no Telegram).
Tests: 12 new cases for the client, both commands and the admin action;
the suite is 45 passing.
This commit is contained in:
1 parent
e1cc6dbaad
commit
b18e3ea703
7 files changed
+581
-21
No files matched your search
@@ -378,6 +378,42 @@ python manage.py export_api_docs --out ../docs/api-reference.html # автон
|
||||
и `EMAIL_HOST`, `EMAIL_PORT`, `EMAIL_HOST_USER`, `EMAIL_HOST_PASSWORD`, `EMAIL_USE_TLS`
|
||||
(см. `.env.example`).
|
||||
|
||||
#### Telegram-бот: настройка
|
||||
|
||||
Бот работает через Bot API (`api.telegram.org`), библиотеки не нужны —
|
||||
используется только `requests`. Клиент — `apps/integration/telegram.py`
|
||||
(методы `sendMessage`, `getMe`, `getUpdates`).
|
||||
|
||||
1. Создайте бота у [@BotFather](https://t.me/BotFather) командой `/newbot` и
|
||||
скопируйте токен вида `1234567890:AA…`.
|
||||
2. Вставьте токен в админке: «Настройки оповещений об обмене» → поле
|
||||
«токен Telegram-бота».
|
||||
3. Напишите боту `/start` (в группе — любое сообщение; бота нужно добавить
|
||||
в группу). Затем нажмите действие **«Определить chat_id по сообщениям боту»** —
|
||||
оно подставит `chat_id`, если боту писал ровно один чат, иначе покажет список.
|
||||
4. Нажмите **«Отправить тестовое уведомление»** — в чат должно прийти сообщение.
|
||||
|
||||
То же самое из консоли:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python manage.py telegram_check # проверить токен и отправить тест
|
||||
python manage.py telegram_check --no-send # только проверить токен
|
||||
python manage.py telegram_chats # список чатов с их chat_id
|
||||
python manage.py telegram_chats --apply # сохранить chat_id, если чат один
|
||||
```
|
||||
|
||||
Особенности:
|
||||
|
||||
- сообщения отправляются обычным текстом (без Markdown), длиннее 4096 символов
|
||||
обрезаются — так требует Bot API;
|
||||
- ошибки Telegram (`chat not found`, `bot was blocked`, `Forbidden`) попадают
|
||||
в лог приложения и в сообщение админки, но не ломают обмен;
|
||||
- `chat_id` группы или канала — отрицательное число, например `-1001234567890`;
|
||||
- для канала бот должен быть администратором с правом публикации;
|
||||
- если сервер без выхода в интернет, Telegram-канал не заработает —
|
||||
нужен прокси или разрешённый исходящий доступ к `api.telegram.org:443`.
|
||||
|
||||
---
|
||||
|
||||
## 7. Платежи
|
||||
|
||||
Reference in new issue
Block a user