APP API (英语)
这个API是ATProtocol服务器的客户端. 它使用HTTP进行交流. 它包括:
- ATProto和Bluesky的APIs.
- 验证和完整的打字类型.
- QQ会话管理.
- - 一个RichText图书馆.
[!注]
我们建议使用 法我们的SDK型安全 和Lexicon代码生成, 所有的新项目.
开始
首先安装软件包 :
yarn add @atproto/api
然后在你的申请中:
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的电话都需要经过认证的会话. 有两种方法 管理会议:
基于密码的 App 会话管理
用户名/ 基于密码的认证可以使用 Agent
课.
[叹息]
这种方法被贬值,有利于基于OAuth的会话管理. 没错 建议使用基于 OAuth 会话管理(通过
@atproto/oauth-client-*软件包).
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-客户端浏览器数字 : 用于浏览器.
- @atproto/oauth-客户端-节点: 用于 节点.js.
- @atproto/oauth-客户端数字 : 下层;可兼容大多数JS引擎.
每个 @atproto/oauth-client-* 执行有另一种方式来获得
OAuthSession 实例,可用于即时 Agent (从)
@atproto/api) (中文(简体) ). 以下是恢复先前保存的会话的例子:
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电话
该剂包括许多共同操作的方法,包括:
// 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
}
审定和类型
软件包包括一个完整的类型系统,包括验证和类型护栏。 例如,为了验证邮政记录:
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 帮你处理.
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帮助处理一系列广泛的任务,包括:
- 主持人标签
- 用户变异(包括变异者)
- 用户屏蔽
- 哑词
- 隐藏员额
更多信息,请参见 调和文档。 。 。 .
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名称的方法和记录。 你也可以用在经纪人身上:
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 ,您可以通过
使用自定义获取执行的会话管理器 :
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 (英语) 或者说 http://opensource.org/licenses/MIT 互联网档案馆的存檔,存档日期2013-12-02(中文(简体) )
- Apache 许可证,2.0版本, ((原始内容存档于2017-09-31) (英语). LICENSE-APACHE.txt 或者说 http://www.apache.org/licenses/LICENSE-2.0 (中文(简体) )(中文(简体) )
下游项目和终端用户可自行选择单独或共同发放许可证。 这种双重许可的动机是Apache 2.0提供的额外软件专利保证.