Skip to main content

tg-rich-converter banner

tg-rich-converter 🚀

PyPI version Python versions License: MIT

A lightweight, zero-dependency Python library that converts standard LLM Markdown, LaTeX formulas, thinking processes, and tables into native Telegram Bot API 10.1+ Rich HTML (sendRichMessage).


Tables and Math Demo


Why tg-rich-converter?

Starting with Telegram Bot API 10.1, Telegram introduced Rich Messages (sendRichMessage) supporting:

  • Messages up to 32,768 characters (no more 4,096-character limit!).
  • Native interactive tables with borders and striping.
  • Native LaTeX math rendering (both inline and display equations).
  • Expandable spoiler/details blocks for reasoning models (DeepSeek-R1, OpenAI o1/o3, Qwen, Gemini).
  • Native lists and advanced typography (<ul>, <ol>, <u>, <mark>).

However, LLMs (OpenAI, Anthropic, DeepSeek, Ollama) still output plain Markdown and LaTeX. tg-rich-converter bridges this gap seamlessly in a single function call.


Features

  • 📊 Robust Native Tables: Converts standard Markdown pipe tables into <table bordered striped> with column alignment (left, center, right). Safely handles formulas with pipes ($|\psi\rangle$, $|x| \ge 0$) and escaped pipes (\|) inside table cells without breaking columns.
  • 🧮 LaTeX Math: Converts $$...$$ into <tg-math-block> and $x$ into <tg-math>.
  • 🧠 Customizable AI Thinking Blocks: Converts <think>...</think> tags from reasoning models into expandable <details><summary>Размышления</summary>...</details> blocks with configurable summary titles.
  • 🛡️ HTML-Safe: Automatically escapes raw <, >, and & in regular text (e.g. mathematical conditions like x < 5 and y > 10), completely preventing Telegram API 400 Bad Request: can't parse entities errors.
  • 📋 Native Lists: Converts unordered (- , * , + ) and ordered (1. ) lists into native <ul> and <ol> tags, avoiding conflicts between asterisk bullet markers and italics.
  • 🎨 Rich Typography: Supports bold (**), italic (* / _), strikethrough (~~), underline (++text++), highlight (==text==), and spoilers (||spoiler||) with snake_case protection.
  • 💻 Syntax-Highlighted Code: Converts markdown code fences into <pre><code class="language-..."> preserving language classes, indentation, and copy buttons.
  • ✂️ Smart Message Splitter: Safely splits long texts up to 32,768 (Telegram Rich limit) or 4,096 (Classic limit) characters. Automatically closes and re-opens nested tags with attributes (<pre><code class="...">, <blockquote>), and protects LaTeX formulas from fragmentation.
  • 👁️ Local HTML Preview: Instantly generates a standalone preview.html styled with authentic Telegram Web dark theme and KaTeX client-side math rendering to visually inspect output without launching a bot.
  • Thread-Safe & Zero Dependencies: Pure standard Python (re, html). Fully reentrant and async-safe for high-concurrency bot environments.

Installation

pip install tg-rich-converter

Quick Start

from tg_rich_converter import to_rich

llm_output = """
# Quantum Computing Report

| Algorithm | State | Complexity | Option |
|:----------|:-----:|:----------:|-------:|
| Linear Search | $N$ items | $O(N)$ | Mode A \\| B |
| State Vector  | $|\\psi\\rangle$ | $O(1)$ | Basic |

### Key Formula
$$|\\psi\\rangle = \\alpha |0\\rangle + \\beta |1\\rangle$$

Stability requires delta < 0.05 and alpha > 0.

<think>
Evaluating time complexity and qubit entanglement...
</think>
"""

# Default thinking summary is "Размышления"
rich_html = to_rich(llm_output)

# Or specify a custom summary:
rich_html_en = to_rich(llm_output, thinking_summary="Reasoning Process")

Smart Message Splitting (Long Outputs)

When LLM output exceeds Telegram limits (32,768 chars for Rich Messages or 4,096 chars for standard messages), naive slicing breaks open HTML tags and crashes the bot. Use split_rich_message:

from tg_rich_converter import split_rich_message

# Automatically converts Markdown to Rich HTML and splits into safe chunks
chunks = split_rich_message(
    long_llm_response,
    max_length=32768,      # 32,768 for Rich Messages (default) or 4,096 for Classic
    is_markdown=True,      # Automatically runs to_rich()
    thinking_summary="Reasoning"
)

# Each chunk is guaranteed to be valid HTML with all open tags closed and reopened
for chunk in chunks:
    await bot.send_rich_message(chat_id=chat_id, rich_message={"html": chunk})

Local HTML Preview

Visualize how your message will look in Telegram Desktop/Mobile without running a bot or sending messages:

from tg_rich_converter import save_preview

# Generates preview.html with Telegram dark theme, KaTeX formulas, and interactive spoilers
save_preview(
    llm_output,
    file_path="preview.html",
    title="LLM Telegram Preview"
)

Double click preview.html to open it in your browser!


Framework Integrations

1. aiogram (3.31+)

from aiogram import Bot
from tg_rich_converter import to_rich

bot = Bot(token="YOUR_BOT_TOKEN")

rich_html = to_rich(llm_response)
await bot.send_rich_message(
    chat_id=chat_id,
    rich_message={"html": rich_html}
)

2. pyTelegramBotAPI (telebot 4.36+)

import telebot
from tg_rich_converter import to_rich

bot = telebot.TeleBot("YOUR_BOT_TOKEN")

rich_html = to_rich(llm_response)
bot.send_rich_message(
    chat_id=chat_id,
    rich_message={"html": rich_html}
)

3. Direct HTTP (requests / httpx / urllib)

import requests
from tg_rich_converter import to_rich

rich_html = to_rich(llm_response)

requests.post(
    f"https://api.telegram.org/bot{BOT_TOKEN}/sendRichMessage",
    json={
        "chat_id": chat_id,
        "rich_message": {
            "html": rich_html
        }
    }
)

Testing

Run unit tests locally:

pytest

License

MIT License. Free for commercial and personal use.

Release files for tg-rich-converter 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tg-rich-converter 0.3.0
File Size Uploaded
tg_rich_converter-0.3.0.tar.gz 119.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for tg-rich-converter 0.3.0
File Interpreter ABI Platform
tg_rich_converter-0.3.0-py3-none-any.whl Python 3 none any Details

Total release size: 133.9 kB

Release files / tg_rich_converter-0.3.0.tar.gz

Download URL tg_rich_converter-0.3.0.tar.gz
Size 119.7 kB
Tags Source
SHA-256 checksum
How to use checksums
44769ad87eb9320d080a69ebdb8c37a0487a7fcc1dafcf2497999bdca53e6293
BLAKE2b-256 checksum
How to use checksums
c9f240701bbbb8b6c69c3e24873695a86c8f7bdd7a7f55b75c5c3da1e9e22913
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 20, 2026.

Transparency log

Release files / tg_rich_converter-0.3.0-py3-none-any.whl

Download URL tg_rich_converter-0.3.0-py3-none-any.whl
Size 14.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ae167176b008ed6b8361fa94f7fe4af2e786562225db8ff8f82a856250b28e03
BLAKE2b-256 checksum
How to use checksums
9471fa32bca9fe9a7f2d039bff325f26bbdbe804641bd8edc902781bd55252bc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 20, 2026.

Transparency log

Release history Release notifications | RSS feed

0.5.0

2 release files

0.4.1

2 release files

0.4.0

2 release files

This release

0.3.0 This release

2 release files

0.2.0

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page