AT Protocolを利用してBlueskyに投稿したり投稿を取得したりなど

AT Protocolを利用して、TypeScriptでBlueskyの自分のアカウントに投稿したり投稿一覧を見たりするメモ。

AT Protocolのインストールとディレクトリ構成

プロジェクトディレクトリ内で@atproto/apiをインストール。ついでにtsconfig.jsonも生成する。

Terminal window
# @atproto/apiをインストール
yarn add @atproto/api
# tsconfig.jsonを生成
npx tsc --init

今回の構成は以下

Terminal window
./projectDir
/node_modules(@atprotoなどが入っている)
package.json
/src(ts/jsファイルを置くディレクトリ)
tsconfig.json
yarn.lock

tsファイルは/src内に作成する。

Blueskyの自分の投稿を取得したりポストしたり

コードは以下。import { BskyAgent }とするとBskyAgentの部分に打ち消し線が入るので(非推奨?)、AtpAgentとして実行。

import { AtpAgent } from '@atproto/api'
// セッションを作成してログイン
const agent = new AtpAgent({
service: 'https://bsky.social'
})
await agent.login({
identifier: 'Blueskyのアカウント名', //@以降
password: 'アプリパスワード'
})

identifierはアカウント名としてるけど、メールアドレスでもいけるっぽい。passwordはログインパスワードでもいけるけど、アプリパスワードにしておくとよさそう。

投稿の取得。

const tl = await agent.getTimeline();
const feed = tl.data.feed;
console.log(feed)

アカウントにポストする。

await agent.post({
text: '投稿のテスト',
createdAt: new Date().toISOString()
})

package.jsonの中身

とりあえず動かすことが目的なので、typeのみ追加した。

{
"type": "module",
"dependencies": {
"@atproto/api": "^0.16.0"
}
}

tsconfig.jsonの中身

/srcを作成しているので、そのあたりを設定。あとtargetあたりを変更している。

{
// Visit https://aka.ms/tsconfig to read more about this file
"compilerOptions": {
//(略)
"baseUrl": ".",
"paths": {
"@atproto/*": ["node_modules/@atproto/*"]
},
// Environment Settings
// See also https://aka.ms/tsconfig/module
"lib": ["ES2023", "dom"],
"module": "nodenext",
"target": "ES2023",
"types": [],
//(略)
}
}

pathsの指定の方法を少し手間取ったけど、TypeScriptの公式ドキュメントがいちばんわかりやすかった。

公式ドキュメント