fix(telegram): harden detail history html fallback
This commit is contained in:
@@ -342,7 +342,7 @@ def _telegram_html_chunks(lines: list[str], limit: int = _TELEGRAM_HTML_CHUNK_LI
|
||||
current = []
|
||||
current_len = 0
|
||||
if line_len > limit:
|
||||
chunks.append(line[:limit])
|
||||
chunks.append(_html_safe_plain_chunk(line, limit=limit))
|
||||
continue
|
||||
current.append(line)
|
||||
current_len += line_len
|
||||
@@ -357,6 +357,17 @@ def _plain_text_from_html(text: str, limit: int = 3900) -> str:
|
||||
return html.unescape(plain)[:limit]
|
||||
|
||||
|
||||
def _html_safe_plain_chunk(text: str, limit: int) -> str:
|
||||
"""Render one overlong HTML line as parse-safe text for HTML mode chunks."""
|
||||
plain = _plain_text_from_html(text, limit=limit)
|
||||
escaped = html.escape(plain)
|
||||
if len(escaped) <= limit:
|
||||
return escaped
|
||||
# Escaping may expand &, <, >. Trim once more after escaping; a partial HTML
|
||||
# entity is still plain text to Telegram, while a partial tag is not.
|
||||
return escaped[:limit]
|
||||
|
||||
|
||||
def _sanitize_telegram_error(text: str) -> str:
|
||||
"""遮蔽 Telegram Bot URL 中的 token,避免例外字串污染 log / trace。"""
|
||||
return _TELEGRAM_BOT_URL_RE.sub(r"\1<redacted>", text)
|
||||
@@ -5920,13 +5931,29 @@ class TelegramGateway:
|
||||
Returns:
|
||||
dict: API 回應
|
||||
"""
|
||||
payload_text = text[:500]
|
||||
payload_parse_mode = parse_mode
|
||||
if parse_mode and parse_mode.upper() == "HTML" and len(text) > 500:
|
||||
payload_text = _plain_text_from_html(text, limit=500)
|
||||
payload_parse_mode = None
|
||||
|
||||
payload = {
|
||||
"chat_id": chat_id or self.alert_chat_id,
|
||||
"text": text[:500], # SOUL.md 字數限制
|
||||
"parse_mode": parse_mode,
|
||||
"text": payload_text, # SOUL.md 字數限制
|
||||
}
|
||||
if payload_parse_mode:
|
||||
payload["parse_mode"] = payload_parse_mode
|
||||
|
||||
return await self._send_request("sendMessage", payload)
|
||||
try:
|
||||
return await self._send_request("sendMessage", payload)
|
||||
except TelegramGatewayError as exc:
|
||||
if payload_parse_mode and payload_parse_mode.upper() == "HTML" and "HTTP error: 400" in str(exc):
|
||||
fallback_payload = {
|
||||
"chat_id": chat_id or self.alert_chat_id,
|
||||
"text": _plain_text_from_html(text, limit=500),
|
||||
}
|
||||
return await self._send_request("sendMessage", fallback_payload)
|
||||
raise
|
||||
|
||||
async def _send_html_line_message(
|
||||
self,
|
||||
|
||||
Reference in New Issue
Block a user