gramio
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGramIO
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.js、Bun和Deno上运行,全面覆盖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 for custom Bot API wrappers
@gramio/types - Writing and publishing custom plugins
- 创建或修改Telegram机器人
- 设置机器人命令、回调、内联查询或消息反应
- 构建键盘(回复键盘、内联键盘、移除键盘、强制回复键盘)
- 使用实体格式消息(粗体、斜体、代码、链接、提及)
- 上传/下载文件和媒体
- 管理用户会话或多步骤对话流程(场景)
- 编写自定义插件
- 配置webhook或长轮询
- 处理Telegram Stars支付
- 带频率限制处理的消息广播
- 结合后端认证构建Telegram Mini Apps (TMA)
- 使用Docker容器化机器人
- 使用独立的构建自定义Bot API封装器
@gramio/types - 编写并发布自定义插件
Quick Start
快速开始
bash
npm create gramio bot-name
cd bot-name
npm run devbash
npm create gramio bot-name
cd bot-name
npm run devBasic 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
核心概念
- Method chaining — handlers, hooks, and plugins chain via ,
.command(),.on(), etc. Order matters..extend() - Type-safe context — context is automatically typed based on the update type. Use for type narrowing in generic handlers.
context.is("message") - Plugin system — adds typed properties to context. Register via
new Plugin("name").derive(() => ({ ... })).bot.extend(plugin) - Hooks lifecycle — onStart → (updates with onError) → onStop. API calls: preRequest → call → onResponse/onResponseError.
- Error suppression — returns error instead of throwing.
bot.api.method({ suppress: true }) - Lazy plugins — async plugins (without ) load at
await. Usebot.start()for immediate loading.await - Derive vs Decorate — runs per-update (computed),
.derive()injects static values once..decorate()
- 方法链式调用 — 处理器、钩子和插件通过、
.command()、.on()等方法链式调用。调用顺序至关重要。.extend() - 类型安全上下文 — 上下文会根据更新类型自动推断类型。在通用处理器中使用进行类型收窄。
context.is("message") - 插件系统 — 可为上下文添加类型化属性。通过
new Plugin("name").derive(() => ({ ... }))注册插件。bot.extend(plugin) - 钩子生命周期 — onStart →(带onError的更新)→ onStop。API调用流程:preRequest → 调用 → onResponse/onResponseError。
- 错误抑制 — 会返回错误而非抛出异常。
bot.api.method({ suppress: true }) - 懒加载插件 — 异步插件(不带)会在
await时加载。使用bot.start()可实现立即加载。await - Derive与Decorate — 在每次更新时执行(计算属性),
.derive()仅注入一次静态值。.decorate()
Official Plugins
官方插件
| Plugin | Package | Purpose |
|---|---|---|
| Session | | Persistent per-user data storage |
| Scenes | | Multi-step conversation flows |
| I18n | | Internationalization (TS-native or Fluent) |
| Autoload | | File-based handler loading |
| Prompt | | Interactive single-question prompts |
| Auto Retry | | Retry on 429 rate limits |
| Media Cache | | Cache file_ids |
| Media Group | | Handle album messages |
| Split | | Split long messages |
| Auto Answer CB | | Auto-answer callbacks |
| PostHog | | Analytics + feature flags |
| 插件 | 包名 | 用途 |
|---|---|---|
| 会话管理 | | 持久化用户数据存储 |
| 场景管理 | | 多步骤对话流程 |
| 国际化 | | 国际化(原生TypeScript或Fluent) |
| 自动加载 | | 基于文件的处理器加载 |
| 交互式提示 | | 单问题交互式提示 |
| 自动重试 | | 遇到429频率限制时自动重试 |
| 媒体缓存 | | 缓存file_ids |
| 媒体组处理 | | 处理相册消息 |
| 消息拆分 | | 拆分长消息 |
| 自动回复回调 | | 自动回复回调查询 |
| 数据分析 | | 分析功能+特性开关 |
References
参考文档
Core
核心模块
| Topic | Description | Reference |
|---|---|---|
| Bot Configuration | Constructor, API options, proxy, test DC, debugging | bot-configuration |
| Bot API | Calling methods, suppress, withRetries, type helpers | bot-api |
| Context & Updates | derive, decorate, middleware, start/stop, type narrowing | context |
| Triggers | command, hears, callbackQuery, inlineQuery, reaction | triggers |
| Hooks | onStart, onStop, onError, preRequest, onResponse | hooks |
| Updates & Lifecycle | start/stop options, graceful shutdown (SIGINT/SIGTERM) | updates |
| 主题 | 描述 | 参考链接 |
|---|---|---|
| 机器人配置 | 构造函数、API选项、代理、测试DC、调试 | bot-configuration |
| Bot API | 调用方法、错误抑制、自动重试、类型助手 | bot-api |
| 上下文与更新 | derive、decorate、中间件、启动/停止、类型收窄 | context |
| 触发器 | command、hears、callbackQuery、inlineQuery、reaction | triggers |
| 钩子 | onStart、onStop、onError、preRequest、onResponse | hooks |
| 更新与生命周期 | 启动/停止选项、优雅关闭(SIGINT/SIGTERM) | updates |
Features
功能特性
| Topic | Description | Reference |
|---|---|---|
| Keyboards | Keyboard, InlineKeyboard, layout helpers, styling | keyboards |
| Formatting | bold, italic, code, pre, link, mention, join | formatting |
| Files | MediaUpload, MediaInput, download, Bun.file() | files |
| CallbackData | Type-safe callback data schemas | callback-data |
| Storage | In-memory, Redis, Cloudflare adapters | storage |
| Telegram Stars | Payments, invoices, subscriptions, inline invoices, refunds, test mode | telegram-stars |
| Types | @gramio/types, type helpers, Proxy wrapper, declaration merging | types |
| 主题 | 描述 | 参考链接 |
|---|---|---|
| 键盘 | 普通键盘、内联键盘、布局助手、样式 | keyboards |
| 消息格式化 | 粗体、斜体、代码、预格式化、链接、提及、拼接 | formatting |
| 文件处理 | MediaUpload、MediaInput、下载、Bun.file() | files |
| 回调数据 | 类型安全的回调数据模式 | callback-data |
| 存储 | 内存存储、Redis、Cloudflare适配器 | storage |
| Telegram Stars | 支付、发票、订阅、内联发票、退款、测试模式 | telegram-stars |
| 类型系统 | @gramio/types、类型助手、代理包装器、声明合并 | types |
Infrastructure
基础设施
| Topic | Description | Reference |
|---|---|---|
| Webhook | Framework integration, tunneling, custom handlers | webhook |
| Rate Limits | withRetries, broadcasting, queues | rate-limits |
| Docker | Dockerfile, multi-stage build, Docker Compose | docker |
| TMA | Mini Apps, mkcert HTTPS, @gramio/init-data auth | tma |
| 主题 | 描述 | 参考链接 |
|---|---|---|
| Webhook | 框架集成、隧道、自定义处理器 | webhook |
| 频率限制 | 自动重试、消息广播、队列 | rate-limits |
| Docker | Dockerfile、多阶段构建、Docker Compose | docker |
| TMA | 迷你应用、mkcert HTTPS、@gramio/init-data认证 | tma |
Plugins
插件
| Plugin | Description | Reference |
|---|---|---|
| Session | Per-user data, Redis support | session |
| Scenes | Multi-step flows, state, navigation | scenes |
| I18n | TS-native and Fluent internationalization | i18n |
| Autoload | File-based handler discovery | autoload |
| Prompt | Send + wait for response | prompt |
| Others | auto-retry, media-cache, media-group, split, posthog | other |
| Plugin Development | Writing custom plugins, derive/decorate/error, lazy loading | plugin-development |
| 插件 | 描述 | 参考链接 |
|---|---|---|
| 会话管理 | 每用户数据存储、Redis支持 | session |
| 场景管理 | 多步骤流程、状态、导航 | scenes |
| 国际化 | 原生TypeScript和Fluent国际化 | i18n |
| 自动加载 | 基于文件的处理器发现 | autoload |
| 交互式提示 | 发送消息并等待响应 | prompt |
| 其他插件 | auto-retry、media-cache、media-group、split、posthog | other |
| 插件开发 | 编写自定义插件、derive/decorate/错误处理、懒加载 | plugin-development |
Examples
示例
| Example | Description | File |
|---|---|---|
| Basic bot | Commands, hooks, error handling | basic.ts |
| Keyboards | Reply, inline, columns, conditional | keyboards.ts |
| CallbackData | Type-safe callback schemas | callback-data.ts |
| Formatting | All entity types, join helper | formatting.ts |
| File upload | Path, URL, buffer, media groups | file-upload.ts |
| Error handling | Custom errors, suppress, scoped | error-handling.ts |
| Webhook | Framework integration | webhook.ts |
| Session | Counters, settings, Redis | session.ts |
| Scenes | Registration flow with steps | scenes.ts |
| Telegram Stars | Payments, invoices, refunds | telegram-stars.ts |
| TMA | Elysia server, init-data auth, webhook | tma.ts |
| Docker | Graceful shutdown, webhook/polling toggle | docker.ts |
| 示例 | 描述 | 文件 |
|---|---|---|
| 基础机器人 | 命令、钩子、错误处理 | basic.ts |
| 键盘示例 | 回复键盘、内联键盘、列布局、条件渲染 | keyboards.ts |
| 回调数据 | 类型安全的回调数据模式 | callback-data.ts |
| 消息格式化 | 所有实体类型、拼接助手 | formatting.ts |
| 文件上传 | 路径、URL、缓冲区、媒体组 | file-upload.ts |
| 错误处理 | 自定义错误、错误抑制、作用域 | error-handling.ts |
| Webhook示例 | 框架集成 | webhook.ts |
| 会话管理 | 计数器、设置、Redis | session.ts |
| 场景管理 | 带步骤的注册流程 | scenes.ts |
| Telegram Stars | 支付、发票、退款 | telegram-stars.ts |
| TMA示例 | Elysia服务器、init-data认证、webhook | tma.ts |
| Docker示例 | 优雅关闭、webhook/轮询切换 | docker.ts |