@gramio/format

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

Telegram Bot API 文本格式化库

中文使用文档
文档目录16 节
  1. 安装
  2. 概览
  3. 模板文字
  4. format
  5. formatSaveIndents
  6. 格式化器
  7. 实例
  8. join ——格式化阵列
  9. markdownToFormattable 平面平面结构
  10. 支持的标记下元素
  11. htmlToFormattable —— HTML —— 格式表
  12. 支持的 HTML 元素
  13. TipTap 示例
  14. 使用Telegram Bot API
  15. 丰富的信息和本地表格
  16. 另见

@ gramio/ 格式

图书馆 格式化 telegram Bot API 的文本。 用在引擎盖下 语法 框架,但它是框架不可知的.

npm JSR JSR Score

安装

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

概览

@gramio/format 正在建设 MessageEntity 对象与文本相并列,所以您无需手动跟踪字符偏移。 所有格式化者自由地作曲——像你们喜欢的那样深入地筑巢.

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[]

模板文字

format

条从每行(安全到来源内的缩进)引出缩进.

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

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

formatSaveIndents

与 format 但保留了所有的空白 完全如所写.

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

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

格式化器

每个前题都接受一个简单的字符串,一个 FormattableString,或标记模板文字.

bold("text")
bold`text`
bold(italic("text"))   // nested: bold wraps italic
主题电报实体页:1
boldbold无法结合 code 编号 : pre
italicitalic无法结合 code 编号 : pre
underlineunderline无法结合 code 编号 : pre
strikethroughstrikethrough无法结合 code 编号 : pre
spoilerspoiler无法结合 code 编号 : pre
blockquoteblockquote无法嵌入
expandableBlockquoteexpandable_blockquote无法嵌入
codecode内置单空间; 无法与其他空间合并
pre(text, lang?)pre代码块; 语法突出显示的可选语言
link(text, url)text_link无法结合 code 编号 : pre
mention(text, user)text_mention
customEmoji(emoji, id)custom_emoji需要在断层上购买用户名

实例

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 ——格式化阵列

阵列 .join() 丢弃实体。 使用 join 相反:

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

第三个参数是分隔符( 默认) ", ") (中文(简体) ). 返回时 null, (中文(简体) ), undefined,或 false 跳过项目.


markdownToFormattable 平面平面结构

将 Markdown 字符串转换为 a FormattableString 与适当的实体。 当您的内容来自 Markdown 源( 如 API docs, 用户输入) 时有用 .

要求数 marked 作为同伴依赖:

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

支持的标记下元素

标记结果
**text** 编号 : __text__粗体
*text* 编号 : _text_斜体
~~text~~击穿
`code`内置代码
```lang\n...\n```预设块( 有可选语言)
> text块引用
[text](url)链接
![alt](url)链接(图像-文本链接)
# Heading . ###### Heading粗体
- item 编号 : 1. item列表中包含项目符号/数字前缀

htmlToFormattable —— HTML —— 格式表

将 HTML 字符串转换为 a FormattableString。为 HTML 设计,由丰富文本编辑器如 提示, (中文(简体) ), 表达器,或 奎尔。 。 。 .

要求数 node-html-parser 作为同伴依赖:

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]

支持的 HTML 元素

元素结果页:1
<strong>, (中文(简体) ), <b>粗体
<em>, (中文(简体) ), <i>斜体
<u>下划线
<s>, (中文(简体) ), <del>, (中文(简体) ), <strike>击穿
<code>内置代码不在里面的时候 <pre>
<pre><code class="language-js">预设块从 language-* 类
<blockquote>块引用连续处理的儿童
<a href="...">链接
<h1> . <h6>粗体
<p>, (中文(简体) ), <div>透明包装儿童与 ""
<br>\n
<ul>未排序列表前缀的项目 -
<ol start="N">命令列表编号项目 start

根部的块级元素由 \n\n。清单项目由 \n内嵌列表得到支持并缩进 \n 在子列表之前.

TipTap 示例

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

使用Telegram Bot API

这个 FormattableString 对象有 .text 财务报告和审定财务报表 .entities 直接映射到Telegram的属性 sendMessage 参数 :

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,
});

与 语法 你可以通过 FormattableString 直接 :

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

丰富的信息和本地表格

对于Telegram Rich Messages ,请使用结构化 table() 需要本地语言时的帮助 InputRichBlockTable 而不是 Markdown 文本 :

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() 也可以直接发送。 第一行默认为页眉,单元格对齐 默认为 left编号 :top启用 blocks.cell("Total", { colSpan: 2 }) 为了跨度。 前一个 Markdown/GFM 序列器为 markdownTable() 标记下成分 rich([...])。 。 。 .

这是一个突破性的变化 从 @gramio/format 0.11: (中文(简体) ) table() 用于生产Markdown/GFM. 重命名现有的 Markdown 呼叫到 markdownTable() 升级到0.12时.

对于由您自己信任的序列器生成的完整的Markdown/HTML字符串,请使用 rawRich()· ; 它保留了保险箱的语法 rich\. ' 尔时tag escapes. Never pass untrusted text to(原始内容存档于2017-03-21). 生Rich().

使用时 rowSpan中,在以下行中省略所覆盖的单元格;列对齐跟随 逻辑表网格.


另见

版本与发布记录

@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 是什么?

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 和提交记录判断。