Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(telegram): send structured markdown as rich messages

cyhf2397121e59b
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index 0e456132e..46ba20f91 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import json
import logging
+import re
import tempfile
import threading
from dataclasses import dataclass
@@ -93,6 +94,11 @@ class TelegramBot(BaseIMClient):
_MAX_IN_FLIGHT_UPDATE_TASKS = 100
_MAX_IN_FLIGHT_MESSAGE_CALLBACK_TASKS = 100
+ _RICH_MARKDOWN_BLOCK_RE = re.compile(
+ r"(?m)^(?:#{1,6}\s+\S|[-*+]\s+\S|\d+\.\s+\S|>\s?\S|---\s*$|\|.*\|\s*$|\$\$)"
+ r"|```|<details\b|<tg-|!\[[^\]]*\]\(https?://",
+ re.IGNORECASE,
+ )
def __init__(self, config: TelegramConfig):
super().__init__(config)
@@ -115,6 +121,7 @@ class TelegramBot(BaseIMClient):
self._routing_states: dict[str, _TelegramRoutingState] = {}
self._question_states: dict[str, _TelegramQuestionState] = {}
self._settings_states: dict[str, _TelegramSettingsState] = {}
+ self._rich_markdown_supported: Optional[bool] = None
def set_settings_manager(self, settings_manager):
self.settings_manager = settings_manager
@@ -833,6 +840,81 @@ class TelegramBot(BaseIMClient):
}
return payload
+ def _build_rich_message_payload(
+ self,
+ context: MessageContext,
+ text: str,
+ keyboard: Optional[InlineKeyboard] = None,
+ *,
+ reply_to: Optional[str] = None,
+ ) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "chat_id": context.channel_id,
+ "rich_message": {
+ "markdown": text,
+ },
+ }
+ if context.thread_id:
+ payload["message_thread_id"] = int(context.thread_id)
+ if reply_to:
+ payload["reply_parameters"] = {"message_id": int(reply_to)}
+ if keyboard is not None:
+ payload["reply_markup"] = {
+ "inline_keyboard": [
+ [{"text": button.text, "callback_data": button.callback_data} for button in row]
+ for row in keyboard.buttons
+ ]
+ }
+ return payload
+
+ def _should_send_rich_markdown(self, text: str) -> bool:
+ if not text or not text.strip():
+ return False
+ if self._rich_markdown_supported is False:
+ return False
+ return bool(self._RICH_MARKDOWN_BLOCK_RE.search(text))
+
+ @staticmethod
+ def _is_rich_message_method_unavailable(err: Exception) -> bool:
+ description = str(err).lower()
+ return "method not found" in description
+
+ async def send_markdown_message(
+ self,
+ context: MessageContext,
+ text: str,
+ keyboard: Optional[InlineKeyboard] = None,
+ reply_to: Optional[str] = None,
+ ) -> str:
+ """Send LLM-authored Markdown through Telegram Rich Messages when useful.
+
+ Bot API 10.1 rich messages understand GFM-like block structure. Plain
+ short markdown still uses the legacy HTML conversion path because it is
+ older, broadly deployed, and sufficient for simple emphasis/links/code.
+ """
+ if not self._should_send_rich_markdown(text):
+ if keyboard is not None:
+ return await self.send_message_with_buttons(context, text, keyboard, parse_mode="markdown")
+ return await self.send_message(context, text, parse_mode="markdown", reply_to=reply_to)
+
+ payload = self._build_rich_message_payload(context, text, keyboard=keyboard, reply_to=reply_to)
+ try:
+ result = await telegram_api.call_api(
+ self.config.bot_token,
+ "sendRichMessage",
+ payload,
+ proxy_url=self._proxy_url,
+ )
+ except Exception as err:
+ if self._is_rich_message_method_unavailable(err):
+ self._rich_markdown_supported = False
+ logger.warning("Telegram sendRichMessage failed; falling back to sendMessage", exc_info=True)
+ if keyboard is not None:
+ return await self.send_message_with_buttons(context, text, keyboard, parse_mode="markdown")
+ return await self.send_message(context, text, parse_mode="markdown", reply_to=reply_to)
+ self._rich_markdown_supported = True
+ return str(result["result"]["message_id"])
+
async def send_message(
self, context: MessageContext, text: str, parse_mode: Optional[str] = None, reply_to: Optional[str] = None
) -> str:
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index 2af6ff9ed..39a6a656a 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -15,7 +15,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
from core import chat_discovery
from modules.agents.native_sessions import NativeResumeSession
-from modules.im import MessageContext
+from modules.im import InlineButton, InlineKeyboard, MessageContext
from modules.im.multi import MultiIMClient
from modules.im.telegram import TelegramBot
from config.v2_config import TelegramConfig
@@ -600,6 +600,96 @@ def test_send_message_uses_html_parse_mode() -> None:
assert payload["text"] == "Hello <b>world</b>"
+def test_send_markdown_message_keeps_plain_markdown_on_html_path() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")
+
+ with patch(
+ "modules.im.telegram.telegram_api.call_api",
+ new=AsyncMock(return_value={"result": {"message_id": 77}}),
+ ) as call_mock:
+ asyncio.run(bot.send_markdown_message(context, "Hello **world**"))
+
+ assert call_mock.await_args.args[1] == "sendMessage"
+ payload = call_mock.await_args.args[2]
+ assert payload["parse_mode"] == "HTML"
+ assert payload["text"] == "Hello <b>world</b>"
+
+
+def test_send_markdown_message_uses_rich_message_for_structured_markdown() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(user_id="42", channel_id="-100123", thread_id="8", platform="telegram")
+ keyboard = InlineKeyboard(buttons=[[InlineButton(text="Inspect", callback_data="quick_reply:Inspect")]])
+ markdown = "# Summary\n\n- shipped\n- verified"
+
+ with patch(
+ "modules.im.telegram.telegram_api.call_api",
+ new=AsyncMock(return_value={"result": {"message_id": 88}}),
+ ) as call_mock:
+ result = asyncio.run(bot.send_markdown_message(context, markdown, keyboard=keyboard, reply_to="77"))
+
+ assert result == "88"
+ assert call_mock.await_args.args[1] == "sendRichMessage"
+ payload = call_mock.await_args.args[2]
+ assert payload["chat_id"] == "-100123"
+ assert payload["message_thread_id"] == 8
+ assert payload["reply_parameters"] == {"message_id": 77}
+ assert payload["rich_message"] == {"markdown": markdown}
+ assert payload["reply_markup"] == {
+ "inline_keyboard": [[{"text": "Inspect", "callback_data": "quick_reply:Inspect"}]]
+ }
+
+
+def test_send_markdown_message_falls_back_when_rich_message_is_rejected() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")
+ markdown = "# Summary\n\n- shipped"
+
+ with patch(
+ "modules.im.telegram.telegram_api.call_api",
+ new=AsyncMock(
+ side_effect=[
+ RuntimeError("Bad Request: method not found"),
+ {"result": {"message_id": 89}},
+ ]
+ ),
+ ) as call_mock:
+ result = asyncio.run(bot.send_markdown_message(context, markdown))
+
+ assert result == "89"
+ assert [call.args[1] for call in call_mock.await_args_list] == ["sendRichMessage", "sendMessage"]
+ fallback_payload = call_mock.await_args_list[1].args[2]
+ assert fallback_payload["parse_mode"] == "HTML"
+ assert fallback_payload["text"] == "# Summary\n\n- shipped"
+
+
+def test_send_markdown_message_disables_rich_path_after_method_missing() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")
+ markdown = "# Summary\n\n- shipped"
+
+ with patch(
+ "modules.im.telegram.telegram_api.call_api",
+ new=AsyncMock(
+ side_effect=[
+ RuntimeError("Bad Request: method not found"),
+ {"result": {"message_id": 89}},
+ {"result": {"message_id": 90}},
+ ]
+ ),
+ ) as call_mock:
+ first = asyncio.run(bot.send_markdown_message(context, markdown))
+ second = asyncio.run(bot.send_markdown_message(context, markdown))
+
+ assert first == "89"
+ assert second == "90"
+ assert [call.args[1] for call in call_mock.await_args_list] == [
+ "sendRichMessage",
+ "sendMessage",
+ "sendMessage",
+ ]
+
+
def test_add_reaction_uses_telegram_message_reactions() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")