chat-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Chat SDK

Chat SDK

Unified TypeScript SDK for building chat bots across Slack, Teams, Google Chat, Discord, Telegram, GitHub, Linear, and WhatsApp. Write bot logic once, deploy everywhere.
用于跨Slack、Teams、Google Chat、Discord、Telegram、GitHub、Linear和WhatsApp构建聊天机器人的统一TypeScript SDK,只需编写一次机器人逻辑,即可部署到所有平台。

Start with published sources

从已发布资源入手

When Chat SDK is installed in a user project, inspect the published files that ship in
node_modules
:
node_modules/chat/docs/                    # bundled docs
node_modules/chat/dist/index.d.ts          # core API types
node_modules/chat/dist/jsx-runtime.d.ts    # JSX runtime types
node_modules/chat/docs/contributing/       # adapter-authoring docs
node_modules/chat/docs/guides/             # framework/platform guides
If one of the paths below does not exist, that package is not installed in the project yet.
Read these before writing code:
  • node_modules/chat/docs/getting-started.mdx
    — install and setup
  • node_modules/chat/docs/usage.mdx
    Chat
    config and lifecycle
  • node_modules/chat/docs/handling-events.mdx
    — event routing and handlers
  • node_modules/chat/docs/threads-messages-channels.mdx
    — thread/channel/message model
  • node_modules/chat/docs/posting-messages.mdx
    — post, edit, delete, schedule
  • node_modules/chat/docs/streaming.mdx
    — AI SDK integration and streaming semantics
  • node_modules/chat/docs/cards.mdx
    — JSX cards
  • node_modules/chat/docs/actions.mdx
    — button/select interactions
  • node_modules/chat/docs/modals.mdx
    — modal submit/close flows
  • node_modules/chat/docs/slash-commands.mdx
    — slash command routing
  • node_modules/chat/docs/direct-messages.mdx
    — DM behavior and
    openDM()
  • node_modules/chat/docs/files.mdx
    — attachments/uploads
  • node_modules/chat/docs/state.mdx
    — persistence, locking, dedupe
  • node_modules/chat/docs/adapters.mdx
    — cross-platform feature matrix
  • node_modules/chat/docs/api/chat.mdx
    — exact
    Chat
    API
  • node_modules/chat/docs/api/thread.mdx
    — exact
    Thread
    API
  • node_modules/chat/docs/api/message.mdx
    — exact
    Message
    API
  • node_modules/chat/docs/api/modals.mdx
    — modal element and event details
For the specific adapter or state package you are using, inspect that installed package's
dist/index.d.ts
export surface in
node_modules
.
当用户项目中安装了Chat SDK后,可以查看
node_modules
中附带的已发布文件:
node_modules/chat/docs/                    # 打包后的文档
node_modules/chat/dist/index.d.ts          # 核心API类型定义
node_modules/chat/dist/jsx-runtime.d.ts    # JSX运行时类型定义
node_modules/chat/docs/contributing/       # 适配器开发文档
node_modules/chat/docs/guides/             # 框架/平台指南
如果下方的某个路径不存在,说明对应的包尚未安装到项目中。
编写代码前请先阅读以下文档:
  • node_modules/chat/docs/getting-started.mdx
    — 安装与配置
  • node_modules/chat/docs/usage.mdx
    Chat
    配置与生命周期
  • node_modules/chat/docs/handling-events.mdx
    — 事件路由与处理器
  • node_modules/chat/docs/threads-messages-channels.mdx
    — 线程/频道/消息模型
  • node_modules/chat/docs/posting-messages.mdx
    — 发布、编辑、删除、定时发送
  • node_modules/chat/docs/streaming.mdx
    — AI SDK集成与流式语义
  • node_modules/chat/docs/cards.mdx
    — JSX卡片
  • node_modules/chat/docs/actions.mdx
    — 按钮/选择器交互
  • node_modules/chat/docs/modals.mdx
    — 模态框提交/关闭流程
  • node_modules/chat/docs/slash-commands.mdx
    — 斜杠命令路由
  • node_modules/chat/docs/direct-messages.mdx
    — 私信行为与
    openDM()
    方法
  • node_modules/chat/docs/files.mdx
    — 附件/上传
  • node_modules/chat/docs/state.mdx
    — 持久化、锁、去重
  • node_modules/chat/docs/adapters.mdx
    — 跨平台功能矩阵
  • node_modules/chat/docs/api/chat.mdx
    — 完整
    Chat
    API说明
  • node_modules/chat/docs/api/thread.mdx
    — 完整
    Thread
    API说明
  • node_modules/chat/docs/api/message.mdx
    — 完整
    Message
    API说明
  • node_modules/chat/docs/api/modals.mdx
    — 模态框元素与事件详情
如果你使用了特定的适配器或状态包,可以查看
node_modules
中对应已安装包的
dist/index.d.ts
导出内容。

Quick start

快速开始

typescript
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createRedisState } from "@chat-adapter/state-redis";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    slack: createSlackAdapter(),
  },
  state: createRedisState(),
  dedupeTtlMs: 600_000,
});

bot.onNewMention(async (thread) => {
  await thread.subscribe();
  await thread.post("Hello! I'm listening to this thread.");
});

bot.onSubscribedMessage(async (thread, message) => {
  await thread.post(`You said: ${message.text}`);
});
typescript
import { Chat } from "chat";
import { createSlackAdapter } from "@chat-adapter/slack";
import { createRedisState } from "@chat-adapter/state-redis";

const bot = new Chat({
  userName: "mybot",
  adapters: {
    slack: createSlackAdapter(),
  },
  state: createRedisState(),
  dedupeTtlMs: 600_000,
});

bot.onNewMention(async (thread) => {
  await thread.subscribe();
  await thread.post("Hello! I'm listening to this thread.");
});

bot.onSubscribedMessage(async (thread, message) => {
  await thread.post(`You said: ${message.text}`);
});

Core concepts

核心概念

  • Chat — main entry point; coordinates adapters, routing, locks, and state
  • Adapters — platform-specific integrations for Slack, Teams, Google Chat, Discord, Telegram, GitHub, Linear, and WhatsApp
  • State adapters — persistence for subscriptions, locks, dedupe, and thread state
  • Thread — conversation context with
    post()
    ,
    stream()
    ,
    subscribe()
    ,
    setState()
    ,
    startTyping()
  • Message — normalized content with
    text
    ,
    formatted
    , attachments, author info, and platform
    raw
  • Channel — container for threads and top-level posts
  • Chat — 主入口,负责协调适配器、路由、锁和状态
  • Adapters — 针对Slack、Teams、Google Chat、Discord、Telegram、GitHub、Linear、WhatsApp的平台专属集成
  • State adapters — 用于订阅、锁、去重和线程状态的持久化
  • Thread — 会话上下文,提供
    post()
    stream()
    subscribe()
    setState()
    startTyping()
    等方法
  • Message — 标准化内容,包含
    text
    formatted
    、附件、作者信息和平台原生
    raw
    数据
  • Channel — 线程和顶层帖子的容器

Event handlers

事件处理器

HandlerTrigger
onNewMention
Bot @-mentioned in an unsubscribed thread
onDirectMessage
New DM in an unsubscribed DM thread
onSubscribedMessage
Any message in a subscribed thread
onNewMessage(regex)
Regex match in an unsubscribed thread
onReaction(emojis?)
Emoji added or removed
onAction(actionIds?)
Button clicks and select/radio interactions
onModalSubmit(callbackId?)
Modal form submitted
onModalClose(callbackId?)
Modal dismissed/cancelled
onSlashCommand(commands?)
Slash command invocation
onAssistantThreadStarted
Slack assistant thread opened
onAssistantContextChanged
Slack assistant context changed
onAppHomeOpened
Slack App Home opened
onMemberJoinedChannel
Slack member joined channel event
Read
node_modules/chat/docs/handling-events.mdx
,
node_modules/chat/docs/actions.mdx
,
node_modules/chat/docs/modals.mdx
, and
node_modules/chat/docs/slash-commands.mdx
before wiring handlers.
onDirectMessage
behavior is documented in
node_modules/chat/docs/direct-messages.mdx
.
处理器触发条件
onNewMention
机器人在未订阅的线程中被@提及
onDirectMessage
未订阅的私信线程中收到新消息
onSubscribedMessage
已订阅线程中收到任意消息
onNewMessage(regex)
未订阅线程中出现匹配正则表达式的内容
onReaction(emojis?)
表情符号被添加或移除
onAction(actionIds?)
按钮点击、选择器/单选框交互
onModalSubmit(callbackId?)
模态框表单提交
onModalClose(callbackId?)
模态框被关闭/取消
onSlashCommand(commands?)
斜杠命令被调用
onAssistantThreadStarted
Slack助理线程被打开
onAssistantContextChanged
Slack助理上下文变更
onAppHomeOpened
Slack应用主页被打开
onMemberJoinedChannel
Slack成员加入频道事件
在绑定处理器前请先阅读
node_modules/chat/docs/handling-events.mdx
node_modules/chat/docs/actions.mdx
node_modules/chat/docs/modals.mdx
node_modules/chat/docs/slash-commands.mdx
onDirectMessage
的行为说明请参考
node_modules/chat/docs/direct-messages.mdx

Streaming

流式传输

Pass any
AsyncIterable<string>
to
thread.post()
or
thread.stream()
. For AI SDK, prefer
result.fullStream
over
result.textStream
when available so step boundaries are preserved.
typescript
import { ToolLoopAgent } from "ai";

const agent = new ToolLoopAgent({ model: "anthropic/claude-4.5-sonnet" });

bot.onNewMention(async (thread, message) => {
  const result = await agent.stream({ prompt: message.text });
  await thread.post(result.fullStream);
});
Key details:
  • streamingUpdateIntervalMs
    controls post+edit fallback cadence
  • fallbackStreamingPlaceholderText
    defaults to
    "..."
    ; set
    null
    to disable
  • Structured
    StreamChunk
    support is Slack-only; other adapters ignore non-text chunks
你可以将任意
AsyncIterable<string>
传入
thread.post()
thread.stream()
。如果使用AI SDK,优先选用
result.fullStream
而非
result.textStream
,这样可以保留步骤边界。
typescript
import { ToolLoopAgent } from "ai";

const agent = new ToolLoopAgent({ model: "anthropic/claude-4.5-sonnet" });

bot.onNewMention(async (thread, message) => {
  const result = await agent.stream({ prompt: message.text });
  await thread.post(result.fullStream);
});
关键细节:
  • streamingUpdateIntervalMs
    控制发布+编辑的 fallback 节奏
  • fallbackStreamingPlaceholderText
    默认值为
    "..."
    ,设置为
    null
    可禁用
  • 结构化
    StreamChunk
    仅支持Slack,其他适配器会忽略非文本块

Cards and modals (JSX)

卡片与模态框(JSX)

Set
jsxImportSource: "chat"
in
tsconfig.json
.
Card components:
  • Card
    ,
    CardText
    ,
    Section
    ,
    Fields
    ,
    Field
    ,
    Button
    ,
    CardLink
    ,
    LinkButton
    ,
    Actions
    ,
    Select
    ,
    SelectOption
    ,
    RadioSelect
    ,
    Table
    ,
    Image
    ,
    Divider
Modal components:
  • Modal
    ,
    TextInput
    ,
    Select
    ,
    SelectOption
    ,
    RadioSelect
tsx
await thread.post(
  <Card title="Order #1234">
    <CardText>Your order has been received.</CardText>
    <Actions>
      <Button id="approve" style="primary">Approve</Button>
      <Button id="reject" style="danger">Reject</Button>
    </Actions>
  </Card>
);
tsconfig.json
中设置
jsxImportSource: "chat"
卡片组件:
  • Card
    CardText
    Section
    Fields
    Field
    Button
    CardLink
    LinkButton
    Actions
    Select
    SelectOption
    RadioSelect
    Table
    Image
    Divider
模态框组件:
  • Modal
    TextInput
    Select
    SelectOption
    RadioSelect
tsx
await thread.post(
  <Card title="Order #1234">
    <CardText>Your order has been received.</CardText>
    <Actions>
      <Button id="approve" style="primary">Approve</Button>
      <Button id="reject" style="danger">Reject</Button>
    </Actions>
  </Card>
);

Adapter inventory

适配器清单

Official platform adapters

官方平台适配器

PlatformPackageFactory
Slack
@chat-adapter/slack
createSlackAdapter
Microsoft Teams
@chat-adapter/teams
createTeamsAdapter
Google Chat
@chat-adapter/gchat
createGoogleChatAdapter
Discord
@chat-adapter/discord
createDiscordAdapter
GitHub
@chat-adapter/github
createGitHubAdapter
Linear
@chat-adapter/linear
createLinearAdapter
Telegram
@chat-adapter/telegram
createTelegramAdapter
WhatsApp Business Cloud
@chat-adapter/whatsapp
createWhatsAppAdapter
平台包名工厂方法
Slack
@chat-adapter/slack
createSlackAdapter
Microsoft Teams
@chat-adapter/teams
createTeamsAdapter
Google Chat
@chat-adapter/gchat
createGoogleChatAdapter
Discord
@chat-adapter/discord
createDiscordAdapter
GitHub
@chat-adapter/github
createGitHubAdapter
Linear
@chat-adapter/linear
createLinearAdapter
Telegram
@chat-adapter/telegram
createTelegramAdapter
WhatsApp Business Cloud
@chat-adapter/whatsapp
createWhatsAppAdapter

Official state adapters

官方状态适配器

State backendPackageFactory
Redis
@chat-adapter/state-redis
createRedisState
ioredis
@chat-adapter/state-ioredis
createIoRedisState
PostgreSQL
@chat-adapter/state-pg
createPostgresState
Memory
@chat-adapter/state-memory
createMemoryState
状态后端包名工厂方法
Redis
@chat-adapter/state-redis
createRedisState
ioredis
@chat-adapter/state-ioredis
createIoRedisState
PostgreSQL
@chat-adapter/state-pg
createPostgresState
Memory
@chat-adapter/state-memory
createMemoryState

Community adapters

社区适配器

  • chat-state-cloudflare-do
  • @beeper/chat-adapter-matrix
  • chat-adapter-imessage
  • @bitbasti/chat-adapter-webex
  • @resend/chat-sdk-adapter
  • chat-adapter-baileys
  • chat-state-cloudflare-do
  • @beeper/chat-adapter-matrix
  • chat-adapter-imessage
  • @bitbasti/chat-adapter-webex
  • @resend/chat-sdk-adapter
  • chat-adapter-baileys

Coming-soon platform entries

即将支持的平台

  • Instagram
  • Signal
  • X
  • Messenger
  • Instagram
  • Signal
  • X
  • Messenger

Building a custom adapter

构建自定义适配器

Read these published docs first:
  • node_modules/chat/docs/contributing/building.mdx
  • node_modules/chat/docs/contributing/testing.mdx
  • node_modules/chat/docs/contributing/publishing.mdx
Also inspect:
  • node_modules/chat/dist/index.d.ts
    Adapter
    and related interfaces
  • node_modules/@chat-adapter/shared/dist/index.d.ts
    — shared errors and utilities
  • Installed official adapter
    dist/index.d.ts
    files — reference implementations for config and APIs
A custom adapter needs request verification, webhook parsing, message/thread/channel operations, ID encoding/decoding, and a format converter. Use
BaseFormatConverter
from
chat
and shared utilities from
@chat-adapter/shared
.
请先阅读以下已发布文档:
  • node_modules/chat/docs/contributing/building.mdx
  • node_modules/chat/docs/contributing/testing.mdx
  • node_modules/chat/docs/contributing/publishing.mdx
同时可查看:
  • node_modules/chat/dist/index.d.ts
    Adapter
    及相关接口定义
  • node_modules/@chat-adapter/shared/dist/index.d.ts
    — 通用错误和工具方法
  • 已安装的官方适配器的
    dist/index.d.ts
    文件 — 参考配置和API的实现示例
自定义适配器需要实现请求验证、webhook解析、消息/线程/频道操作、ID编码/解码以及格式转换器功能。你可以使用
chat
提供的
BaseFormatConverter
@chat-adapter/shared
的通用工具方法。

Webhook setup

Webhook配置

Each registered adapter exposes
bot.webhooks.<name>
. Wire those directly to your HTTP framework routes. See
node_modules/chat/docs/guides/slack-nextjs.mdx
and
node_modules/chat/docs/guides/discord-nuxt.mdx
for framework-specific route patterns.
每个已注册的适配器都会暴露
bot.webhooks.<name>
,直接将其绑定到你的HTTP框架路由即可。框架专属的路由模式可参考
node_modules/chat/docs/guides/slack-nextjs.mdx
node_modules/chat/docs/guides/discord-nuxt.mdx