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
@@ -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']})."
|
||||
)
|
||||
)
|
||||
Reference in new issue
Block a user