gramio

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GramIO

GramIO

GramIO is a modern, type-safe Telegram Bot API framework for TypeScript. It runs on Node.js, Bun, and Deno with full Bot API coverage, a composable plugin system, and first-class TypeScript support.
GramIO是一款面向TypeScript的现代化、类型安全的Telegram Bot API框架。它可在Node.jsBunDeno上运行,全面覆盖Bot API,拥有可组合的插件系统,并提供一流的TypeScript支持。

When to Use This Skill

适用场景

  • Creating or modifying Telegram bots
  • Setting up bot commands, callbacks, inline queries, or reactions
  • Building keyboards (reply, inline, remove, force reply)
  • Formatting messages with entities (bold, italic, code, links, mentions)
  • Uploading/downloading files and media
  • Managing user sessions or multi-step conversation flows (scenes)
  • Writing custom plugins
  • Configuring webhooks or long polling
  • Handling payments with Telegram Stars
  • Broadcasting messages with rate limit handling
  • Building Telegram Mini Apps (TMA) with backend auth
  • Containerizing bots with Docker
  • Using standalone
    @gramio/types
    for custom Bot API wrappers
  • Writing and publishing custom plugins
  • 创建或修改Telegram机器人
  • 设置机器人命令、回调、内联查询或消息反应
  • 构建键盘(回复键盘、内联键盘、移除键盘、强制回复键盘)
  • 使用实体格式消息(粗体、斜体、代码、链接、提及)
  • 上传/下载文件和媒体
  • 管理用户会话或多步骤对话流程(场景)
  • 编写自定义插件
  • 配置webhook或长轮询
  • 处理Telegram Stars支付
  • 带频率限制处理的消息广播
  • 结合后端认证构建Telegram Mini Apps (TMA)
  • 使用Docker容器化机器人
  • 使用独立的
    @gramio/types
    构建自定义Bot API封装器
  • 编写并发布自定义插件

Quick Start

快速开始

bash
npm create gramio bot-name
cd bot-name
npm run dev
bash
npm create gramio bot-name
cd bot-name
npm run dev

Basic Pattern

基础模式

typescript
import { Bot } from "gramio";

const bot = new Bot(process.env.BOT_TOKEN as string)
    .command("start", (context) => context.send("Hello!"))
    .onStart(({ info }) => console.log(`@${info.username} started`))
    .onError(({ context, kind, error }) => console.error(`[${kind}]`, error));

bot.start();
typescript
import { Bot } from "gramio";

const bot = new Bot(process.env.BOT_TOKEN as string)
    .command("start", (context) => context.send("Hello!"))
    .onStart(({ info }) => console.log(`@${info.username} started`))
    .onError(({ context, kind, error }) => console.error(`[${kind}]`, error));

bot.start();

Critical Concepts

核心概念

  1. Method chaining — handlers, hooks, and plugins chain via
    .command()
    ,
    .on()
    ,
    .extend()
    , etc. Order matters.
  2. Type-safe context — context is automatically typed based on the update type. Use
    context.is("message")
    for type narrowing in generic handlers.
  3. Plugin system
    new Plugin("name").derive(() => ({ ... }))
    adds typed properties to context. Register via
    bot.extend(plugin)
    .
  4. Hooks lifecycle — onStart → (updates with onError) → onStop. API calls: preRequest → call → onResponse/onResponseError.
  5. Error suppression
    bot.api.method({ suppress: true })
    returns error instead of throwing.
  6. Lazy plugins — async plugins (without
    await
    ) load at
    bot.start()
    . Use
    await
    for immediate loading.
  7. Derive vs Decorate
    .derive()
    runs per-update (computed),
    .decorate()
    injects static values once.
  1. 方法链式调用 — 处理器、钩子和插件通过
    .command()
    .on()
    .extend()
    等方法链式调用。调用顺序至关重要。
  2. 类型安全上下文 — 上下文会根据更新类型自动推断类型。在通用处理器中使用
    context.is("message")
    进行类型收窄。
  3. 插件系统
    new Plugin("name").derive(() => ({ ... }))
    可为上下文添加类型化属性。通过
    bot.extend(plugin)
    注册插件。
  4. 钩子生命周期 — onStart →(带onError的更新)→ onStop。API调用流程:preRequest → 调用 → onResponse/onResponseError。
  5. 错误抑制
    bot.api.method({ suppress: true })
    会返回错误而非抛出异常。
  6. 懒加载插件 — 异步插件(不带
    await
    )会在
    bot.start()
    时加载。使用
    await
    可实现立即加载。
  7. Derive与Decorate
    .derive()
    在每次更新时执行(计算属性),
    .decorate()
    仅注入一次静态值。

Official Plugins

官方插件

PluginPackagePurpose
Session
@gramio/session
Persistent per-user data storage
Scenes
@gramio/scenes
Multi-step conversation flows
I18n
@gramio/i18n
Internationalization (TS-native or Fluent)
Autoload
@gramio/autoload
File-based handler loading
Prompt
@gramio/prompt
Interactive single-question prompts
Auto Retry
@gramio/auto-retry
Retry on 429 rate limits
Media Cache
@gramio/media-cache
Cache file_ids
Media Group
@gramio/media-group
Handle album messages
Split
@gramio/split
Split long messages
Auto Answer CB
@gramio/auto-answer-callback-query
Auto-answer callbacks
PostHog
@gramio/posthog
Analytics + feature flags
插件包名用途
会话管理
@gramio/session
持久化用户数据存储
场景管理
@gramio/scenes
多步骤对话流程
国际化
@gramio/i18n
国际化(原生TypeScript或Fluent)
自动加载
@gramio/autoload
基于文件的处理器加载
交互式提示
@gramio/prompt
单问题交互式提示
自动重试
@gramio/auto-retry
遇到429频率限制时自动重试
媒体缓存
@gramio/media-cache
缓存file_ids
媒体组处理
@gramio/media-group
处理相册消息
消息拆分
@gramio/split
拆分长消息
自动回复回调
@gramio/auto-answer-callback-query
自动回复回调查询
数据分析
@gramio/posthog
分析功能+特性开关

References

参考文档

Core

核心模块

TopicDescriptionReference
Bot ConfigurationConstructor, API options, proxy, test DC, debuggingbot-configuration
Bot APICalling methods, suppress, withRetries, type helpersbot-api
Context & Updatesderive, decorate, middleware, start/stop, type narrowingcontext
Triggerscommand, hears, callbackQuery, inlineQuery, reactiontriggers
HooksonStart, onStop, onError, preRequest, onResponsehooks
Updates & Lifecyclestart/stop options, graceful shutdown (SIGINT/SIGTERM)updates
主题描述参考链接
机器人配置构造函数、API选项、代理、测试DC、调试bot-configuration
Bot API调用方法、错误抑制、自动重试、类型助手bot-api
上下文与更新derive、decorate、中间件、启动/停止、类型收窄context
触发器command、hears、callbackQuery、inlineQuery、reactiontriggers
钩子onStart、onStop、onError、preRequest、onResponsehooks
更新与生命周期启动/停止选项、优雅关闭(SIGINT/SIGTERM)updates

Features

功能特性

TopicDescriptionReference
KeyboardsKeyboard, InlineKeyboard, layout helpers, stylingkeyboards
Formattingbold, italic, code, pre, link, mention, joinformatting
FilesMediaUpload, MediaInput, download, Bun.file()files
CallbackDataType-safe callback data schemascallback-data
StorageIn-memory, Redis, Cloudflare adaptersstorage
Telegram StarsPayments, invoices, subscriptions, inline invoices, refunds, test modetelegram-stars
Types@gramio/types, type helpers, Proxy wrapper, declaration mergingtypes
主题描述参考链接
键盘普通键盘、内联键盘、布局助手、样式keyboards
消息格式化粗体、斜体、代码、预格式化、链接、提及、拼接formatting
文件处理MediaUpload、MediaInput、下载、Bun.file()files
回调数据类型安全的回调数据模式callback-data
存储内存存储、Redis、Cloudflare适配器storage
Telegram Stars支付、发票、订阅、内联发票、退款、测试模式telegram-stars
类型系统@gramio/types、类型助手、代理包装器、声明合并types

Infrastructure

基础设施

TopicDescriptionReference
WebhookFramework integration, tunneling, custom handlerswebhook
Rate LimitswithRetries, broadcasting, queuesrate-limits
DockerDockerfile, multi-stage build, Docker Composedocker
TMAMini Apps, mkcert HTTPS, @gramio/init-data authtma
主题描述参考链接
Webhook框架集成、隧道、自定义处理器webhook
频率限制自动重试、消息广播、队列rate-limits
DockerDockerfile、多阶段构建、Docker Composedocker
TMA迷你应用、mkcert HTTPS、@gramio/init-data认证tma

Plugins

插件

PluginDescriptionReference
SessionPer-user data, Redis supportsession
ScenesMulti-step flows, state, navigationscenes
I18nTS-native and Fluent internationalizationi18n
AutoloadFile-based handler discoveryautoload
PromptSend + wait for responseprompt
Othersauto-retry, media-cache, media-group, split, posthogother
Plugin DevelopmentWriting custom plugins, derive/decorate/error, lazy loadingplugin-development
插件描述参考链接
会话管理每用户数据存储、Redis支持session
场景管理多步骤流程、状态、导航scenes
国际化原生TypeScript和Fluent国际化i18n
自动加载基于文件的处理器发现autoload
交互式提示发送消息并等待响应prompt
其他插件auto-retry、media-cache、media-group、split、posthogother
插件开发编写自定义插件、derive/decorate/错误处理、懒加载plugin-development

Examples

示例

ExampleDescriptionFile
Basic botCommands, hooks, error handlingbasic.ts
KeyboardsReply, inline, columns, conditionalkeyboards.ts
CallbackDataType-safe callback schemascallback-data.ts
FormattingAll entity types, join helperformatting.ts
File uploadPath, URL, buffer, media groupsfile-upload.ts
Error handlingCustom errors, suppress, scopederror-handling.ts
WebhookFramework integrationwebhook.ts
SessionCounters, settings, Redissession.ts
ScenesRegistration flow with stepsscenes.ts
Telegram StarsPayments, invoices, refundstelegram-stars.ts
TMAElysia server, init-data auth, webhooktma.ts
DockerGraceful shutdown, webhook/polling toggledocker.ts
示例描述文件
基础机器人命令、钩子、错误处理basic.ts
键盘示例回复键盘、内联键盘、列布局、条件渲染keyboards.ts
回调数据类型安全的回调数据模式callback-data.ts
消息格式化所有实体类型、拼接助手formatting.ts
文件上传路径、URL、缓冲区、媒体组file-upload.ts
错误处理自定义错误、错误抑制、作用域error-handling.ts
Webhook示例框架集成webhook.ts
会话管理计数器、设置、Redissession.ts
场景管理带步骤的注册流程scenes.ts
Telegram Stars支付、发票、退款telegram-stars.ts
TMA示例Elysia服务器、init-data认证、webhooktma.ts
Docker示例优雅关闭、webhook/轮询切换docker.ts