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.
125 lines
4.6 KiB
Python
125 lines
4.6 KiB
Python
"""Delivery of critical exchange alerts to administrators.
|
||
|
||
Admins configure the channels in the admin panel
|
||
(:class:`apps.integration.models.NotificationSettings`): email, Telegram or
|
||
both. Alerts are best-effort — a failure to notify must never break the
|
||
exchange itself, so every transport swallows its own errors and only logs them.
|
||
"""
|
||
|
||
import logging
|
||
|
||
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__)
|
||
|
||
ADMIN_SYNC_URL = "/admin/integration/syncrun/{pk}/change/"
|
||
|
||
|
||
def _send_email(config: NotificationSettings, subject: str, message: str) -> bool:
|
||
recipients = config.email_list()
|
||
if not recipients:
|
||
return False
|
||
try:
|
||
send_mail(
|
||
subject,
|
||
message,
|
||
settings.DEFAULT_FROM_EMAIL,
|
||
recipients,
|
||
fail_silently=False,
|
||
)
|
||
except Exception: # noqa: BLE001 - alerting must never break the workflow
|
||
logger.exception("Не удалось отправить оповещение на email: %s", recipients)
|
||
return False
|
||
return True
|
||
|
||
|
||
def _send_telegram(config: NotificationSettings, subject: str, message: str) -> bool:
|
||
if not config.telegram_configured:
|
||
return False
|
||
try:
|
||
send_message(
|
||
config.telegram_bot_token,
|
||
config.telegram_chat_id,
|
||
f"{subject}\n\n{message}",
|
||
)
|
||
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
|
||
|
||
|
||
def send_alert(subject: str, message: str) -> dict[str, bool]:
|
||
"""Sends an alert through every configured channel.
|
||
|
||
Returns which transports actually delivered the message.
|
||
"""
|
||
config = NotificationSettings.load()
|
||
result = {"enabled": config.is_enabled, "email": False, "telegram": False}
|
||
logger.warning("Оповещение обмена: %s | %s", subject, message)
|
||
if not config.is_enabled:
|
||
return result
|
||
|
||
result["email"] = _send_email(config, subject, message)
|
||
result["telegram"] = _send_telegram(config, subject, message)
|
||
return result
|
||
|
||
|
||
def notify_sync_failed(run) -> dict[str, bool]:
|
||
"""Reports a failed exchange session."""
|
||
config = NotificationSettings.load()
|
||
if not config.notify_catalog_failure:
|
||
return {"enabled": False, "email": False, "telegram": False}
|
||
|
||
finished = run.finished_at or timezone.now()
|
||
duration = ""
|
||
if run.started_at:
|
||
seconds = int((finished - run.started_at).total_seconds())
|
||
duration = f"{seconds} с"
|
||
|
||
subject = f"[HOMM] Сбой обмена с 1С: {run.get_entity_display()}"
|
||
message = "\n".join(
|
||
[
|
||
f"Процесс: {run.get_entity_display()} ({run.get_direction_display()})",
|
||
f"Статус: {run.get_status_display()}",
|
||
f"Начало: {run.started_at:%d.%m.%Y %H:%M:%S}",
|
||
f"Длительность: {duration or '—'}",
|
||
f"Ошибка: {run.error or 'без текста'}",
|
||
f"Сеанс: #{run.pk}",
|
||
f"Админка: {ADMIN_SYNC_URL.format(pk=run.pk)}",
|
||
]
|
||
)
|
||
return send_alert(subject, message)
|
||
|
||
|
||
def notify_outbox_dead(message, attempts_limit: int = 5) -> dict[str, bool]:
|
||
"""Reports an outbox message that exhausted its retries."""
|
||
config = NotificationSettings.load()
|
||
if not config.notify_outbox_dead:
|
||
return {"enabled": False, "email": False, "telegram": False}
|
||
|
||
order_id = (message.payload or {}).get("order_id")
|
||
order_hint = f"Заказ в базе: #{order_id}" if order_id else ""
|
||
subject = "[HOMM] Заказ не доставлен в 1С"
|
||
text = "\n".join(
|
||
part
|
||
for part in [
|
||
f"Сообщение: {message.topic}",
|
||
f"Попыток: {message.attempts} из {attempts_limit}",
|
||
f"Последняя ошибка: {message.last_error or 'без текста'}",
|
||
order_hint,
|
||
f"Сообщение outbox: #{message.pk}",
|
||
"Админка: /admin/integration/outboxmessage/",
|
||
"Проверьте доступность 1С и повторите отправку из админки.",
|
||
]
|
||
if part
|
||
)
|
||
return send_alert(subject, text)
|