iTranslated by AI
Automatically Post My Hatena Bookmarks to Bluesky
Since the uncertainty of how long Twitter will remain a reliable platform still continues, I've recently started trying out other SNS platforms in parallel.
About half of my Twitter usage consists of sharing interesting technical articles, so I wanted to start by multi-posting those. However, it seemed unlikely to last long if I had to manually copy and paste every time to other SNS platforms after posting to Twitter once.
Meanwhile, I saw that azu-san was creating a tool for multi-posting to Twitter and Bluesky.
I read that article and took a quick look at the repository as well, but since it was an Electron-based app, it unfortunately didn't quite fit my needs. In my case, I sometimes post from my iPad even at home, and I post from Android when I'm out, so an Electron-based PC-only app would force me to change my style.
I had been thinking about a good way to do this for the past few days. This morning, when I was woken up by the sunrise earlier than my alarm and was still half-asleep, it suddenly occurred to me that if I built a mechanism to use Hatena Bookmark as a data source and automatically multi-post what I save there to various SNS, I could achieve about 80% of what I want. I still frequently save technical articles to Hatena Bookmark, and Hatena Bookmark currently supports Twitter[1] (which might be a concern, as I'll explain later).
Actually, Hatena Bookmark allows you to retrieve a specific user's bookmarks via RSS, so I looked into whether I could easily implement this using Zapier or IFTTT with RSS as the data source. However, while both can use RSS as an input, the only available posting destination was Twitter[2], and they didn't seem to support Bluesky yet.
So, I had no choice but to build it myself. It simply reads the RSS, filters for unposted entries, and posts them to Bluesky. Since I'm in the middle of learning Deno, I decided to write it in Deno for practice.
//
// main.ts
//
// Created by Kesin11 on 2023/06/20.
// Copyright © 2023 Kesin11. Licensed under MIT.
//
import { excludePosted, fetchHatenaBookmarks } from "./hatenab.ts";
import { Bluesky } from "./bluesky.ts";
type metadata = { lastPosted: string };
let lastPosted: Date | undefined = undefined;
try {
const metaFile = await Deno.readTextFile("./metadata.json");
const metadata = JSON.parse(metaFile) as metadata;
lastPosted = (metadata.lastPosted)
? new Date(metadata.lastPosted)
: undefined;
} catch (_error) {}
const bookmarks = await fetchHatenaBookmarks();
const filterdBookmarks = excludePosted(bookmarks, lastPosted);
console.dir(filterdBookmarks);
const bsky = await Bluesky.init();
await bsky.postHatenaBookmarks(filterdBookmarks);
// Assuming excludePosted is sorted in ascending order
const newLastPosted = filterdBookmarks.at(-1)?.date;
if (newLastPosted) {
await Deno.writeTextFile(
"./metadata.json",
JSON.stringify({ lastPosted: newLastPosted.toISOString() } as metadata),
);
}
//
// hatenab.ts
//
// Created by Kesin11 on 2023/06/20.
// Copyright © 2023 Kesin11. Licensed under MIT.
//
import Parser from "npm:rss-parser";
export type RssBookmark = {
date: Date;
isoDate: string;
title: string;
link: string;
content: string;
};
export async function fetchHatenaBookmarks(): Promise<RssBookmark[]> {
const parser: Parser = new Parser({});
const feed = await parser.parseURL(
"https://b.hatena.ne.jp/Kesin/bookmark.rss",
);
return feed.items.map((entry) => {
return {
date: new Date(entry.date),
isoDate: entry.isoDate!,
title: entry.title!,
link: entry.link!,
content: entry.content!,
};
});
}
export function excludePosted(
bookmarks: RssBookmark[],
lastPosted: Date | undefined,
): RssBookmark[] {
if (bookmarks.length === 0) return [];
// If there is no timestamp for the last entry from the previous run, return only the latest entry
if (lastPosted === undefined) {
return [bookmarks.at(0)!];
}
return bookmarks
.toSorted((a, b) => a.date.getTime() - b.date.getTime())
.filter((entry) => entry.date.getTime() > lastPosted.getTime());
}
//
// hatenab.ts
//
// Created by Kesin11 on 2023/06/20.
// Copyright © 2023 Kesin11. Licensed under MIT.
//
// NOTE: For some reason, Deno threw an error saying BskyAgent couldn't be imported directly. Maybe because it's published in CommonJS?
// import { BskyAgent, RichText } from "npm:@atproto/api@0.3.12";
import AtprotoAPI from "npm:@atproto/api@0.3.12";
const { BskyAgent, RichText } = AtprotoAPI;
import { RssBookmark } from "./hatenab.ts";
export class Bluesky {
constructor(public agent: AtprotoAPI.BskyAgent) {}
static async init() {
const agent = new BskyAgent({ service: "https://bsky.social" });
const identifier = Deno.env.get("BLUESKY_IDENTIFIER");
const password = Deno.env.get("BLUESKY_PASSWORD");
if (!identifier || !password) {
throw new Error("BLUESKY_IDENTIFIER or BLUESKY_PASSWORD is not set");
}
await agent.login({ identifier: identifier, password: password });
return new Bluesky(agent);
}
private async post(text: string) {
const rt = new RichText({ text });
await rt.detectFacets(this.agent);
await this.agent.post({
$type: "app.bsky.feed.post",
text: rt.text,
facets: rt.facets,
createdAt: new Date().toISOString(),
});
}
async postHatenaBookmarks(bookmarks: RssBookmark[]) {
for await (const bookmark of bookmarks) {
const text = (bookmark.content !== "")
? `${bookmark.content} ${bookmark.link}`
: `"${bookmark.title}" ${bookmark.link}`;
await this.post(text);
}
}
}
I referred to the following articles for the Bluesky posting part. This was my first time using the Bluesky API, but if you're just posting like this, it's very easy.
As mentioned in azu-san's article, it seems that more complex code is required to achieve rich displays like those on Twitter or Zenn. Since this is just a prototype I came up with today, I'll put that aside for now.
All that's left is to run this script periodically via cron somewhere, and the articles saved to Hatena Bookmark will be automatically posted to Bluesky. After posting, the timestamp of the latest entry is saved in metadata.json. In subsequent runs, it filters for entries after that time, providing a simple way to prevent duplicate posts. While running it via cron in a local environment is fine, you'll need to persist metadata.json if you run it in a clean environment every time, like with GitHub Actions. A quick way to do this would be to save it with actions/cache using an appropriate key.
-
Although the integration once became impossible due to the Twitter turmoil, it has become practical again thanks to a feature that directs you to Twitter after posting. https://bookmark.hatenastaff.com/entry/2023/05/16/150518 ↩︎
-
Incidentally, posting to Twitter is no longer free on either platform and requires a paid plan. ↩︎
Discussion