# @botpress/chat 中文文档

规范地址：https://npmcn.com/package/%40botpress/chat/

版本：1\.1\.0
npm 元数据更新时间：2026-09-02T19:11:16.748Z
中文译文更新时间：2026-11-08T12:23:38.514Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40botpress/chat
原文对照：https://npmcn.com/package/%40botpress/chat/?lang=original
项目主页：https://github.com/botpress/botpress#readme
源码仓库：https://github.com/botpress/botpress

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：14.9 MB，80 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：^20\.19\.0 \|\| ^22\.12\.0 \|\| \>=23\.0\.0
- 运行依赖：8 个
- 首次发布：2023-10-03T17:47:48.144Z
- 最新版本发布：2026-07-24T16:21:10.525Z
- 近 30 天下载量：37153（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：31（近 12 个月 4 个）

## 中文简介

Botpress 聊天 API 客户端

## 安装

```sh
npm install @botpress/chat
```

也可以使用：`pnpm add @botpress/chat`、`yarn add @botpress/chat`、`bun add @botpress/chat`

## README

# 聊天客户端

## 安装

```bash
npm install @botpress/chat # for npm
yarn add @botpress/chat # for yarn
pnpm add @botpress/chat # for pnpm
```

## 使用量

### API 查询

这个 `@botpress/chat` 软件包导出 a `Client` 可与 Botpress Chat API 交互的类.

```ts
import _ from 'lodash'
import * as chat from '@botpress/chat'

const main = async () => {
  /**
   * You can find your webhook id in the the Botpress Dashboard.
   * Navigate to your bot's Chat Integration configuration. Look for:
   * https://webhook.botpress.cloud/$YOUR_WEBHOOK_ID
   */
  const webhookId = process.env.WEBHOOK_ID
  if (!webhookId) {
    throw new Error('WEBHOOK_ID is required')
  }

  // 0. connect and create a user
  const client = await chat.Client.connect({ webhookId })

  // 1. create a conversation
  const { conversation } = await client.createConversation({})

  // 2. send a message
  await client.createMessage({
    conversationId: conversation.id,
    payload: {
      type: 'text',
      text: 'hello world',
    },
  })

  // 3. sleep for a bit
  await new Promise((resolve) => setTimeout(resolve, 2000))

  // 4. list messages
  const { messages } = await client
    .listMessages({
      conversationId: conversation.id,
    })
    .then(({ messages }) => ({
      messages: _.sortBy(messages, (m) => new Date(m.createdAt).getTime()),
    }))

  const botResponse = messages[1]
  console.log("Bot's response:", botResponse.payload)
}

void main()
  .then(() => {
    console.log('done')
    process.exit(0)
  })
  .catch((err) => {
    console.error(err)
    process.exit(1)
  })
```

### 实时事件

也可以实时收听消息和事件.

```ts
// ...

const listener = await client.listenConversation({
  id: conversation.id,
})

const botResponse = await new Promise<chat.Message>((resolve) => {
  const onMessage = (ev: chat.Signals['message_created']) => {
    if (ev.userId === client.user.id) {
      // message created by my current user, ignoring...
      return
    }
    listener.off('message_created', onMessage)
    resolve(ev)
  }
  listener.on('message_created', onMessage)
})

console.log("Bot's response:", botResponse.payload)
```

### 重新连接

这个 `Client` 如果连接丢失,类不会自动重接服务器。 这允许你处理重联的方式 对你的应用程序有道理。 当连接丢失时, 您可以监听 `error` 事件:

```ts
const state = { messages } // your application state

const onDisconnection = async () => {
  try {
    await listener.connect()
    const { messages } = await client.listMessages({ conversationId: conversation.id })
    state.messages = messages
  } catch (thrown) {
    console.error('failed to reconnect, retrying...', thrown)
    setTimeout(onDisconnection, 1000) // consider using a backoff strategy
  }
}

listener.on('error', (err) => {
  console.error('connection lost', err)
  void onDisconnection()
})
```

## 常见问题

### @botpress/chat 是什么？

Botpress 聊天 API 客户端

### 如何安装 @botpress/chat？

在项目目录运行 npm install @botpress/chat，或使用 pnpm add / yarn add / bun add。

### @botpress/chat 支持 TypeScript 吗？

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

### @botpress/chat 支持 ESM 还是 CommonJS？

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

### @botpress/chat 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js ^20\.19\.0 \|\| ^22\.12\.0 \|\| \>=23\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @botpress/chat 可以商用吗？

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

### @botpress/chat 的下载量有多少？

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

### @botpress/chat 还在维护吗？

最新版本 1\.1\.0 发布于 2026/07/25（3 个月前）；至今共发布 31 个版本，其中过去 12 个月发布了 4 个；首次发布于 2023/10/04。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

