Agent Zero AI framework
feat(telegram): group reply-to + formatting pipeline cleanup
keyboardstaff40a72c0c517f
diff --git a/plugins/_telegram_integration/helpers/handler.py b/plugins/_telegram_integration/helpers/handler.pyindex 763269dea..84ba1a39b 100644--- a/plugins/_telegram_integration/helpers/handler.py+++ b/plugins/_telegram_integration/helpers/handler.py@@ -34,6 +34,7 @@ CTX_TG_CHAT_ID = "telegram_chat_id"CTX_TG_USER_ID = "telegram_user_id"CTX_TG_USERNAME = "telegram_username"CTX_TG_TYPING_STOP = "_telegram_typing_stop"+CTX_TG_REPLY_TO = "_telegram_reply_to_message_id"# TransientCTX_TG_ATTACHMENTS = "_telegram_response_attachments"@@ -221,6 +222,15 @@ async def handle_message(message: TgMessage, bot_name: str, bot_cfg: dict):# Store stop event so send_telegram_reply can cancel typingcontext.data[CTX_TG_TYPING_STOP] = typing_stop+ # In group chats, if user replied to the bot's message, reply to the user's message+ reply_to_id = None+ if message.chat.type != "private" and instance.bot_info:+ if (message.reply_to_message+ and message.reply_to_message.from_user+ and message.reply_to_message.from_user.id == instance.bot_info.id):+ reply_to_id = message.message_id+ context.data[CTX_TG_REPLY_TO] = reply_to_id+# Build user message texttext = _extract_message_content(message)@@ -485,22 +495,24 @@ async def send_telegram_reply(if typing_stop:typing_stop.set()+ reply_to = context.data.pop(CTX_TG_REPLY_TO, None)+try:async with _temp_bot(instance.bot.token, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) as reply_bot:if attachments:for path in attachments:local_path = files.fix_dev_path(path)if tc.is_image_file(local_path):- await tc.send_photo(reply_bot, chat_id, local_path)+ await tc.send_photo(reply_bot, chat_id, local_path, reply_to_message_id=reply_to)else:- await tc.send_file(reply_bot, chat_id, local_path)+ await tc.send_file(reply_bot, chat_id, local_path, reply_to_message_id=reply_to)if response_text:html_text = tc.md_to_telegram_html(response_text)if keyboard:- await tc.send_text_with_keyboard(reply_bot, chat_id, html_text, keyboard)+ await tc.send_text_with_keyboard(reply_bot, chat_id, html_text, keyboard, reply_to_message_id=reply_to)else:- await tc.send_text(reply_bot, chat_id, html_text)+ await tc.send_text(reply_bot, chat_id, html_text, reply_to_message_id=reply_to)return Nonediff --git a/plugins/_telegram_integration/helpers/telegram_client.py b/plugins/_telegram_integration/helpers/telegram_client.pyindex 62aa7c4e3..4ea104123 100644--- a/plugins/_telegram_integration/helpers/telegram_client.py+++ b/plugins/_telegram_integration/helpers/telegram_client.py@@ -218,11 +218,7 @@ def is_image_file(path: str) -> bool:def md_to_telegram_html(text: str) -> str:- """Convert standard Markdown to Telegram-compatible HTML.-- Handles: fenced code blocks, inline code, bold, italic, strikethrough,- links, headings, blockquotes, tables, and nested lists.- """+ """Convert Markdown to Telegram-compatible HTML."""stash: list[str] = []def _put(html: str) -> str:@@ -232,109 +228,79 @@ def md_to_telegram_html(text: str) -> str:def _esc(t: str) -> str:return t.replace("&", "&").replace("<", "<").replace(">", ">")- # Stash fenced code blocks- def _code_block(m: re.Match) -> str:- lang, code = m.group(1) or "", _esc(m.group(2))- tag = f'<pre><code class="language-{lang}">{code}</code></pre>' if lang else f"<pre>{code}</pre>"- return _put(tag)+ # Stash code blocks & inline code+ def _code_block(m):+ lang, body = m.group(1), m.group(2).rstrip("\n")+ if lang:+ return _put(f'<pre><code class="language-{lang}">{_esc(body)}</code></pre>')+ return _put(f"<pre>{_esc(body)}</pre>")- text = re.sub(r"```(\w*)\n(.*?)```", _code_block, text, flags=re.DOTALL)-- # Stash inline code+ text = re.sub(r"(?:```|~~~)(\w*)\n?(.*?)(?:```|~~~)", _code_block, text, flags=re.DOTALL)text = re.sub(r"`([^`]+)`", lambda m: _put(f"<code>{_esc(m.group(1))}</code>"), text)- # Stash Markdown tables as list-style text- text = _stash_tables(text, _put, _esc)-- # Escape remaining HTML chars+ # Strip unsupported syntax+ text = _strip_tables(text)+ text = re.sub(r"^[ \t]*[-*_=]{3,}[ \t]*$", "", text, flags=re.MULTILINE)+ text = re.sub(r"!\[([^\]]*)\]\(([^)]+)\)", r"[\1](\2)", text)++ # Stash links+ text = re.sub(+ r"\[([^\]]+)\]\(([^)]+)\)",+ lambda m: _put(+ f'<a href="{m.group(2).replace("&", "&").replace(chr(34), """)}">{_esc(m.group(1))}</a>'+ ),+ text,+ )++ # Escape HTML & apply inline formattingtext = _esc(text)-- # Inline formatting+ text = re.sub(r"\*\*\*(.+?)\*\*\*", r"<b><i>\1</i></b>", text)text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)text = re.sub(r"__(.+?)__", r"<b>\1</b>", text)text = re.sub(r"(?<!\w)\*([^*]+?)\*(?!\w)", r"<i>\1</i>", text)text = re.sub(r"(?<!\w)_([^_]+?)_(?!\w)", r"<i>\1</i>", text)text = re.sub(r"~~(.+?)~~", r"<s>\1</s>", text)- text = re.sub(r"\[([^\]]+)\]\(([^)]+)\)", r'<a href="\2">\1</a>', text)text = re.sub(r"^#{1,6}\s+(.+)$", r"<b>\1</b>", text, flags=re.MULTILINE)- # Blockquotes: > text → <blockquote>+ # Block-level formattingtext = _convert_blockquotes(text)-- # Lists (nested + ordered)text = _convert_lists(text)- # Restore all stashed blocks+ # Restore stashfor i, block in enumerate(stash):text = text.replace(f"\x00B{i}\x00", block)return text-# ── Helpers for md_to_telegram_html ──-_TABLE_ROW = re.compile(r"^\|(.+)\|$")+_TABLE_RE = re.compile(r"^\|(.+)\|$")_TABLE_SEP = re.compile(r"^[\s|:-]+$")-def _stash_tables(text: str, put_fn, esc_fn) -> str:- """Convert Markdown tables to key-value list format and stash them.-- | Name | Age |- |-------|-----|- | Alice | 30 | → • Name: Alice, Age: 30- | Bob | 25 | • Name: Bob, Age: 25- """- lines = text.split("\n")+def _strip_tables(text: str) -> str:+ """Strip Markdown table pipe syntax, keeping cell content as plain text."""out: list[str] = []- headers: list[str] = []- data_rows: list[list[str]] = []-- def _flush():- if not headers and not data_rows:- return- if headers and data_rows:- items: list[str] = []- for row in data_rows:- pairs = ", ".join(- f"{headers[i]}: {row[i]}" if i < len(row) else headers[i]- for i in range(len(headers))- )- items.append(f"\u2022 {pairs}")- out.append(put_fn(esc_fn("\n".join(items))))- elif data_rows:- # No header row — just bullet each row- for row in data_rows:- out.append(put_fn(esc_fn(f"\u2022 {', '.join(row)}")))- headers.clear()- data_rows.clear()-- for line in lines:- m = _TABLE_ROW.match(line.strip())+ for line in text.split("\n"):+ stripped = line.strip()+ if _TABLE_SEP.match(stripped):+ continue+ m = _TABLE_RE.match(stripped)if m:- if _TABLE_SEP.match(line.strip()):- continue- cells = [c.strip() for c in m.group(1).split("|")]- if not headers:- headers.extend(cells)- else:- data_rows.append(cells)+ out.append(" ".join(c.strip() for c in m.group(1).split("|")))else:- _flush()out.append(line)- _flush()return "\n".join(out)-_LIST_ITEM = re.compile(r"^( *)([-*+]|\d+\.)\s+(.*)$")-_BULLETS = ["\u2022", "\u25e6", "\u25aa"] # • ◦ ▪+_LIST_RE = re.compile(r"^( *)([-*+]|\d+\.)\s+(.*)$")+_BULLETS = ("\u2022", "\u25e6", "\u25aa")def _convert_lists(text: str) -> str:- """Convert Markdown list items to indented bullet / numbered lines."""- lines = text.split("\n")+ """Convert Markdown list markers to Unicode bullets."""out: list[str] = []- for line in lines:- m = _LIST_ITEM.match(line)+ for line in text.split("\n"):+ m = _LIST_RE.match(line)if m:depth = len(m.group(1)) // 2marker, content = m.group(2), m.group(3)@@ -349,20 +315,19 @@ def _convert_lists(text: str) -> str:def _convert_blockquotes(text: str) -> str:- """Convert Markdown blockquotes (> text) to <blockquote> tags."""- lines = text.split("\n")+ """Convert Markdown blockquotes to Telegram <blockquote> tags."""out: list[str] = []- quote_buf: list[str] = []+ buf: list[str] = []def _flush():- if quote_buf:- out.append("<blockquote>" + "\n".join(quote_buf) + "</blockquote>")- quote_buf.clear()+ if buf:+ out.append("<blockquote>" + "\n".join(buf) + "</blockquote>")+ buf.clear()- for line in lines:- m = re.match(r"^>\s?(.*)", line) # > is already HTML-escaped at this point+ for line in text.split("\n"):+ m = re.match(r"^>\s?(.*)", line)if m:- quote_buf.append(m.group(1))+ buf.append(m.group(1))else:_flush()out.append(line)diff --git a/plugins/_telegram_integration/prompts/fw.telegram.system_context_reply.md b/plugins/_telegram_integration/prompts/fw.telegram.system_context_reply.mdindex ac96eceb6..fc4cecede 100644--- a/plugins/_telegram_integration/prompts/fw.telegram.system_context_reply.md+++ b/plugins/_telegram_integration/prompts/fw.telegram.system_context_reply.md@@ -8,6 +8,15 @@ include file paths in attachments array to send files/imagesfor multiple files zip first then attach single archiveoptionally set keyboard array for inline buttons+# formatting rules+use Telegram-friendly markdown only:+ allowed: **bold**, *italic*, ~~strikethrough~~, `inline code`, ```code blocks```, [links](url), > blockquotes, bullet lists (- item), numbered lists (1. item)+ headings rendered as bold — keep them short+ avoid: tables (use "• key: value" bullet list instead), deeply nested lists (max 2 levels), horizontal rules (---), image syntax + do not mix formatting inside code blocks — code blocks are monospace only+ send images/files via attachments array, not inline markdown+ keep messages concise — users read on mobile+usage:~~~json