fix(telegram): preserve code block content when language tag contains special characters

This commit is contained in:
santhreal
2026-08-04 21:40:03 +08:00
committed by Xubin Ren
parent 5770329542
commit a13e29bf07
2 changed files with 12 additions and 2 deletions
+2 -2
View File
@@ -166,7 +166,7 @@ def _strip_md_block(text: str) -> str:
markdown syntax while the response is still being generated. markdown syntax while the response is still being generated.
""" """
# Code blocks -> just the code # Code blocks -> just the code
text = re.sub(r'```[\w]*\n?([\s\S]*?)```', r'\1', text) text = re.sub(r'```[^\n]*\n?([\s\S]*?)```', r'\1', text)
# Headers -> plain text # Headers -> plain text
text = re.sub(r'^#{1,6}\s+(.+)$', r'\1', text, flags=re.MULTILINE) text = re.sub(r'^#{1,6}\s+(.+)$', r'\1', text, flags=re.MULTILINE)
# Blockquotes # Blockquotes
@@ -232,7 +232,7 @@ def _markdown_to_telegram_html(text: str) -> str:
code_blocks.append(m.group(1)) code_blocks.append(m.group(1))
return f"\x00CB{len(code_blocks) - 1}\x00" return f"\x00CB{len(code_blocks) - 1}\x00"
text = re.sub(r'```[\w]*\n?([\s\S]*?)```', save_code_block, text) text = re.sub(r'```[^\n]*\n?([\s\S]*?)```', save_code_block, text)
# 1.5. Convert markdown tables to box-drawing (reuse code_block placeholders) # 1.5. Convert markdown tables to box-drawing (reuse code_block placeholders)
lines = text.split('\n') lines = text.split('\n')
@@ -2395,3 +2395,13 @@ async def test_callback_query_handles_inaccessible_message() -> None:
query.answer.assert_awaited_once() query.answer.assert_awaited_once()
channel._handle_message.assert_awaited_once() channel._handle_message.assert_awaited_once()
assert channel._handle_message.await_args.kwargs["chat_id"] == "123" assert channel._handle_message.await_args.kwargs["chat_id"] == "123"
def test_markdown_to_html_code_block_special_chars_language() -> None:
from nanobot.channels.telegram.runtime import _markdown_to_telegram_html, _strip_md_block
text = "```c++\nint main() { return 0; }\n```"
html = _markdown_to_telegram_html(text)
assert html == "<pre><code>int main() { return 0; }\n</code></pre>"
stripped = _strip_md_block(text)
assert stripped == "int main() { return 0; }\n"