惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
H
Help Net Security
云风的 BLOG
云风的 BLOG
Apple Machine Learning Research
Apple Machine Learning Research
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Hugging Face - Blog
Hugging Face - Blog
博客园_首页
D
Docker
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
博客园 - Franky
B
Blog RSS Feed
Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
量子位
V
Visual Studio Blog
Y
Y Combinator Blog
小众软件
小众软件
N
Netflix TechBlog - Medium
博客园 - 三生石上(FineUI控件)
Microsoft Security Blog
Microsoft Security Blog
雷峰网
雷峰网

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Build Complex Rich Messages for Telegram Bots (Typ...
Valentin · 2026-06-18 · via DEV Community

Valentin

Telegram recently introduced Rich Messages — a new HTML-based formatting system that lets you build beautifully styled messages with headings, lists, tables, collages, maps, and much more.

But if you're writing a Telegram bot in TypeScript/JavaScript, you might have noticed that there's no ready-made builder for this new format yet. You have to manually write HTML strings, escape content, and keep track of nesting, media limits, and text length — which is tedious and error‑prone.

That's why I built tg-rich-messages — a small, zero‑dependency library that does all the heavy lifting for you.


✨ What it does

It provides a clean, typed API to build rich messages programmatically. You can mix and match inline and block elements, and the library will generate the correct HTML for Telegram's sendRichMessage method.

Features:

  • All inline formatting: bold, italic, underline, strikethrough, spoiler, code, marked, sub, sup, links, mentions, emoji, date/time, and more.
  • All block elements: headings (1–6), paragraphs, preformatted code, lists (ordered/unordered, with checkboxes), blockquotes, pullquotes, tables (alignment, colspan, rowspan, stripes), details (expandable), maps, collages, slideshows.
  • Media blocks: photo, video, animation, audio, voice — with captions and credits.
  • Full validation: checks text length (≤32768 chars), media count (≤50), total blocks (≤500), and nesting depth (≤16).
  • Tree‑shakeable, no runtime dependencies.
  • Tagged template literal (fmtRich) for natural inline mixing.

🚀 Quick Start

Install the package:

npm install tg-rich-messages

Then build your message:

import { doc, bold, italic, paragraph, heading, list, code, fmtRich } from 'tg-rich-messages';

// Using the builder API
const message = doc(
  heading(1, 'Welcome'),
  paragraph([bold('Hello'), ' ', italic('world'), '!']),
  list(
    [
      'First item',
      { content: code('code example'), checkbox: true, checked: true },
      { content: 'Ordered item', value: 7, type: 'a' },
    ],
    { ordered: true, start: 7 },
  )
);

// Render to HTML
const html = message.toHTML();

// Get InputRichMessage payload for sendRichMessage
const payload = message.toInputRichMessage({
  skipEntityDetection: true
});

Or use the template literal:

const message = fmtRich`
  ${bold`Hello`} ${italic`world`}!
  Here is some ${code`inline code`}.
`;

console.log(message.toHTML());
// <p><b>Hello</b> <i>world</i>!<br>Here is some <code>inline code</code>.</p>


📦 Example with a Telegram Bot

Send the rich message via the Bot API:

await fetch(`https://api.telegram.org/bot${TOKEN}/sendRichMessage`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    chat_id: chatId,
    rich_message: message.toInputRichMessage()
  })
});


🔍 Validation

The built‑in validate() method checks:

  • Text length (actual UTF‑8 characters, not bytes)
  • Number of media attachments (≤50)
  • Total blocks (≤500)
  • Nesting depth (≤16)

This prevents you from sending messages that Telegram would reject.


🧩 Why I built it

I needed a clean, typed way to generate rich messages for my own Telegram bot. I couldn't find an existing JS/TS library that did this, so I built one for myself — and decided to share it in case others find it useful too.

It's not a long‑term maintained project, but I believe it's already feature‑complete for most use cases. Pull requests are welcome!


📎 Links


🙌 Feedback

If you try it out, let me know what you think! Issues and suggestions are welcome on GitHub.

Happy building! 🚀