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(