AT Protocolを利用してBlueskyに投稿したり投稿を取得したりなど
AT Protocolを利用して、TypeScriptでBlueskyの自分のアカウントに投稿したり投稿一覧を見たりするメモ。
AT Protocolのインストールとディレクトリ構成
プロジェクトディレクトリ内で@atproto/apiをインストール。ついでにtsconfig.json
も生成する。
# @atproto/apiをインストールyarn add @atproto/api
# tsconfig.jsonを生成npx tsc --init
今回の構成は以下
./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の公式ドキュメントがいちばんわかりやすかった。