ci: add a link preview card to Bluesky release posts

The Bluesky app builds the card itself when a link is pasted, the API
doesn't. Uses GitHub's social preview image for the release page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
MoepchiandClaude Opus 5.5 committed 2026-10-07 18:46:00 +00:00
1 parent 3a91a8db07
commit 0aefd4198b
1 file changed
+45 -5
+45 -5
View File
@@ -2,7 +2,7 @@
Reads the release (tag, url, body) as JSON from stdin, e.g. from Reads the release (tag, url, body) as JSON from stdin, e.g. from
`gh release view <tag> --json tagName,url,body`. The post is the first `gh release view <tag> --json tagName,url,body`. The post is the first
paragraph of the release notes plus the link. Notes containing paragraph of the release notes plus the link and a preview card. Notes containing
<!-- no-social --> are skipped. DRY_RUN=true logs in (if credentials are set) <!-- no-social --> are skipped. DRY_RUN=true logs in (if credentials are set)
and prints the post without publishing it. and prints the post without publishing it.
""" """
@@ -10,6 +10,8 @@ import json
import os import os
import re import re
import sys import sys
import time
import urllib.error
import urllib.request import urllib.request
from datetime import datetime, timezone from datetime import datetime, timezone
@@ -35,16 +37,42 @@ def build_post(release: dict) -> str | None:
return f"{head}: {summary}{tail}" if summary else head + tail return f"{head}: {summary}{tail}" if summary else head + tail
def xrpc(method: str, payload: dict, token: str | None = None) -> dict: def xrpc(method: str, payload: dict | bytes, token: str | None = None, content_type: str = "application/json") -> dict:
req = urllib.request.Request( req = urllib.request.Request(
f"https://bsky.social/xrpc/{method}", f"https://bsky.social/xrpc/{method}",
data=json.dumps(payload).encode(), data=payload if isinstance(payload, bytes) else json.dumps(payload).encode(),
headers={"Content-Type": "application/json", **({"Authorization": f"Bearer {token}"} if token else {})}, headers={"Content-Type": content_type, **({"Authorization": f"Bearer {token}"} if token else {})},
) )
with urllib.request.urlopen(req, timeout=30) as res: with urllib.request.urlopen(req, timeout=30) as res:
return json.load(res) return json.load(res)
def fetch(url: str, retries: int = 2) -> tuple[bytes, str]:
req = urllib.request.Request(url, headers={"User-Agent": "webspeak3-release-announcer"})
try:
with urllib.request.urlopen(req, timeout=30) as res:
return res.read(), res.headers.get_content_type()
except urllib.error.HTTPError as err:
if err.code != 429 or not retries: # GitHub's image service throttles bursts now and then
raise
time.sleep(10)
return fetch(url, retries - 1)
def link_card(release: dict, text: str) -> dict:
"""The preview card the Bluesky app would show for a pasted link. The API doesn't build one itself.
The image is GitHub's own social preview for the release page. Its URL takes any cache-busting
segment, so we don't have to scrape the release page (GitHub rate-limits that)."""
url = release["url"]
card = {"uri": url, "title": f"WebSpeak3 {release['tagName']}",
"description": text.split("\n\n")[0].split(": ", 1)[-1]}
path = url.removeprefix("https://github.com/")
image, mime = fetch(f"https://opengraph.githubassets.com/{release['tagName']}/{path}")
if len(image) <= 1_000_000: # Bluesky's blob limit for thumbnails
card["image"] = (image, mime)
return card
def main() -> None: def main() -> None:
release = json.load(sys.stdin) release = json.load(sys.stdin)
text = build_post(release) text = build_post(release)
@@ -52,6 +80,13 @@ def main() -> None:
print("Release notes contain <!-- no-social -->, skipping.") print("Release notes contain <!-- no-social -->, skipping.")
return return
print(text) print(text)
url = release["url"]
try:
card = link_card(release, text)
print(f"Link card: {card['title']} (image: {len(card['image'][0]) if 'image' in card else 'none'} bytes)")
except Exception as err: # a missing preview shouldn't cost us the post
print(f"No link card: {err}")
card = None
dry_run = os.environ.get("DRY_RUN") == "true" dry_run = os.environ.get("DRY_RUN") == "true"
handle, password = os.environ.get("BLUESKY_HANDLE"), os.environ.get("BLUESKY_APP_PASSWORD") handle, password = os.environ.get("BLUESKY_HANDLE"), os.environ.get("BLUESKY_APP_PASSWORD")
@@ -64,7 +99,6 @@ def main() -> None:
return return
# Bluesky doesn't auto-link URLs in API posts; the link needs a facet with UTF-8 byte offsets. # Bluesky doesn't auto-link URLs in API posts; the link needs a facet with UTF-8 byte offsets.
url = release["url"]
start = len(text[: text.rindex(url)].encode()) start = len(text[: text.rindex(url)].encode())
record = { record = {
"$type": "app.bsky.feed.post", "$type": "app.bsky.feed.post",
@@ -76,6 +110,12 @@ def main() -> None:
"features": [{"$type": "app.bsky.richtext.facet#link", "uri": url}], "features": [{"$type": "app.bsky.richtext.facet#link", "uri": url}],
}], }],
} }
if card:
external = {"uri": card["uri"], "title": card["title"], "description": card["description"]}
if "image" in card:
image, mime = card["image"]
external["thumb"] = xrpc("com.atproto.repo.uploadBlob", image, session["accessJwt"], mime)["blob"]
record["embed"] = {"$type": "app.bsky.embed.external", "external": external}
post = xrpc("com.atproto.repo.createRecord", post = xrpc("com.atproto.repo.createRecord",
{"repo": session["did"], "collection": "app.bsky.feed.post", "record": record}, {"repo": session["did"], "collection": "app.bsky.feed.post", "record": record},
session["accessJwt"]) session["accessJwt"])