Created
November 23, 2024 05:32
-
-
Save coreymcmahon/214b1b4a8dbf83a4d4242918889e3297 to your computer and use it in GitHub Desktop.
Post to Bluesky using the AT Protocol API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Put BSKY_USERNAME and BSKY_PASSWORD in your .env file and then run: | |
* deno run --allow-net bsky.ts "Hello, world!" | |
*/ | |
import "jsr:@std/dotenv/load"; | |
const getToken = async () => { | |
const body = JSON.stringify({ | |
identifier: Deno.env.get("BSKY_USERNAME"), | |
password: Deno.env.get("BSKY_PASSWORD"), | |
}); | |
const response = await fetch( | |
`https://bsky.social/xrpc/com.atproto.server.createSession`, | |
{ | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
body, | |
} | |
); | |
const data = await response.json(); | |
return { | |
did: data.did, | |
accessJwt: data.accessJwt, | |
refreshJwt: data.refreshJwt, | |
}; | |
}; | |
const createPost = async (token: string, did: string, post: string) => { | |
const body = JSON.stringify({ | |
repo: did, | |
collection: "app.bsky.feed.post", | |
record: { | |
text: post, | |
createdAt: new Date().toISOString(), | |
}, | |
}); | |
const response = await fetch( | |
`https://bsky.social/xrpc/com.atproto.repo.createRecord`, | |
{ | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
Authorization: `Bearer ${token}`, | |
}, | |
body, | |
} | |
); | |
return await response.json(); | |
}; | |
if (import.meta.main) { | |
if (Deno.args.length !== 1) { | |
console.log('Usage: deno run --allow-net bsky.ts "Hello, world!"'); | |
} else { | |
const token = await getToken(); | |
const response = await createPost(token.accessJwt, token.did, Deno.args[0]); | |
console.log("Posted:", response); | |
} | |
} | |
export { getToken, createPost }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment