# @atproto/api 中文文档

规范地址：https://npmcn.com/package/%40atproto/api/

版本：0\.30\.3
npm 元数据更新时间：2026-11-06T01:44:57.452Z
中文译文更新时间：2026-11-07T03:50:24.779Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40atproto/api
原文对照：https://npmcn.com/package/%40atproto/api/?lang=original
项目主页：https://atproto.com/
源码仓库：https://github.com/bluesky-social/atproto

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

- 包体积（解压后）：10.5 MB，1777 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- Node.js 要求：\>=22
- 运行依赖：8 个
- 首次发布：2022-12-21T19:59:13.976Z
- 最新版本发布：2026-11-06T01:44:57.094Z
- 近 30 天下载量：980692（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：381（近 12 个月 122 个）

## 中文简介

Atproto 和 Bluesky 的客户端库

## 安装

```sh
npm install @atproto/api
```

也可以使用：`pnpm add @atproto/api`、`yarn add @atproto/api`、`bun add @atproto/api`

## README

# APP API (英语)

这个API是ATProtocol服务器的客户端. 它使用HTTP进行交流. 它包括:

-   ATProto和Bluesky的APIs.
-   验证和完整的打字类型.
-   QQ会话管理.
-   \- 一个RichText图书馆.

> \[!注\]
> 
> 我们建议使用 [法](https://github.com/bluesky-social/atproto/tree/main/packages/lex/lex)我们的SDK型安全 和Lexicon代码生成, 所有的新项目.

## 开始

首先安装软件包 :

```sh
yarn add @atproto/api
```

然后在你的申请中:

```typescript
import { Agent, CredentialSession } from '@atproto/api'

const session = new CredentialSession(new URL('https://bsky.social'))
await session.login(account)
const agent = new Agent(session)
```

## 使用量

### 会话管理

大多数API的电话都需要经过认证的会话. 有两种方法 管理会议:

1.  [基于密码的 App 会话管理](https://npmcn.com/package/%40atproto/api/#readme-app-password-based-session-management)
2.  [基于 OAuth 会话管理](https://npmcn.com/package/%40atproto/api/#readme-oauth-based-session-management)

#### 基于密码的 App 会话管理

用户名/ 基于密码的认证可以使用 `Agent` 课.

> \[叹息\]
> 
> 这种方法被贬值,有利于基于OAuth的会话管理. 没错 建议使用基于 OAuth 会话管理(通过 `@atproto/oauth-client-*` 软件包).

```typescript
import { Agent, CredentialSession, type AtpAgentLoginOpts } from '@atproto/api'

// Configure connection to the server with authentification
const account: AtpAgentLoginOpts = {
  identifier: 'your.bsky.social',
  password: 'xxxx-xxxx-xxxx-xxxx',
}

async function authenticate(account: AtpAgentLoginOpts): Promise<Agent> {
  const session = new CredentialSession(new URL('https://example.com'))
  await session.login(account)
  const agent = new Agent(session)
  return agent
}

;(async () => {
  console.log('Authenticating...')
  const agent = await authenticate(account)
  console.log(`Authenticated as from: ${agent.sessionManager.did}`)
})()
```

#### 基于 OAuth 会话管理

根据应用程序所使用的环境, OAuth 客户端 备有:

-   [@atproto/oauth-客户端浏览器](https://www.npmjs.com/package/@atproto/oauth-client-browser)数字 : 用于浏览器.
-   [@atproto/oauth-客户端-节点](https://www.npmjs.com/package/@atproto/oauth-client-node): 用于 节点.js.
-   [@atproto/oauth-客户端](https://www.npmjs.com/package/@atproto/oauth-client)数字 : 下层;可兼容大多数JS引擎.

每个 `@atproto/oauth-client-*` 执行有另一种方式来获得 `OAuthSession` 实例,可用于即时 `Agent` (从) `@atproto/api`) (中文(简体) ). 以下是恢复先前保存的会话的例子:

```typescript
import { Agent } from '@atproto/api'
import { OAuthClient } from '@atproto/oauth-client'

const oauthClient = new OAuthClient({
  // ...
})

const oauthSession = await oauthClient.restore('did:plc:123')

// Instantiate the api Agent using an OAuthSession
const agent = new Agent(oauthSession)
```

### API电话

该剂包括许多共同操作的方法,包括:

```typescript
// The DID of the user currently authenticated (or undefined)
agent.did
agent.accountDid // Throws if the user is not authenticated

// Feeds and content
await agent.getTimeline(params, opts)
await agent.getAuthorFeed(params, opts)
await agent.getPostThread(params, opts)
await agent.getPost(params)
await agent.getPosts(params, opts)
await agent.getLikes(params, opts)
await agent.getRepostedBy(params, opts)
await agent.post(record)
await agent.deletePost(postUri)
await agent.like(uri, cid)
await agent.deleteLike(likeUri)
await agent.repost(uri, cid)
await agent.deleteRepost(repostUri)
await agent.uploadBlob(data, opts)

// Social graph
await agent.getFollows(params, opts)
await agent.getFollowers(params, opts)
await agent.follow(did)
await agent.deleteFollow(followUri)

// Actors
await agent.getProfile(params, opts)
await agent.upsertProfile(updateFn)
await agent.getProfiles(params, opts)
await agent.getSuggestions(params, opts)
await agent.searchActors(params, opts)
await agent.searchActorsTypeahead(params, opts)
await agent.mute(did)
await agent.unmute(did)
await agent.muteModList(listUri)
await agent.unmuteModList(listUri)
await agent.blockModList(listUri)
await agent.unblockModList(listUri)

// Notifications
await agent.listNotifications(params, opts)
await agent.countUnreadNotifications(params, opts)
await agent.updateSeenNotifications()

// Identity
await agent.resolveHandle(params, opts)
await agent.updateHandle(params, opts)

// Legacy: Session management should be performed through the SessionManager
// rather than the Agent instance.
if (agent instanceof AtpAgent) {
  // AtpAgent instances support using different sessions during their lifetime
  await agent.createAccount({ ... }) // session a
  await agent.login({ ... }) // session b
  await agent.resumeSession(savedSession) // session c
}
```

### 审定和类型

软件包包括一个完整的类型系统,包括验证和类型护栏。 例如,为了验证邮政记录:

```typescript
import { AppBskyFeedPost } from '@atproto/api'

const post = {...}
if (AppBskyFeedPost.isRecord(post)) {
  // typescript now recognizes `post` as a AppBskyFeedPost.Record
  // however -- we still need to validate it
  const res = AppBskyFeedPost.validateRecord(post)
  if (res.success) {
    // a valid record
  } else {
    // something is wrong
    console.log(res.error)
  }
}
```

### 丰富文本

一些记录(i)使用 `app.bsky.richtext` 词典. 目前richtext只用于链接和提及,但会随着时间推移被扩展以包括粗体,斜体等.

这是 **强烈的** 建议使用此软件包 `RichText` 图书馆。 Javascript在utf16中编码字符串,而协议(和大多数其他编程环境)则使用utf8. 二人之间的转换很困难,但是 `RichText` 帮你处理.

```typescript
import { RichText } from '@atproto/api'

// creating richtext
const rt = new RichText({
  text: 'Hello @alice.com, check out this link: https://example.com',
})
await rt.detectFacets(agent) // automatically detects mentions and links
const postRecord = {
  $type: 'app.bsky.feed.post',
  text: rt.text,
  facets: rt.facets,
  createdAt: new Date().toISOString(),
}

// rendering as markdown
let markdown = ''
for (const segment of rt.segments()) {
  if (segment.isLink()) {
    markdown += `[${segment.text}](${segment.link?.uri})`
  } else if (segment.isMention()) {
    markdown += `[${segment.text}](https://my-bsky-app.com/user/${segment.mention?.did})`
  } else {
    markdown += segment.text
  }
}

// calculating string lengths
const rt2 = new RichText({ text: 'Hello' })
console.log(rt2.length) // => 5
console.log(rt2.graphemeLength) // => 5
const rt3 = new RichText({ text: '👨‍👩‍👧‍👧' })
console.log(rt3.length) // => 25
console.log(rt3.graphemeLength) // => 1
```

### 调和

运用节制制度是一项具有挑战性的任务,但我们已经尽力为您简化了. 调和API帮助处理一系列广泛的任务,包括:

-   主持人标签
-   用户变异(包括变异者)
-   用户屏蔽
-   哑词
-   隐藏员额

更多信息,请参见 [调和文档](https://npmcn.com/package/%40atproto/api/docs/moderation.md)。 。 。 .

```typescript
import { moderatePost } from '@atproto/api'

// First get the user's moderation prefs and their label definitions
// =

const prefs = await agent.getPreferences()
const labelDefs = await agent.getLabelDefinitions(prefs)

// We call the appropriate moderation function for the content
// =

const postMod = moderatePost(postView, {
  userDid: agent.session.did,
  moderationPrefs: prefs.moderationPrefs,
  labelDefs,
})

// We then use the output to decide how to affect rendering
// =

// in feeds
if (postMod.ui('contentList').filter) {
  // don't include in feeds
}
if (postMod.ui('contentList').blur) {
  // render the whole object behind a cover (use postMod.ui('contentList').blurs to explain)
  if (postMod.ui('contentList').noOverride) {
    // do not allow the cover the be removed
  }
}
if (postMod.ui('contentList').alert || postMod.ui('contentList').inform) {
  // render warnings on the post
  // find the warnings in postMod.ui('contentList').alerts and postMod.ui('contentList').informs
}

// viewed directly
if (postMod.ui('contentView').filter) {
  // don't include in feeds
}
if (postMod.ui('contentView').blur) {
  // render the whole object behind a cover (use postMod.ui('contentView').blurs to explain)
  if (postMod.ui('contentView').noOverride) {
    // do not allow the cover the be removed
  }
}
if (postMod.ui('contentView').alert || postMod.ui('contentView').inform) {
  // render warnings on the post
  // find the warnings in postMod.ui('contentView').alerts and postMod.ui('contentView').informs
}

// post embeds in all contexts
if (postMod.ui('contentMedia').blur) {
  // render the whole object behind a cover (use postMod.ui('contentMedia').blurs to explain)
  if (postMod.ui('contentMedia').noOverride) {
    // do not allow the cover the be removed
  }
}
```

## 高级

### 高级 API 呼叫

以上方法为便利包装. 它涵盖大多数但并非所有可用的方法.

《AT议定书》确定了带有反向DNA名称的方法和记录。 你也可以用在经纪人身上:

```typescript
const res1 = await agent.com.atproto.repo.createRecord({
  did: alice.did,
  collection: 'app.bsky.feed.post',
  record: {
    $type: 'app.bsky.feed.post',
    text: 'Hello, world!',
    createdAt: new Date().toISOString(),
  },
})
const res2 = await agent.com.atproto.repo.listRecords({
  repo: alice.did,
  collection: 'app.bsky.feed.post',
})

const res3 = await agent.app.bsky.feed.post.create(
  { repo: alice.did },
  {
    text: 'Hello, world!',
    createdAt: new Date().toISOString(),
  },
)
const res4 = await agent.app.bsky.feed.post.list({ repo: alice.did })
```

### 非浏览器配置

如果你的环境没有内在的 `fetch` 执行,你需要 提供一个。 通常通过多填充进行.

### 自己拿来

如果你想提供自己的 `fetch` ,您可以通过 使用自定义获取执行的会话管理器 :

```typescript
import { AtpAgent } from '@atproto/api'

const myFetch = (input: RequestInfo | URL, init?: RequestInit) => {
  console.log('requesting', input)
  const response = await globalThis.fetch(input, init)
  console.log('got response', response)
  return response
}

const agent = new AtpAgent({
  service: 'https://example.com',
  fetch: myFetch,
})
```

## 许可证

根据麻省理工学院和Apache 2.0条款,这个项目具有双重许可证:

-   麻省理工学院许可证[LICENSE-MIT.txt (英语)](https://github.com/bluesky-social/atproto/blob/main/LICENSE-MIT.txt) 或者说 [http://opensource.org/licenses/MIT 互联网档案馆的存檔,存档日期2013-12-02](http://opensource.org/licenses/MIT)(中文(简体) )
-   Apache 许可证,2.0版本, ([(原始内容存档于2017-09-31) (英语). LICENSE-APACHE.txt](https://github.com/bluesky-social/atproto/blob/main/LICENSE-APACHE.txt) 或者说 [http://www.apache.org/licenses/LICENSE-2.0 (中文(简体) )](http://www.apache.org/licenses/LICENSE-2.0)(中文(简体) )

下游项目和终端用户可自行选择单独或共同发放许可证。 这种双重许可的动机是Apache 2.0提供的额外软件专利保证.

## 常见问题

### @atproto/api 是什么？

Atproto 和 Bluesky 的客户端库

### 如何安装 @atproto/api？

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

### @atproto/api 支持 TypeScript 吗？

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

### @atproto/api 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @atproto/api 需要什么版本的 Node\.js？

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

### @atproto/api 可以商用吗？

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

### @atproto/api 的下载量有多少？

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

### @atproto/api 还在维护吗？

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

