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.
107 lines
4.0 KiB
Python
107 lines
4.0 KiB
Python
"""Проверка 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']}")
|