fix: sanitize daily report HTML for Telegram parse_mode

Strip div/br tags unsupported by Telegram API; reports still store UI HTML in details

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-05-29 16:35:04 +10:00
parent 0baeacf808
commit 2670c8cb46
4 changed files with 37 additions and 9 deletions
+22 -6
View File
@@ -3,6 +3,7 @@
from __future__ import annotations
import html
import re
from datetime import datetime
from typing import Any
@@ -20,6 +21,25 @@ LOGON_TYPE_NAMES: dict[int, str] = {
}
# Telegram parse_mode=HTML: только теги из Bot API (без div/br/p и т.д.)
_TELEGRAM_BR = re.compile(r"<br\s*/?>", re.I)
_TELEGRAM_DROP_TAGS = re.compile(
r"</?(?:div|p|ul|ol|li|hr|h[1-6]|table|tr|td|th|thead|tbody|body|html|head)\b[^>]*>",
re.I,
)
_TELEGRAM_SPAN_OPEN = re.compile(r"<span\b(?![^>]*\btg-spoiler\b)[^>]*>", re.I)
_TELEGRAM_SPAN_CLOSE = re.compile(r"</span>", re.I)
def sanitize_telegram_html(text: str) -> str:
"""Приводит HTML отчёта (UI/агент) к тегам, допустимым в Telegram."""
out = _TELEGRAM_BR.sub("\n", text)
out = _TELEGRAM_DROP_TAGS.sub("", out)
out = _TELEGRAM_SPAN_OPEN.sub("", out)
out = _TELEGRAM_SPAN_CLOSE.sub("", out)
return out.strip()
def html_escape(value: Any) -> str:
if value is None:
return ""
@@ -163,15 +183,11 @@ def format_daily_report_html(event: Event) -> str:
details = _details_dict(event)
report_html = details.get("report_html")
if isinstance(report_html, str) and report_html.strip():
# Уже HTML от агента или SAC
return report_html.strip()
return sanitize_telegram_html(report_html.strip())
body = _detail(details, "report_body", default=event.summary)
if body != "-":
escaped = html.escape(body)
return (
f"<b>📊 {html_escape(event.title)}</b>\n"
f'<div class="agent-report">{escaped.replace(chr(10), "<br>")}</div>'
)
return f"<b>📊 {html_escape(event.title)}</b>\n{escaped}"
return format_generic_event_html(event)