@acedatacloud/skills 2026.704.0 → 2026.704.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/skills/bluesky/SKILL.md +72 -121
- package/skills/bluesky/scripts/bluesky.py +345 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@acedatacloud/skills",
|
|
3
|
-
"version": "2026.704.
|
|
3
|
+
"version": "2026.704.1",
|
|
4
4
|
"description": "Agent Skills for AceDataCloud AI services — music, image, video generation, LLM chat, web search. Compatible with Claude Code, GitHub Copilot, Gemini CLI, OpenAI Codex, and 30+ AI coding agents.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
package/skills/bluesky/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: bluesky
|
|
3
|
-
description: Publish, delete and read your own posts on Bluesky via the AT Protocol (XRPC). Use when the user wants to post to their Bluesky account, cross-post an article as a short dev-focused post, delete a post, or list their own recent posts with engagement stats (reposts, likes, replies). Auth uses the user's handle plus an App Password.
|
|
3
|
+
description: Publish (with optional images), delete and read your own posts on Bluesky via the AT Protocol (XRPC). Use when the user wants to post to their Bluesky account (text or 带图 / with a picture), cross-post an article as a short dev-focused post, attach an image, delete a post, or list their own recent posts with engagement stats (reposts, likes, replies). Auth uses the user's handle plus an App Password.
|
|
4
4
|
when_to_use: |
|
|
5
5
|
Trigger when the user wants to publish a post to their Bluesky account,
|
|
6
6
|
delete one, or review their own recent posts and engagement. Bluesky runs on
|
|
@@ -12,152 +12,103 @@ allowed_tools: [Bash]
|
|
|
12
12
|
license: Apache-2.0
|
|
13
13
|
metadata:
|
|
14
14
|
author: acedatacloud
|
|
15
|
-
version: "1.
|
|
15
|
+
version: "1.1"
|
|
16
16
|
---
|
|
17
17
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
per task and reuse the values. The identifier must be a full handle, DID or
|
|
37
|
-
email — normalize a bare username (no `.` / `@`) to `<name>.bsky.social` when
|
|
38
|
-
using the default PDS, otherwise `createSession` returns `AuthenticationRequired`:
|
|
39
|
-
|
|
40
|
-
```bash
|
|
41
|
-
SVC="${BLUESKY_SERVICE:-https://bsky.social}"
|
|
42
|
-
ID="$BLUESKY_HANDLE"
|
|
43
|
-
# Bare username → full handle on the default bsky.social PDS. A dotted handle
|
|
44
|
-
# (custom domain), a DID (`did:...`) or an email are already valid — leave them.
|
|
45
|
-
case "$ID" in
|
|
46
|
-
*.* | *@* | did:*) : ;;
|
|
47
|
-
*) [ "$SVC" = "https://bsky.social" ] && ID="$ID.bsky.social" ;;
|
|
48
|
-
esac
|
|
49
|
-
SESSION=$(curl -sS -X POST "$SVC/xrpc/com.atproto.server.createSession" \
|
|
50
|
-
-H "Content-Type: application/json" \
|
|
51
|
-
-d "$(jq -n --arg id "$ID" --arg pw "$BLUESKY_APP_PASSWORD" \
|
|
52
|
-
'{identifier:$id, password:$pw}')")
|
|
53
|
-
echo "$SESSION" | jq '{did, handle, active}'
|
|
54
|
-
JWT=$(echo "$SESSION" | jq -r .accessJwt)
|
|
55
|
-
DID=$(echo "$SESSION" | jq -r .did)
|
|
18
|
+
Everything runs through the shipped CLI [`scripts/bluesky.py`](scripts/bluesky.py)
|
|
19
|
+
— self-contained (`requests` + `Pillow`, both preinstalled in the sandbox). One
|
|
20
|
+
call creates the session, auto-computes clickable **facets** (links, #hashtags,
|
|
21
|
+
@mentions with correct UTF-8 byte offsets), and for image posts downloads the
|
|
22
|
+
file, **resizes/recompresses it to Bluesky's ~1 MB blob limit**, `uploadBlob`s it
|
|
23
|
+
and builds the `app.bsky.embed.images` embed — so there's no fragile
|
|
24
|
+
`curl + jq + heredoc` to hand-assemble (the old inline recipe kept breaking on
|
|
25
|
+
shell quoting, especially once an image + facets were involved).
|
|
26
|
+
|
|
27
|
+
Three connector credentials are injected: `$BLUESKY_HANDLE`
|
|
28
|
+
(e.g. `name.bsky.social`), `$BLUESKY_APP_PASSWORD` (an App Password from Bluesky
|
|
29
|
+
**Settings → Privacy and Security → App Passwords**, NOT the login password) and
|
|
30
|
+
`$BLUESKY_SERVICE` (PDS base URL, default `https://bsky.social`). The CLI reads
|
|
31
|
+
them from the env — never echo them.
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
BSKY="$SKILL_DIR/scripts/bluesky.py"
|
|
35
|
+
python3 "$BSKY" whoami # verify the session → {did, handle, service}
|
|
56
36
|
```
|
|
57
37
|
|
|
58
|
-
If `
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
38
|
+
If `whoami` fails with `session_failed` / `AuthenticationRequired`, the
|
|
39
|
+
identifier or App Password is wrong. The **#1 cause is a bare handle** — the CLI
|
|
40
|
+
auto-appends `.bsky.social` to a bare username on the default PDS, but if it
|
|
41
|
+
still fails the user must reconnect the connector with their **full** handle
|
|
42
|
+
(`name.bsky.social`, a custom domain, a DID, or the account email) and a valid
|
|
43
|
+
App Password.
|
|
44
|
+
|
|
45
|
+
## Post — text, images and links in one call
|
|
46
|
+
|
|
47
|
+
**Confirm the text with the user before posting** (it publishes as their real
|
|
48
|
+
account). Text ≤ **300 graphemes**. Clickable links / #hashtags / @mentions are
|
|
49
|
+
turned into facets automatically — just write them in the text, no byte-offset
|
|
50
|
+
math needed.
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
# plain text post
|
|
54
|
+
python3 "$BSKY" post --text "Hello Bluesky 👋 shipping with the AT Protocol"
|
|
55
|
+
|
|
56
|
+
# 带图发送 / post WITH an image (URL or local path) — the image is downloaded,
|
|
57
|
+
# resized to fit the blob limit, uploaded and embedded automatically:
|
|
58
|
+
python3 "$BSKY" post \
|
|
59
|
+
--text "Stop wiring 3 image APIs. One endpoint → posters, cards, mockups. https://platform.acedata.cloud/documents/openai-images-generations-integration #AI #API" \
|
|
60
|
+
--image "https://cdn.acedata.cloud/xxxx.png" --alt "AI image API hero"
|
|
61
|
+
|
|
62
|
+
# up to 4 images, each with its own --alt (paired by order)
|
|
63
|
+
python3 "$BSKY" post --text "gallery" --image a.png --alt "one" --image b.png --alt "two"
|
|
79
64
|
```
|
|
80
65
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
```bash
|
|
93
|
-
# text = "New post about #ai" — "#ai" starts at byte 15, ends at byte 18
|
|
94
|
-
curl -sS -X POST "$SVC/xrpc/com.atproto.repo.createRecord" \
|
|
95
|
-
-H "Authorization: Bearer $JWT" -H "Content-Type: application/json" \
|
|
96
|
-
-d "$(jq -n --arg did "$DID" --arg now "$NOW" '
|
|
97
|
-
{repo:$did, collection:"app.bsky.feed.post",
|
|
98
|
-
record:{ "$type":"app.bsky.feed.post", text:"New post about #ai", createdAt:$now,
|
|
99
|
-
facets:[ { index:{byteStart:15, byteEnd:18},
|
|
100
|
-
features:[{ "$type":"app.bsky.richtext.facet#tag", tag:"ai" }] } ] }}')" \
|
|
101
|
-
| jq '{uri, cid}'
|
|
66
|
+
Multi-line text or lots of emoji? Skip shell-quoting headaches by writing the
|
|
67
|
+
text to a file and using `--text-file` (or pipe via `--text -`):
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
cat > /tmp/post.txt <<'EOF'
|
|
71
|
+
Line one 🎨
|
|
72
|
+
|
|
73
|
+
Line two with a link https://platform.acedata.cloud #AI
|
|
74
|
+
EOF
|
|
75
|
+
python3 "$BSKY" post --text-file /tmp/post.txt --image "https://cdn.acedata.cloud/xxxx.png"
|
|
102
76
|
```
|
|
103
77
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
78
|
+
Success prints
|
|
79
|
+
`{"posted":true,"uri":"at://…","url":"https://bsky.app/profile/<handle>/post/<rkey>", ...}`.
|
|
80
|
+
The `url` is the public, shareable link — hand it to the user verbatim.
|
|
107
81
|
|
|
108
82
|
## List my recent posts + engagement
|
|
109
83
|
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
| jq '.feed[] | {uri: .post.uri,
|
|
114
|
-
text: .post.record.text,
|
|
115
|
-
reposts: .post.repostCount,
|
|
116
|
-
likes: .post.likeCount,
|
|
117
|
-
replies: .post.replyCount,
|
|
118
|
-
at: .post.indexedAt}'
|
|
84
|
+
```sh
|
|
85
|
+
python3 "$BSKY" list --limit 20 # default filter: posts_no_replies
|
|
86
|
+
python3 "$BSKY" list --limit 50 --filter posts_with_media
|
|
119
87
|
```
|
|
120
88
|
|
|
121
|
-
`
|
|
122
|
-
`
|
|
89
|
+
`--filter`: `posts_no_replies` | `posts_with_replies` | `posts_with_media` |
|
|
90
|
+
`posts_and_author_threads`. `--limit` max 100.
|
|
123
91
|
|
|
124
92
|
## Delete a post
|
|
125
93
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
```bash
|
|
129
|
-
POST_URI="at://$DID/app.bsky.feed.post/3kabc123xyz"
|
|
130
|
-
RKEY="${POST_URI##*/}"
|
|
131
|
-
curl -sS -X POST "$SVC/xrpc/com.atproto.repo.deleteRecord" \
|
|
132
|
-
-H "Authorization: Bearer $JWT" -H "Content-Type: application/json" \
|
|
133
|
-
-d "$(jq -n --arg did "$DID" --arg rkey "$RKEY" \
|
|
134
|
-
'{repo:$did, collection:"app.bsky.feed.post", rkey:$rkey}')" \
|
|
135
|
-
| jq '{deleted: true, rkey: "'"$RKEY"'"}'
|
|
94
|
+
```sh
|
|
95
|
+
python3 "$BSKY" delete --uri "at://did:plc:xxxx/app.bsky.feed.post/3kabc123xyz"
|
|
136
96
|
```
|
|
137
97
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
## Attaching images (optional)
|
|
142
|
-
|
|
143
|
-
Upload each image via `POST $SVC/xrpc/com.atproto.repo.uploadBlob`
|
|
144
|
-
(`Content-Type: image/jpeg`, raw bytes body, Bearer `$JWT`) → returns a `blob`
|
|
145
|
-
object. Then set `record.embed` to
|
|
146
|
-
`{ "$type":"app.bsky.embed.images", images:[{ alt:"<desc>", image:<blob> }] }`.
|
|
147
|
-
Max 4 images per post; each blob ≲ 1 MB (resize/compress first).
|
|
98
|
+
Pass the full `at://…` post `uri` (from `list` or a prior `post`); the CLI
|
|
99
|
+
extracts the `rkey`. An empty result / `deleted:true` is success.
|
|
148
100
|
|
|
149
101
|
## Gotchas
|
|
150
102
|
|
|
151
103
|
- **App Password, not account password:** creating a session with the real
|
|
152
104
|
login password may be rejected or trip 2FA. Always the App Password from
|
|
153
105
|
Settings → App Passwords.
|
|
154
|
-
- **
|
|
155
|
-
byte
|
|
156
|
-
link highlights the wrong span.
|
|
106
|
+
- **Facets & image resizing are automatic** — the CLI computes link/#tag/@mention
|
|
107
|
+
byte offsets and shrinks oversized images to the ~1 MB blob limit for you.
|
|
157
108
|
- **300 graphemes**, counted as user-perceived characters (emoji = 1).
|
|
158
109
|
- **Rate limits:** the PDS rate-limits writes per account; space out bulk posts
|
|
159
110
|
or you'll get `429 {"error":"RateLimitExceeded"}`.
|
|
160
111
|
- **Self-hosted PDS:** if the user runs their own PDS, `$BLUESKY_SERVICE` points
|
|
161
112
|
there; all XRPC calls target that host, not `bsky.social`.
|
|
162
|
-
- The
|
|
163
|
-
|
|
113
|
+
- The CLI creates a fresh short-lived session on **every** invocation, so an
|
|
114
|
+
expiring `accessJwt` is never a concern — just run the command again.
|
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Bluesky (AT Protocol / XRPC) CLI shipped with the `bluesky` skill.
|
|
3
|
+
|
|
4
|
+
Deps: `requests` + `Pillow` (both preinstalled in the sandbox). One command does
|
|
5
|
+
the whole publish flow that previously had to be hand-assembled from curl + jq +
|
|
6
|
+
python heredocs (and kept breaking on shell quoting):
|
|
7
|
+
|
|
8
|
+
- create a session (handle normalized to a full handle on the default PDS)
|
|
9
|
+
- auto-compute richtext `facets` (clickable links, #hashtags, @mentions) with
|
|
10
|
+
correct UTF-8 byte offsets
|
|
11
|
+
- attach images: download the URL/path, resize/recompress to Bluesky's ~1 MB
|
|
12
|
+
blob limit, `uploadBlob`, and build the `app.bsky.embed.images` embed
|
|
13
|
+
- `createRecord`, then print the public post URL
|
|
14
|
+
|
|
15
|
+
Secrets ($BLUESKY_APP_PASSWORD) are read from the env and never printed.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import io
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
import sys
|
|
24
|
+
from datetime import datetime, timezone
|
|
25
|
+
|
|
26
|
+
import requests
|
|
27
|
+
from PIL import Image
|
|
28
|
+
|
|
29
|
+
# bsky.social's uploadBlob rejects images over ~1 MB; stay safely under it.
|
|
30
|
+
BLOB_LIMIT = 976_560
|
|
31
|
+
URL_RE = re.compile(r"https?://[^\s\]\)]+")
|
|
32
|
+
TAG_RE = re.compile(r"(?<!\w)#([A-Za-z0-9_]+)")
|
|
33
|
+
# A mention target must be a dotted handle (name.bsky.social / custom domain);
|
|
34
|
+
# each dot-separated segment is non-empty so a trailing sentence dot isn't eaten.
|
|
35
|
+
MENTION_RE = re.compile(r"(?<!\w)@([A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+)")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def out(o):
|
|
39
|
+
print(json.dumps(o, ensure_ascii=False))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def die(o):
|
|
43
|
+
out(o)
|
|
44
|
+
sys.exit(1)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def env_service():
|
|
48
|
+
return os.environ.get("BLUESKY_SERVICE", "https://bsky.social").rstrip("/")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def normalize_identifier(handle, svc):
|
|
52
|
+
# A dotted handle, an email or a DID is already valid; a bare username needs
|
|
53
|
+
# `.bsky.social` on the default PDS or createSession returns AuthRequired.
|
|
54
|
+
if any(c in handle for c in ".@") or handle.startswith("did:"):
|
|
55
|
+
return handle
|
|
56
|
+
if svc == "https://bsky.social":
|
|
57
|
+
return f"{handle}.bsky.social"
|
|
58
|
+
return handle
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def create_session(svc):
|
|
62
|
+
handle = os.environ["BLUESKY_HANDLE"]
|
|
63
|
+
pw = os.environ["BLUESKY_APP_PASSWORD"]
|
|
64
|
+
ident = normalize_identifier(handle, svc)
|
|
65
|
+
try:
|
|
66
|
+
r = requests.post(
|
|
67
|
+
f"{svc}/xrpc/com.atproto.server.createSession",
|
|
68
|
+
json={"identifier": ident, "password": pw},
|
|
69
|
+
timeout=30,
|
|
70
|
+
)
|
|
71
|
+
except requests.RequestException as e:
|
|
72
|
+
die({"error": "session_request_failed", "detail": str(e)})
|
|
73
|
+
data = r.json() if r.content else {}
|
|
74
|
+
if r.status_code != 200 or not data.get("accessJwt"):
|
|
75
|
+
die({
|
|
76
|
+
"error": "session_failed",
|
|
77
|
+
"status": r.status_code,
|
|
78
|
+
"detail": data,
|
|
79
|
+
"hint": "reconnect the Bluesky connector with your FULL handle "
|
|
80
|
+
"(e.g. name.bsky.social) and a valid App Password",
|
|
81
|
+
})
|
|
82
|
+
return data["accessJwt"], data["did"], ident
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def byte_index(text, char_index):
|
|
86
|
+
return len(text[:char_index].encode("utf-8"))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def resolve_handle(svc, handle):
|
|
90
|
+
try:
|
|
91
|
+
r = requests.get(
|
|
92
|
+
f"{svc}/xrpc/com.atproto.identity.resolveHandle",
|
|
93
|
+
params={"handle": handle},
|
|
94
|
+
timeout=15,
|
|
95
|
+
)
|
|
96
|
+
if r.status_code == 200:
|
|
97
|
+
return r.json().get("did")
|
|
98
|
+
except requests.RequestException:
|
|
99
|
+
pass
|
|
100
|
+
return None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def build_facets(text, svc):
|
|
104
|
+
"""Compute link / hashtag / mention facets with UTF-8 byte offsets."""
|
|
105
|
+
facets = []
|
|
106
|
+
url_spans = [] # char ranges already claimed by a link facet
|
|
107
|
+
for m in URL_RE.finditer(text):
|
|
108
|
+
uri = m.group(0).rstrip(".,;:)]}'\"") # drop trailing punctuation
|
|
109
|
+
c_start, c_end = m.start(), m.start() + len(uri)
|
|
110
|
+
url_spans.append((c_start, c_end))
|
|
111
|
+
facets.append({
|
|
112
|
+
"index": {"byteStart": byte_index(text, c_start),
|
|
113
|
+
"byteEnd": byte_index(text, c_end)},
|
|
114
|
+
"features": [{"$type": "app.bsky.richtext.facet#link", "uri": uri}],
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
def inside_url(pos):
|
|
118
|
+
# Skip #frag / @x that live inside a URL (e.g. https://x.com/#a) so
|
|
119
|
+
# facets never overlap — atproto rejects overlapping richtext ranges.
|
|
120
|
+
return any(s <= pos < e for s, e in url_spans)
|
|
121
|
+
|
|
122
|
+
for m in TAG_RE.finditer(text):
|
|
123
|
+
if inside_url(m.start()):
|
|
124
|
+
continue
|
|
125
|
+
facets.append({
|
|
126
|
+
"index": {"byteStart": byte_index(text, m.start()),
|
|
127
|
+
"byteEnd": byte_index(text, m.end())},
|
|
128
|
+
"features": [{"$type": "app.bsky.richtext.facet#tag", "tag": m.group(1)}],
|
|
129
|
+
})
|
|
130
|
+
for m in MENTION_RE.finditer(text):
|
|
131
|
+
if inside_url(m.start()):
|
|
132
|
+
continue
|
|
133
|
+
did = resolve_handle(svc, m.group(1))
|
|
134
|
+
if did:
|
|
135
|
+
facets.append({
|
|
136
|
+
"index": {"byteStart": byte_index(text, m.start()),
|
|
137
|
+
"byteEnd": byte_index(text, m.end())},
|
|
138
|
+
"features": [{"$type": "app.bsky.richtext.facet#mention", "did": did}],
|
|
139
|
+
})
|
|
140
|
+
return facets
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def fetch_bytes(src):
|
|
144
|
+
if re.match(r"^https?://", src):
|
|
145
|
+
r = requests.get(src, timeout=120, headers={"User-Agent": "Mozilla/5.0 (bluesky-skill)"})
|
|
146
|
+
r.raise_for_status()
|
|
147
|
+
return r.content
|
|
148
|
+
with open(src, "rb") as f:
|
|
149
|
+
return f.read()
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def compress_to_limit(raw):
|
|
153
|
+
"""Return (bytes, mime) within BLOB_LIMIT, recompressing/resizing if needed."""
|
|
154
|
+
known = {"JPEG": "image/jpeg", "PNG": "image/png", "WEBP": "image/webp", "GIF": "image/gif"}
|
|
155
|
+
try:
|
|
156
|
+
fmt = Image.open(io.BytesIO(raw)).format
|
|
157
|
+
except Exception:
|
|
158
|
+
die({"error": "image_decode_failed", "detail": "could not read the image bytes"})
|
|
159
|
+
# Small AND a format Bluesky handles as-is → upload untouched (keeps PNG
|
|
160
|
+
# transparency / animated GIF). Otherwise fall through and re-encode to JPEG
|
|
161
|
+
# so the blob's bytes always match its declared mimeType.
|
|
162
|
+
if len(raw) <= BLOB_LIMIT and fmt in known:
|
|
163
|
+
return raw, known[fmt]
|
|
164
|
+
|
|
165
|
+
img = Image.open(io.BytesIO(raw))
|
|
166
|
+
if img.mode not in ("RGB", "L"):
|
|
167
|
+
img = img.convert("RGB")
|
|
168
|
+
max_side = max(img.size)
|
|
169
|
+
buf = io.BytesIO()
|
|
170
|
+
for target_side in (max_side, 2048, 1600, 1280, 1024, 800, 640):
|
|
171
|
+
if target_side < max_side:
|
|
172
|
+
ratio = target_side / max_side
|
|
173
|
+
work = img.resize((max(1, int(img.width * ratio)), max(1, int(img.height * ratio))))
|
|
174
|
+
else:
|
|
175
|
+
work = img
|
|
176
|
+
for quality in (90, 85, 80, 70, 60, 50, 40):
|
|
177
|
+
buf = io.BytesIO()
|
|
178
|
+
work.save(buf, format="JPEG", quality=quality, optimize=True)
|
|
179
|
+
if buf.tell() <= BLOB_LIMIT:
|
|
180
|
+
return buf.getvalue(), "image/jpeg"
|
|
181
|
+
# Couldn't get under the limit; return the smallest attempt and let the API decide.
|
|
182
|
+
return buf.getvalue(), "image/jpeg"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def upload_blob(svc, jwt, raw, mime):
|
|
186
|
+
r = requests.post(
|
|
187
|
+
f"{svc}/xrpc/com.atproto.repo.uploadBlob",
|
|
188
|
+
data=raw,
|
|
189
|
+
headers={"Authorization": f"Bearer {jwt}", "Content-Type": mime},
|
|
190
|
+
timeout=120,
|
|
191
|
+
)
|
|
192
|
+
data = r.json() if r.content else {}
|
|
193
|
+
if r.status_code != 200 or "blob" not in data:
|
|
194
|
+
die({"error": "uploadBlob_failed", "status": r.status_code, "detail": data})
|
|
195
|
+
return data["blob"]
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def read_text(a):
|
|
199
|
+
if a.text_file:
|
|
200
|
+
with open(a.text_file, encoding="utf-8") as f:
|
|
201
|
+
return f.read().rstrip("\n")
|
|
202
|
+
if a.text == "-":
|
|
203
|
+
return sys.stdin.read().rstrip("\n")
|
|
204
|
+
if a.text is not None:
|
|
205
|
+
return a.text
|
|
206
|
+
return "" # no text source; caller allows this when images are attached
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def cmd_post(a):
|
|
210
|
+
svc = env_service()
|
|
211
|
+
text = read_text(a)
|
|
212
|
+
images = a.image or []
|
|
213
|
+
if len(images) > 4:
|
|
214
|
+
die({"error": "too_many_images", "detail": "Bluesky allows at most 4 images per post"})
|
|
215
|
+
if not text and not images:
|
|
216
|
+
die({"error": "empty_post", "detail": "a post needs --text/--text-file or at least one --image"})
|
|
217
|
+
jwt, did, ident = create_session(svc)
|
|
218
|
+
record = {
|
|
219
|
+
"$type": "app.bsky.feed.post",
|
|
220
|
+
"text": text,
|
|
221
|
+
"createdAt": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z"),
|
|
222
|
+
"langs": [a.lang],
|
|
223
|
+
}
|
|
224
|
+
facets = build_facets(text, svc)
|
|
225
|
+
if facets:
|
|
226
|
+
record["facets"] = facets
|
|
227
|
+
|
|
228
|
+
if images:
|
|
229
|
+
alts = a.alt or []
|
|
230
|
+
embed_images = []
|
|
231
|
+
for i, src in enumerate(images):
|
|
232
|
+
try:
|
|
233
|
+
raw = fetch_bytes(src)
|
|
234
|
+
except (requests.RequestException, OSError) as e:
|
|
235
|
+
die({"error": "image_fetch_failed", "src": src, "detail": str(e)})
|
|
236
|
+
blob_bytes, mime = compress_to_limit(raw)
|
|
237
|
+
blob = upload_blob(svc, jwt, blob_bytes, mime)
|
|
238
|
+
# Missing alt defaults to empty (never reuse another image's alt).
|
|
239
|
+
alt = alts[i] if i < len(alts) else ""
|
|
240
|
+
embed_images.append({"alt": alt, "image": blob})
|
|
241
|
+
record["embed"] = {"$type": "app.bsky.embed.images", "images": embed_images}
|
|
242
|
+
|
|
243
|
+
r = requests.post(
|
|
244
|
+
f"{svc}/xrpc/com.atproto.repo.createRecord",
|
|
245
|
+
headers={"Authorization": f"Bearer {jwt}", "Content-Type": "application/json"},
|
|
246
|
+
json={"repo": did, "collection": "app.bsky.feed.post", "record": record},
|
|
247
|
+
timeout=60,
|
|
248
|
+
)
|
|
249
|
+
data = r.json() if r.content else {}
|
|
250
|
+
if r.status_code != 200 or "uri" not in data:
|
|
251
|
+
die({"error": "createRecord_failed", "status": r.status_code, "detail": data})
|
|
252
|
+
rkey = data["uri"].rsplit("/", 1)[-1]
|
|
253
|
+
out({
|
|
254
|
+
"posted": True,
|
|
255
|
+
"uri": data["uri"],
|
|
256
|
+
"cid": data.get("cid"),
|
|
257
|
+
"url": f"https://bsky.app/profile/{ident}/post/{rkey}",
|
|
258
|
+
"images": len(images),
|
|
259
|
+
"facets": len(facets),
|
|
260
|
+
})
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def cmd_list(a):
|
|
264
|
+
svc = env_service()
|
|
265
|
+
jwt, did, _ = create_session(svc)
|
|
266
|
+
r = requests.get(
|
|
267
|
+
f"{svc}/xrpc/app.bsky.feed.getAuthorFeed",
|
|
268
|
+
params={"actor": did, "limit": a.limit, "filter": a.filter},
|
|
269
|
+
headers={"Authorization": f"Bearer {jwt}"},
|
|
270
|
+
timeout=30,
|
|
271
|
+
)
|
|
272
|
+
data = r.json() if r.content else {}
|
|
273
|
+
if r.status_code != 200:
|
|
274
|
+
die({"error": "getAuthorFeed_failed", "status": r.status_code, "detail": data})
|
|
275
|
+
out([
|
|
276
|
+
{
|
|
277
|
+
"uri": it["post"]["uri"],
|
|
278
|
+
"text": it["post"]["record"].get("text", ""),
|
|
279
|
+
"reposts": it["post"].get("repostCount", 0),
|
|
280
|
+
"likes": it["post"].get("likeCount", 0),
|
|
281
|
+
"replies": it["post"].get("replyCount", 0),
|
|
282
|
+
"at": it["post"].get("indexedAt"),
|
|
283
|
+
}
|
|
284
|
+
for it in data.get("feed", [])
|
|
285
|
+
])
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def cmd_delete(a):
|
|
289
|
+
svc = env_service()
|
|
290
|
+
jwt, did, _ = create_session(svc)
|
|
291
|
+
rkey = a.uri.rsplit("/", 1)[-1]
|
|
292
|
+
r = requests.post(
|
|
293
|
+
f"{svc}/xrpc/com.atproto.repo.deleteRecord",
|
|
294
|
+
headers={"Authorization": f"Bearer {jwt}", "Content-Type": "application/json"},
|
|
295
|
+
json={"repo": did, "collection": "app.bsky.feed.post", "rkey": rkey},
|
|
296
|
+
timeout=30,
|
|
297
|
+
)
|
|
298
|
+
if r.status_code != 200:
|
|
299
|
+
die({"error": "deleteRecord_failed", "status": r.status_code,
|
|
300
|
+
"detail": r.json() if r.content else {}})
|
|
301
|
+
out({"deleted": True, "rkey": rkey})
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def cmd_whoami(a):
|
|
305
|
+
svc = env_service()
|
|
306
|
+
jwt, did, ident = create_session(svc)
|
|
307
|
+
out({"did": did, "handle": ident, "service": svc, "session": bool(jwt)})
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def main():
|
|
311
|
+
p = argparse.ArgumentParser(prog="bluesky", description="Bluesky AT Protocol CLI")
|
|
312
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
313
|
+
|
|
314
|
+
pp = sub.add_parser("post", help="publish a post (text + optional images + auto facets)")
|
|
315
|
+
pp.add_argument("--text", help='post text (use "-" to read from stdin)')
|
|
316
|
+
pp.add_argument("--text-file", help="read post text from a file (safest for multi-line/emoji)")
|
|
317
|
+
pp.add_argument("--image", action="append", help="image URL or local path (repeatable, max 4)")
|
|
318
|
+
pp.add_argument("--alt", action="append", help="alt text per image (repeatable, paired by order)")
|
|
319
|
+
pp.add_argument("--lang", default="en", help="BCP-47 language tag (default: en)")
|
|
320
|
+
pp.set_defaults(func=cmd_post)
|
|
321
|
+
|
|
322
|
+
pl = sub.add_parser("list", help="list my recent posts with engagement")
|
|
323
|
+
pl.add_argument("--limit", type=int, default=20)
|
|
324
|
+
pl.add_argument("--filter", default="posts_no_replies",
|
|
325
|
+
help="posts_no_replies | posts_with_replies | posts_with_media | posts_and_author_threads")
|
|
326
|
+
pl.set_defaults(func=cmd_list)
|
|
327
|
+
|
|
328
|
+
pd = sub.add_parser("delete", help="delete one of my posts by its at:// uri")
|
|
329
|
+
pd.add_argument("--uri", required=True)
|
|
330
|
+
pd.set_defaults(func=cmd_delete)
|
|
331
|
+
|
|
332
|
+
pw = sub.add_parser("whoami", help="verify the session and show did/handle")
|
|
333
|
+
pw.set_defaults(func=cmd_whoami)
|
|
334
|
+
|
|
335
|
+
a = p.parse_args()
|
|
336
|
+
try:
|
|
337
|
+
a.func(a)
|
|
338
|
+
except SystemExit:
|
|
339
|
+
raise
|
|
340
|
+
except Exception as e:
|
|
341
|
+
die({"error": f"{type(e).__name__}", "detail": str(e)})
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
if __name__ == "__main__":
|
|
345
|
+
main()
|