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:
apuc committed 2026-11-22 22:25:13 +03:00
1 parent e1cc6dbaad
commit b18e3ea703
7 files changed
+581 -21

No files matched your search

+57 -4
View File
@@ -11,6 +11,7 @@ from .models import (
)
from .notifications import send_alert
from .services import stop_sync_run
from .telegram import TelegramError, recent_chats
class SyncLogInline(admin.TabularInline):
@@ -188,9 +189,13 @@ class NotificationSettingsAdmin(admin.ModelAdmin):
{
"fields": ("telegram_bot_token", "telegram_chat_id"),
"description": (
"Создайте бота у @BotFather, получите токен и укажите chat_id "
"чата или канала. Если хотя бы одно поле пустое — Telegram "
"не используется."
"1. Создайте бота у @BotFather и вставьте токен.<br>"
"2. Напишите боту /start (в группе — любое сообщение) и нажмите "
"действие «Определить chat_id по сообщениям боту».<br>"
"3. Проверьте канал действием «Отправить тестовое уведомление».<br>"
"Те же шаги есть командами: <code>telegram_check</code> и "
"<code>telegram_chats --apply</code>. Если хотя бы одно поле "
"пустое — Telegram не используется."
),
},
),
@@ -201,7 +206,7 @@ class NotificationSettingsAdmin(admin.ModelAdmin):
("Служебное", {"fields": ("updated_at",)}),
)
readonly_fields = ("updated_at",)
actions = ("send_test_alert",)
actions = ("send_test_alert", "detect_chat_id")
def has_add_permission(self, request):
return not NotificationSettings.objects.exists()
@@ -209,6 +214,54 @@ class NotificationSettingsAdmin(admin.ModelAdmin):
def has_delete_permission(self, request, obj=None):
return False
@admin.action(description="Определить chat_id по сообщениям боту")
def detect_chat_id(self, request, queryset):
"""Fills chat_id from the chats that wrote to the bot."""
for config in queryset:
if not config.telegram_bot_token:
self.message_user(
request,
"Сначала укажите токен бота — без него Telegram не ответит.",
level="error",
)
continue
try:
chats = recent_chats(config.telegram_bot_token)
except TelegramError as exc:
self.message_user(
request, f"Не удалось получить чаты: {exc}", level="error"
)
continue
if not chats:
self.message_user(
request,
"Боту ещё никто не писал. Откройте бота в Telegram, "
"отправьте /start и повторите действие.",
level="warning",
)
continue
if len(chats) == 1:
config.telegram_chat_id = chats[0]["id"]
config.save(update_fields=["telegram_chat_id", "updated_at"])
self.message_user(
request,
f"chat_id сохранён: {chats[0]['id']} ({chats[0]['title']}).",
)
continue
listing = "; ".join(
f"{chat['title']} — {chat['id']}" for chat in chats[:5]
)
self.message_user(
request,
f"Боту писали {len(chats)} чата, автоматически выбрать нельзя. "
f"Укажите нужный id вручную: {listing}",
level="warning",
)
@admin.action(description="Отправить тестовое уведомление")
def send_test_alert(self, request, queryset):
result = send_alert(
@@ -0,0 +1,76 @@
"""Поиск chat_id: кто из чатов писал боту."""
from django.core.management.base import BaseCommand, CommandError
from apps.integration.models import NotificationSettings
from apps.integration.telegram import TelegramError, recent_chats
class Command(BaseCommand):
help = (
"Показывает чаты, которые писали боту, чтобы узнать chat_id "
"для оповещений о сбоях обмена."
)
def add_arguments(self, parser):
parser.add_argument(
"--token",
default="",
help="Токен бота. По умолчанию — из настроек оповещений.",
)
parser.add_argument(
"--apply",
action="store_true",
help="Сохранить chat_id в настройки, если боту писал ровно один чат.",
)
def handle(self, *args, **options):
config = NotificationSettings.load()
token = options["token"] or config.telegram_bot_token
if not token:
raise CommandError(
"Не задан токен бота. Укажите его в админке или через --token."
)
try:
chats = recent_chats(token)
except TelegramError as exc:
raise CommandError(f"Telegram недоступен: {exc}") from exc
if not chats:
self.stdout.write(
self.style.WARNING(
"Боту ещё никто не писал. Откройте бота в Telegram, "
"отправьте /start (в группе — любое сообщение или /start@бот) "
"и повторите команду."
)
)
return
self.stdout.write("Чаты, которые писали боту (новые сверху):")
for chat in chats:
username = f" @{chat['username']}" if chat["username"] else ""
self.stdout.write(
f" {chat['id']:>16} {chat['type']:<8} {chat['title']}{username}"
)
if not options["apply"]:
self.stdout.write(
"\nСкопируйте нужный id в поле «chat_id в Telegram» в админке "
"или запустите команду с --apply, если чат один."
)
return
if len(chats) > 1:
raise CommandError(
f"Боту писали {len(chats)} чата — автоматически выбрать нельзя. "
"Укажите chat_id в админке вручную."
)
config.telegram_chat_id = chats[0]["id"]
config.save(update_fields=["telegram_chat_id", "updated_at"])
self.stdout.write(
self.style.SUCCESS(
f"chat_id сохранён в настройки: {chats[0]['id']} ({chats[0]['title']})."
)
)
@@ -0,0 +1,106 @@
"""Проверка Telegram-бота: токен, имя бота и тестовое сообщение."""
from django.core.management.base import BaseCommand, CommandError
from apps.integration.models import NotificationSettings
from apps.integration.telegram import (
TelegramError,
get_me,
recent_chats,
send_message,
)
class Command(BaseCommand):
help = (
"Проверяет токен Telegram-бота и отправляет тестовое сообщение "
"в настроенный чат."
)
def add_arguments(self, parser):
parser.add_argument(
"--token",
default="",
help="Токен бота. По умолчанию — из настроек оповещений.",
)
parser.add_argument(
"--chat-id",
default="",
help="chat_id получателя. По умолчанию — из настроек оповещений.",
)
parser.add_argument(
"--no-send",
action="store_true",
help="Только проверить токен, без отправки сообщения.",
)
def handle(self, *args, **options):
config = NotificationSettings.load()
token = options["token"] or config.telegram_bot_token
chat_id = options["chat_id"] or config.telegram_chat_id
if not token:
raise CommandError(
"Не задан токен бота. Укажите его в админке "
"(«Настройки оповещений об обмене») или через --token."
)
try:
bot = get_me(token)
except TelegramError as exc:
raise CommandError(f"Токен не принят Telegram: {exc}") from exc
username = bot.get("username", "")
self.stdout.write(
self.style.SUCCESS(
f"Бот найден: @{username} (id {bot.get('id')}, "
f"{bot.get('first_name', '')})"
)
)
if options["no_send"]:
return
if not chat_id:
self.stdout.write(
self.style.WARNING(
"chat_id не задан — отправить тестовое сообщение некуда.\n"
"Напишите боту любое сообщение и запустите "
"`python manage.py telegram_chats --apply`."
)
)
try:
chats = recent_chats(token)
except TelegramError as exc:
self.stdout.write(f"Список чатов получить не удалось: {exc}")
return
self._print_chats(chats)
return
try:
send_message(
token,
chat_id,
"HOMM: проверка канала оповещений. Если вы видите это сообщение, "
"оповещения о сбоях обмена будут приходить сюда.",
)
except TelegramError as exc:
raise CommandError(
f"Сообщение не отправлено в чат {chat_id}: {exc}. "
"Проверьте, что бот добавлен в чат и chat_id верный."
) from exc
self.stdout.write(
self.style.SUCCESS(f"Тестовое сообщение отправлено в чат {chat_id}.")
)
def _print_chats(self, chats):
if not chats:
self.stdout.write(
"Боту ещё никто не писал. Откройте бота в Telegram, "
"отправьте /start и повторите команду."
)
return
self.stdout.write("Чаты, которые писали боту:")
for chat in chats:
self.stdout.write(f" {chat['id']:>16} {chat['type']:<8} {chat['title']}")
+9 -14
View File
@@ -8,17 +8,15 @@ exchange itself, so every transport swallows its own errors and only logs them.
import logging
import requests
from django.conf import settings
from django.core.mail import send_mail
from django.utils import timezone
from .models import NotificationSettings
from .telegram import TelegramError, send_message
logger = logging.getLogger(__name__)
TELEGRAM_API_URL = "https://api.telegram.org/bot{token}/sendMessage"
TELEGRAM_TIMEOUT = 10
ADMIN_SYNC_URL = "/admin/integration/syncrun/{pk}/change/"
@@ -43,21 +41,18 @@ def _send_email(config: NotificationSettings, subject: str, message: str) -> boo
def _send_telegram(config: NotificationSettings, subject: str, message: str) -> bool:
if not config.telegram_configured:
return False
url = TELEGRAM_API_URL.format(token=config.telegram_bot_token)
try:
response = requests.post(
url,
json={
"chat_id": config.telegram_chat_id,
"text": f"{subject}\n\n{message}",
"disable_web_page_preview": True,
},
timeout=TELEGRAM_TIMEOUT,
send_message(
config.telegram_bot_token,
config.telegram_chat_id,
f"{subject}\n\n{message}",
)
response.raise_for_status()
except Exception as exc: # noqa: BLE001 - alerting must never break the workflow
except TelegramError as exc: # noqa: BLE001 - alerting must never break the workflow
logger.warning("Не удалось отправить оповещение в Telegram: %s", exc)
return False
except Exception: # noqa: BLE001 - safety net for unexpected transport errors
logger.exception("Непредвиденная ошибка при отправке в Telegram")
return False
return True
+106
View File
@@ -0,0 +1,106 @@
"""Minimal Telegram Bot API client used for administrator alerts.
Only three Bot API methods are needed:
* ``sendMessage`` — deliver an alert;
* ``getMe`` — verify the token and show the bot name;
* ``getUpdates`` — find the ``chat_id`` of a chat that wrote to the bot.
The client is intentionally tiny: no polling loop, no webhook, no dependencies
beyond ``requests``.
"""
import logging
import requests
logger = logging.getLogger(__name__)
API_ROOT = "https://api.telegram.org"
TIMEOUT = 10
MAX_MESSAGE_LENGTH = 4096
TRUNCATION_SUFFIX = "\n… (сообщение обрезано)"
class TelegramError(Exception):
"""Raised when the Bot API rejects a call or is unreachable."""
def _call(method: str, token: str, payload: dict, timeout: int = TIMEOUT) -> object:
"""Calls a Bot API method and returns its ``result`` field."""
if not token:
raise TelegramError("не задан токен Telegram-бота")
url = f"{API_ROOT}/bot{token}/{method}"
try:
response = requests.post(url, json=payload, timeout=timeout)
except requests.RequestException as exc:
raise TelegramError(f"Telegram недоступен: {exc}") from exc
try:
data = response.json()
except ValueError:
data = {}
if response.status_code != 200 or not data.get("ok"):
description = data.get("description") or f"HTTP {response.status_code}"
raise TelegramError(f"Telegram API: {description}")
return data.get("result")
def get_me(token: str) -> dict:
"""Returns the bot description: id, username, first_name."""
return _call("getMe", token, {}) or {}
def send_message(token: str, chat_id: str, text: str) -> dict:
"""Sends a plain-text message. Long messages are truncated to 4096 chars."""
if len(text) > MAX_MESSAGE_LENGTH:
cut = MAX_MESSAGE_LENGTH - len(TRUNCATION_SUFFIX)
text = text[:cut] + TRUNCATION_SUFFIX
return _call(
"sendMessage",
token,
{
"chat_id": str(chat_id),
"text": text,
"disable_web_page_preview": True,
},
) or {}
def get_updates(token: str, limit: int = 50, offset: int | None = None) -> list:
"""Returns recent updates — used to discover chat ids."""
payload: dict = {"limit": limit, "timeout": 0, "allowed_updates": ["message"]}
if offset is not None:
payload["offset"] = offset
return _call("getUpdates", token, payload) or []
def recent_chats(token: str, limit: int = 50) -> list[dict]:
"""Returns chats that wrote to the bot, newest first, without duplicates."""
seen: dict[str, dict] = {}
for update in get_updates(token, limit=limit):
message = update.get("message") or update.get("edited_message") or {}
chat = message.get("chat")
if not chat:
continue
chat_id = str(chat.get("id"))
if chat_id in seen:
continue
seen[chat_id] = {
"id": chat_id,
"type": chat.get("type", ""),
"title": (
chat.get("title")
or " ".join(
part
for part in [chat.get("first_name"), chat.get("last_name")]
if part
)
or chat.get("username")
or chat_id
),
"username": chat.get("username", ""),
}
return list(seen.values())
+191 -3
View File
@@ -1,17 +1,24 @@
from decimal import Decimal
from io import StringIO
from unittest import mock
import requests
from django.conf import settings
from django.contrib import admin
from django.core import mail
from django.test import TestCase, override_settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.test import RequestFactory, TestCase, override_settings
from django.utils import timezone
from rest_framework.test import APIClient
from apps.catalog.models import Product
from apps.orders.models import Order
from .admin import NotificationSettingsAdmin
from .models import NotificationSettings, OutboxMessage, SyncLog, SyncRun
from .services import process_outbox, pull_catalog_from_1c, stop_sync_run
from .telegram import TelegramError, get_me, recent_chats, send_message
class IntegrationApiTests(TestCase):
@@ -197,9 +204,11 @@ class ExchangeAlertTests(TestCase):
side_effect=RuntimeError("1C недоступна"),
):
with mock.patch(
"apps.integration.notifications.requests.post"
"apps.integration.telegram.requests.post"
) as post:
post.return_value.raise_for_status.return_value = None
response = post.return_value
response.status_code = 200
response.json.return_value = {"ok": True, "result": {"message_id": 1}}
with self.assertRaises(RuntimeError):
pull_catalog_from_1c()
@@ -264,3 +273,182 @@ class StopSyncRunTests(TestCase):
revoke.assert_not_called()
run.refresh_from_db()
self.assertEqual(run.status, SyncRun.Status.RUNNING)
class TelegramClientTests(TestCase):
def _response(self, status=200, payload=None):
response = mock.Mock()
response.status_code = status
response.json.return_value = payload or {"ok": True, "result": {}}
return response
@mock.patch("apps.integration.telegram.requests.post")
def test_send_message_posts_to_bot_api(self, post):
post.return_value = self._response(
payload={"ok": True, "result": {"message_id": 7}}
)
send_message("123:ABC", "-100500", "Привет")
self.assertEqual(
post.call_args.args[0],
"https://api.telegram.org/bot123:ABC/sendMessage",
)
payload = post.call_args.kwargs["json"]
self.assertEqual(payload["chat_id"], "-100500")
self.assertEqual(payload["text"], "Привет")
self.assertTrue(payload["disable_web_page_preview"])
@mock.patch("apps.integration.telegram.requests.post")
def test_long_message_is_truncated(self, post):
post.return_value = self._response()
send_message("123:ABC", "1", "а" * 5000)
text = post.call_args.kwargs["json"]["text"]
self.assertEqual(len(text), 4096)
self.assertTrue(text.endswith("(сообщение обрезано)"))
@mock.patch("apps.integration.telegram.requests.post")
def test_api_error_is_reported_with_description(self, post):
post.return_value = self._response(
status=400,
payload={"ok": False, "description": "Bad Request: chat not found"},
)
with self.assertRaises(TelegramError) as ctx:
send_message("123:ABC", "1", "текст")
self.assertIn("chat not found", str(ctx.exception))
@mock.patch("apps.integration.telegram.requests.post")
def test_network_error_is_wrapped(self, post):
post.side_effect = requests.RequestException("нет сети")
with self.assertRaises(TelegramError) as ctx:
get_me("123:ABC")
self.assertIn("Telegram недоступен", str(ctx.exception))
def test_missing_token_is_rejected(self):
with self.assertRaises(TelegramError):
send_message("", "1", "текст")
@mock.patch("apps.integration.telegram.requests.post")
def test_recent_chats_dedupes_and_names_private_chats(self, post):
post.return_value = self._response(
payload={
"ok": True,
"result": [
{
"message": {
"chat": {
"id": 111,
"type": "private",
"first_name": "Иван",
"last_name": "Петров",
}
}
},
{"message": {"chat": {"id": 111, "type": "private"}}},
{
"message": {
"chat": {"id": -100500, "type": "channel", "title": "HOMM"}
}
},
],
}
)
chats = recent_chats("123:ABC")
self.assertEqual([chat["id"] for chat in chats], ["111", "-100500"])
self.assertEqual(chats[0]["title"], "Иван Петров")
self.assertEqual(chats[1]["title"], "HOMM")
class TelegramCommandTests(TestCase):
def setUp(self):
self.config = NotificationSettings.load()
self.config.telegram_bot_token = "123:ABC"
self.config.telegram_chat_id = "-100500"
self.config.save()
@mock.patch("apps.integration.management.commands.telegram_check.recent_chats")
@mock.patch("apps.integration.management.commands.telegram_check.send_message")
@mock.patch("apps.integration.management.commands.telegram_check.get_me")
def test_check_sends_test_message(self, get_me, send_message_mock, chats):
get_me.return_value = {"id": 1, "username": "homm_bot", "first_name": "HOMM"}
chats.return_value = []
out = StringIO()
call_command("telegram_check", stdout=out)
text = out.getvalue()
self.assertIn("Бот найден: @homm_bot", text)
self.assertIn("Тестовое сообщение отправлено", text)
send_message_mock.assert_called_once()
self.assertEqual(send_message_mock.call_args.args[1], "-100500")
def test_check_without_token_fails(self):
self.config.telegram_bot_token = ""
self.config.save()
with self.assertRaises(CommandError):
call_command("telegram_check", stdout=StringIO())
@mock.patch("apps.integration.management.commands.telegram_check.send_message")
@mock.patch("apps.integration.management.commands.telegram_check.get_me")
def test_check_with_telegram_error_fails_clearly(self, get_me, send):
get_me.return_value = {"id": 1, "username": "homm_bot"}
send.side_effect = TelegramError("Telegram API: chat not found")
with self.assertRaises(CommandError) as ctx:
call_command("telegram_check", stdout=StringIO())
self.assertIn("chat not found", str(ctx.exception))
@mock.patch("apps.integration.management.commands.telegram_chats.recent_chats")
def test_chats_apply_saves_single_chat(self, chats):
chats.return_value = [
{"id": "-100777", "type": "group", "title": "HOMM ops", "username": ""}
]
call_command("telegram_chats", "--apply", stdout=StringIO())
self.config.refresh_from_db()
self.assertEqual(self.config.telegram_chat_id, "-100777")
@mock.patch("apps.integration.management.commands.telegram_chats.recent_chats")
def test_chats_apply_requires_single_chat(self, chats):
chats.return_value = [
{"id": "1", "type": "private", "title": "Иван", "username": ""},
{"id": "2", "type": "private", "title": "Пётр", "username": ""},
]
with self.assertRaises(CommandError):
call_command("telegram_chats", "--apply", stdout=StringIO())
class TelegramAdminActionTests(TestCase):
def test_detect_chat_id_saves_single_chat(self):
config = NotificationSettings.load()
config.telegram_bot_token = "123:ABC"
config.save()
model_admin = NotificationSettingsAdmin(NotificationSettings, admin.site)
request = RequestFactory().get("/admin/integration/notificationsettings/")
with mock.patch.object(model_admin, "message_user") as message_user:
with mock.patch(
"apps.integration.admin.recent_chats",
return_value=[
{"id": "-100900", "title": "HOMM alerts", "type": "group", "username": ""}
],
):
model_admin.detect_chat_id(request, NotificationSettings.objects.all())
config.refresh_from_db()
self.assertEqual(config.telegram_chat_id, "-100900")
message_user.assert_called_once()
self.assertIn("chat_id сохранён", message_user.call_args.args[1])
+36
View File
@@ -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. Платежи