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