@gramio/format

中文文档
0.12.1发布于 2026/09/10MITTypeScriptESM + CJS构建来源已验证近 30 天下载 5.8万

Library for formatting text for Telegram Bot API

原始使用文档
文档目录16 节
  1. Installation
  2. Overview
  3. Template literals
  4. format
  5. formatSaveIndents
  6. Formatters
  7. Examples
  8. join — formatting arrays
  9. markdownToFormattable — Markdown → FormattableString
  10. Supported Markdown elements
  11. htmlToFormattable — HTML → FormattableString
  12. Supported HTML elements
  13. TipTap example
  14. Using with Telegram Bot API
  15. Rich messages and native tables
  16. See also

@gramio/format

Library for formatting text for Telegram Bot API. Used under the hood by GramIO framework but it is framework-agnostic.

npm JSR JSR Score

Installation

npm install @gramio/format
# or
bun add @gramio/format

Overview

@gramio/format builds MessageEntity objects alongside the text so you never have to track character offsets manually. All formatters compose freely — nest them as deeply as you like.

import { format, bold, italic, link, spoiler } from "@gramio/format";

const msg = format`${bold`Hi!`}

Can ${italic("you")} help ${spoiler`me`}?

Can you give me a ${link("star", "https://github.com/gramiojs/gramio")}?`;

// msg.text     → the plain string
// msg.entities → ready-to-send MessageEntity[]

Template literals

format

Strips leading indentation from every line (safe to indent inside your source).

import { format, bold, italic } from "@gramio/format";

format`Hello ${bold("world")}!`
// text: "Hello world!"
// entities: [{ type: "bold", offset: 6, length: 5 }]

formatSaveIndents

Same as format but preserves all whitespace exactly as written.

import { formatSaveIndents, code } from "@gramio/format";

formatSaveIndents`Run:\n    ${code("bun install")}`

Formatters

Every formatter accepts either a plain string, a FormattableString, or a tagged template literal.

bold("text")
bold`text`
bold(italic("text"))   // nested: bold wraps italic
FormatterTelegram entityNotes
boldboldCannot be combined with code / pre
italicitalicCannot be combined with code / pre
underlineunderlineCannot be combined with code / pre
strikethroughstrikethroughCannot be combined with code / pre
spoilerspoilerCannot be combined with code / pre
blockquoteblockquoteCannot be nested
expandableBlockquoteexpandable_blockquoteCannot be nested
codecodeInline monospace; cannot be combined with others
pre(text, lang?)preCode block; optional language for syntax highlight
link(text, url)text_linkCannot be combined with code / pre
mention(text, user)text_mention
customEmoji(emoji, id)custom_emojiRequires purchased username on Fragment

Examples

import {
    bold, italic, underline, strikethrough, spoiler,
    blockquote, expandableBlockquote,
    code, pre, link, mention, customEmoji,
    format,
} from "@gramio/format";

bold`Important`
italic`Subtle`
underline`Marked`
strikethrough`Removed`
spoiler`Secret`

blockquote`A quote from someone wise.`
expandableBlockquote`A very long quote that can be collapsed.`

code`npm install`
pre("console.log('hi')", "js")

link("GramIO", "https://gramio.dev")
mention("John", { id: 1, is_bot: false, first_name: "John" })
customEmoji("⚔️", "5222106016283378623")

// Compose freely
format`${bold("Price")}: ${italic("$42")}\nSee ${link("docs", "https://gramio.dev")}`

join — formatting arrays

Array .join() discards entities. Use join instead:

import { join, bold, format } from "@gramio/format";

const items = ["apple", "banana", "cherry"];

format`Shopping list:\n${join(items, (item) => bold(item), "\n")}`;
// text:     "Shopping list:\napple\nbanana\ncherry"
// entities: bold on each item at the correct offsets

The third argument is the separator (default ", "). Return null, undefined, or false from the iterator to skip an item.


markdownToFormattable — Markdown → FormattableString

Converts a Markdown string to a FormattableString with proper entities. Useful when your content comes from a Markdown source (e.g., API docs, user input).

Requires marked as a peer dependency:

npm install marked
import { markdownToFormattable } from "@gramio/format/markdown";

const result = markdownToFormattable(
    "# Title\n\n**bold** and *italic*\n\n> Blockquote\n\n[link](https://gramio.dev)"
);

// result.text     → "Title\n\nbold and italic\n\nBlockquote\n\nlink"
// result.entities → bold, italic, blockquote, text_link at correct offsets

Supported Markdown elements

MarkdownResult
**text** / __text__bold
*text* / _text_italic
~~text~~strikethrough
`code`inline code
```lang\n...\n```pre block (with optional language)
> textblockquote
[text](url)link
![alt](url)link (image → text link)
# Heading … ###### Headingbold
- item / 1. itemlist with bullet/number prefix

htmlToFormattable — HTML → FormattableString

Converts an HTML string to a FormattableString. Designed for HTML produced by rich-text editors such as TipTap, ProseMirror, or Quill.

Requires node-html-parser as a peer dependency:

npm install node-html-parser
import { htmlToFormattable } from "@gramio/format/html";

const result = htmlToFormattable(
    "<p><strong>Hello</strong> <em>world</em></p>"
);

// result.text     → "Hello world"
// result.entities → [bold offset=0 len=5, italic offset=6 len=5]

Supported HTML elements

ElementResultNotes
<strong>, <b>bold
<em>, <i>italic
<u>underline
<s>, <del>, <strike>strikethrough
<code>inline codeWhen not inside <pre>
<pre><code class="language-js">pre blockLanguage extracted from language-* class
<blockquote>blockquoteChildren processed recursively
<a href="...">link
<h1> … <h6>bold
<p>, <div>transparent wrapperChildren joined with ""
<br>\n
<ul>unordered listItems prefixed with -
<ol start="N">ordered listItems numbered from start

Block-level elements at the root are separated by \n\n. List items are separated by \n. Nested lists are supported and indented with \n before the sub-list.

TipTap example

import { htmlToFormattable } from "@gramio/format/html";

const html = `
<h1>Release notes</h1>
<p>Version <strong>2.0</strong> is out with <em>exciting</em> changes:</p>
<ul>
  <li><p>New <code>htmlToFormattable</code> function</p></li>
  <li><p>Performance improvements</p></li>
</ul>
<p>Read the <a href="https://gramio.dev">full docs</a>.</p>
`;

const result = htmlToFormattable(html);
// Sends correctly formatted message to Telegram with all entities intact

Using with Telegram Bot API

The FormattableString object has .text and .entities properties that map directly to Telegram's sendMessage parameters:

import { format, bold, link } from "@gramio/format";

const msg = format`Check out ${bold(link("GramIO", "https://gramio.dev"))}!`;

await bot.api.sendMessage({
    chat_id: chatId,
    text: msg.text,
    entities: msg.entities,
});

With GramIO you can pass the FormattableString directly:

bot.on("message", (ctx) => {
    ctx.send(format`Hello ${bold(ctx.from.first_name)}!`);
});

Rich messages and native tables

For Telegram Rich Messages, use the structured table() helper when you want a native InputRichBlockTable instead of Markdown text:

import { blocks, table } from "@gramio/format/rich";

const report = blocks([
    blocks.heading(1, "Release report"),
    table(
        [["Package", "Version"], ["gramio", "0.14.0"]],
        { bordered: true, striped: true, compact: true, align: ["left", "right"] },
    ),
]);

ctx.send(report);

table() can also be sent directly. The first row is a header by default, and cell alignment defaults to left/top. Use blocks.cell("Total", { colSpan: 2 }) for spans. The previous Markdown/GFM serializer is available as markdownTable() for explicit Markdown composition with rich([...]).

This is a breaking change from @gramio/format 0.11: table() used to produce Markdown/GFM. Rename existing Markdown calls to markdownTable() when upgrading to 0.12.

For a complete Markdown/HTML string produced by your own trusted serializer, use rawRich(); it preserves the syntax that the safe rich\…`tag escapes. Never pass untrusted text torawRich()`.

When using rowSpan, omit the covered cells in following rows; column alignment follows the logical table grid.


See also

版本与发布记录

@gramio/format 共发布 33 个版本,首次发布于 2024/02/11;过去 12 个月发布了 11 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.12.1latest2026/09/102 个月前
0.12.02026/09/102 个月前
0.11.02026/08/252 个月前
0.10.02026/07/303 个月前
0.9.02026/06/175 个月前
0.8.02026/05/096 个月前

关于 @gramio/format 的常见问题

@gramio/format 是什么?

Library for formatting text for Telegram Bot API

如何安装 @gramio/format?

在项目目录运行 npm install @gramio/format,或使用 pnpm add / yarn add / bun add。

@gramio/format 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gramio/format 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@gramio/format 可以商用吗?

@gramio/format 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@gramio/format 的下载量有多少?

根据 npm 官方下载统计,@gramio/format 在 2026/10/17 – 2026/11/15 这 30 天内被下载 57,592 次,日均约 1,920 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gramio/format 还在维护吗?

最新版本 0.12.1 发布于 2026/09/10(2 个月前);至今共发布 33 个版本,其中过去 12 个月发布了 11 个;首次发布于 2024/02/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。