AI-powered virtual executive team — a single coherent executive persona backed by 8 specialist agents (FastAPI + Next.js).
fix(integrations): retry a Telegram reply as plain text only on a refusal (#437)
Rufus681e237544cd
diff --git a/packages/core/openexecutive/integrations/telegram_bot.py b/packages/core/openexecutive/integrations/telegram_bot.pyindex d43f249c..996c3a7c 100644--- a/packages/core/openexecutive/integrations/telegram_bot.py+++ b/packages/core/openexecutive/integrations/telegram_bot.py@@ -94,12 +94,14 @@ async def send_message(token: str, chat_id: int, text: str) -> str | None:# The reply is Markdown, which Telegram shows as typed: send it as# Telegram's HTML instead. Should Telegram refuse that (an entity it# can't parse, or escaping that pushed it over the length cap), the- # chunk goes again as the plain text it was before.+ # chunk goes again as the plain text it was before. Only a 400 is a+ # refusal of the message itself: a 429 or 5xx would fail again (or,+ # after a 5xx that was delivered anyway, send the reply twice).resp = await client.post(_tg_url(token, "sendMessage"),json={**base, "text": markdown_to_telegram_html(chunk), "parse_mode": "HTML"},)- if resp.is_error:+ if resp.status_code == 400:logger.warning("Telegram sendMessage (HTML) failed, sending as plain text: %s %s",resp.status_code,diff --git a/packages/core/openexecutive/utils/markdown_telegram.py b/packages/core/openexecutive/utils/markdown_telegram.pyindex 6581078a..2f851e6f 100644--- a/packages/core/openexecutive/utils/markdown_telegram.py+++ b/packages/core/openexecutive/utils/markdown_telegram.py@@ -109,4 +109,9 @@ def markdown_to_telegram_html(text: str) -> str:rendered = "".join(out)# A quote's last paragraph leaves its break inside the tag.rendered = re.sub(r"\s+</blockquote>", "</blockquote>", rendered)- return re.sub(r"\n{3,}", "\n\n", rendered).strip()+ # Collapse runs of blank lines between blocks, but not inside code,+ # which is shown exactly as written.+ parts = re.split(r"(<pre>.*?</pre>)", rendered, flags=re.S)+ return "".join(+ part if part.startswith("<pre>") else re.sub(r"\n{3,}", "\n\n", part) for part in parts+ ).strip()diff --git a/packages/core/tests/unit/test_bot_link_previews.py b/packages/core/tests/unit/test_bot_link_previews.pyindex 02e588f1..f1710125 100644--- a/packages/core/tests/unit/test_bot_link_previews.py+++ b/packages/core/tests/unit/test_bot_link_previews.py@@ -18,6 +18,7 @@ def test_telegram_messages_turn_previews_off(monkeypatch: pytest.MonkeyPatch) ->class Resp:is_error = False+ status_code = 200def json(self) -> dict[str, Any]:return {"result": {"message_id": 7}}diff --git a/packages/core/tests/unit/test_telegram_formatting.py b/packages/core/tests/unit/test_telegram_formatting.pyindex 9cc194d9..c1c88ed2 100644--- a/packages/core/tests/unit/test_telegram_formatting.py+++ b/packages/core/tests/unit/test_telegram_formatting.py@@ -34,6 +34,12 @@ def test_code_blocks_and_quotes() -> None:assert render("> quoted\n> more") == "<blockquote>quoted\nmore</blockquote>"+def test_blank_lines_inside_code_are_kept() -> None:+ assert render("```\ndef a():\n pass\n\n\ndef b():\n pass\n```") == (+ "<pre>def a():\n pass\n\n\ndef b():\n pass</pre>"+ )++def test_text_and_raw_html_are_escaped() -> None:out = render("Tom & Jerry <b>not bold</b> <script>x</script>")assert "<b>" not in out and "<script>" not in out@@ -56,22 +62,24 @@ def test_a_link_shows_its_target_and_is_never_a_tag() -> None:class _Resp:- def __init__(self, ok: bool) -> None:+ def __init__(self, ok: bool, status: int = 400) -> None:self.is_error = not ok- self.status_code = 200 if ok else 400+ self.status_code = 200 if ok else statusself.text = "" if ok else "Bad Request: can't parse entities"def json(self) -> dict[str, Any]:return {"result": {"message_id": 7}}-def _send(monkeypatch: pytest.MonkeyPatch, text: str, html_ok: bool = True) -> list[dict[str, Any]]:+def _send(+ monkeypatch: pytest.MonkeyPatch, text: str, html_ok: bool = True, status: int = 400+) -> list[dict[str, Any]]:sent: list[dict[str, Any]] = []class Client:async def post(self, url: str, json: dict[str, Any]) -> _Resp:sent.append(json)- return _Resp(html_ok or "parse_mode" not in json)+ return _Resp(html_ok or "parse_mode" not in json, status)monkeypatch.setattr(telegram_bot, "_get_http_client", lambda: Client())asyncio.run(telegram_bot.send_message("t", 1, text))@@ -90,3 +98,11 @@ def test_a_refused_html_message_goes_again_as_plain_text(monkeypatch: pytest.Monassert html_try["parse_mode"] == "HTML"assert "parse_mode" not in plain_try and plain_try["text"] == "**Done.**"assert plain_try["link_preview_options"] == {"is_disabled": True}++[email protected]("status", [429, 500, 403])+def test_only_a_refusal_is_retried_as_plain_text(monkeypatch: pytest.MonkeyPatch, status: int) -> None:+ # Rate limits, server errors and a blocked bot would fail again, and a+ # 5xx that was delivered anyway would send the reply twice.+ [only_try] = _send(monkeypatch, "**Done.**", html_ok=False, status=status)+ assert only_try["parse_mode"] == "HTML"