@acedatacloud/skills 2026.704.0 → 2026.704.2
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/skills/x/SKILL.md +109 -0
- package/skills/x/scripts/x.py +417 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@acedatacloud/skills",
|
|
3
|
-
"version": "2026.704.
|
|
3
|
+
"version": "2026.704.2",
|
|
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()
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: x
|
|
3
|
+
description: Read & act on X (Twitter) with the user's own login cookies (BYOC) — post tweets (text / images / video / threads / replies / quotes), search tweets & users, read timelines and single tweets, like / retweet / follow / delete, and see trends. Use when the user mentions X / Twitter, 发推 / 发推特 / 推特, "我的 Twitter", posting to X, searching X, or reading their X timeline.
|
|
4
|
+
when_to_use: |
|
|
5
|
+
Trigger for anything on the user's X (Twitter) account driven by their own
|
|
6
|
+
login cookie: post a tweet / thread / reply / quote (optionally with images or
|
|
7
|
+
a video), search tweets or users, read their home timeline or a user's tweets,
|
|
8
|
+
look up one tweet, like / retweet / follow / delete, or check trends. This acts
|
|
9
|
+
as the user's REAL account, so every write is gated behind an explicit
|
|
10
|
+
confirmation.
|
|
11
|
+
connections: [x]
|
|
12
|
+
allowed_tools: [Bash]
|
|
13
|
+
license: Apache-2.0
|
|
14
|
+
metadata:
|
|
15
|
+
author: acedatacloud
|
|
16
|
+
version: "1.0"
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
# x — read & post on X (Twitter) via your own cookies
|
|
20
|
+
|
|
21
|
+
Drives the user's **real** X account through X's internal web API via
|
|
22
|
+
[`twikit`](https://github.com/d60/twikit), authenticated by the login cookie they
|
|
23
|
+
captured with the ACE extension. No official API key, no cost.
|
|
24
|
+
|
|
25
|
+
> ⚠️ **Not yet E2E-verified.** Built against twikit's documented API but not run
|
|
26
|
+
> against a live account at build time. The first live run is the verification —
|
|
27
|
+
> if X's internal API drifted it surfaces as a clear error, not silent breakage.
|
|
28
|
+
|
|
29
|
+
The connector injects the cookie jar as an env var:
|
|
30
|
+
|
|
31
|
+
- `X_COOKIES` — a JSON array of cookies (needs at least `auth_token` + `ct0`).
|
|
32
|
+
**Secret — full account access. Never echo or print it.**
|
|
33
|
+
|
|
34
|
+
## Setup — install twikit once per session
|
|
35
|
+
|
|
36
|
+
`twikit` may not be preinstalled; bootstrap it (same pattern as the telegram
|
|
37
|
+
skill), then call the shipped CLI:
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
python3 -c "import twikit" 2>/dev/null || pip install --user --quiet twikit 2>/dev/null || true
|
|
41
|
+
X=$SKILL_DIR/scripts/x.py
|
|
42
|
+
python3 $X whoami # who is logged in
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Read commands (run directly)
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
python3 $X whoami # the logged-in account
|
|
49
|
+
python3 $X search --query "ai agents" --product Latest --limit 20 # Top | Latest | Media
|
|
50
|
+
python3 $X search-users --query "openai" --limit 10
|
|
51
|
+
python3 $X timeline --limit 20 # my home timeline
|
|
52
|
+
python3 $X user-tweets --user elonmusk --type Tweets --limit 20 # Tweets|Replies|Media|Likes
|
|
53
|
+
python3 $X tweet --id 1234567890123456789 # single tweet detail
|
|
54
|
+
python3 $X trends --category trending --limit 20 # trending|for-you|news|sports|entertainment
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`--user` accepts either an `@screen_name` (the `@` is optional) or a numeric id.
|
|
58
|
+
|
|
59
|
+
## Verify the connection first
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
python3 $X whoami
|
|
63
|
+
# → {"id": "...", "screen_name": "...", "followers_count": ...}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
On an auth error the cookie is expired — have the user reconnect at
|
|
67
|
+
<https://auth.acedata.cloud/user/connections>. Do **not** loop-retry.
|
|
68
|
+
|
|
69
|
+
## Write commands — GATED (dry-run unless trailing `--confirm`)
|
|
70
|
+
|
|
71
|
+
Every state-changing command (`post`, `thread`, `like`, `unlike`, `retweet`,
|
|
72
|
+
`unretweet`, `follow`, `unfollow`, `delete`) **dry-runs** without a trailing
|
|
73
|
+
`--confirm`. `--confirm` is honored **only as the last argument**, so a tweet
|
|
74
|
+
body that merely contains "--confirm" can never silently post. Always show the
|
|
75
|
+
dry-run, get an explicit "yes" on the exact text, then re-run with `--confirm`.
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
python3 $X post --text "hello world" # dry-run
|
|
79
|
+
python3 $X post --text "hello world" --confirm # LIVE tweet
|
|
80
|
+
python3 $X post --text "look at this" --media a.jpg,b.png --confirm # up to 4 images (or 1 video)
|
|
81
|
+
python3 $X post --text "great point" --reply-to 123456 --confirm # reply
|
|
82
|
+
python3 $X post --text "worth reading" --quote-url https://x.com/u/status/123 --confirm # quote
|
|
83
|
+
python3 $X thread --text "1/2 first" --text "2/2 second" --confirm # thread (2+ segments)
|
|
84
|
+
python3 $X like --id 123456 --confirm
|
|
85
|
+
python3 $X retweet --id 123456 --confirm
|
|
86
|
+
python3 $X follow --user elonmusk --confirm
|
|
87
|
+
python3 $X delete --id 123456 --confirm # delete one of MY tweets
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- **A confirmed `post` / `thread` is immediately PUBLIC** on the user's real
|
|
91
|
+
account — there is no draft step. Always confirm the exact text first.
|
|
92
|
+
- `--media` takes comma-separated file paths. X allows up to **4 images** OR
|
|
93
|
+
**1 video/GIF** per tweet; for a thread the media attaches to the **first**
|
|
94
|
+
segment only.
|
|
95
|
+
|
|
96
|
+
## Gotchas
|
|
97
|
+
|
|
98
|
+
- **This is the user's real X account.** Confirm before any write — posts are
|
|
99
|
+
immediate and public.
|
|
100
|
+
- **Not E2E-verified** (see the warning above) — expect to validate the first run.
|
|
101
|
+
- **twikit is a scraper of X's non-public API.** It can break when X changes its
|
|
102
|
+
internal endpoints. A `Couldn't get KEY_BYTE indices` / transaction-id error
|
|
103
|
+
means twikit needs upgrading: `pip install --user -U twikit`. An auth error
|
|
104
|
+
means the cookie expired → reconnect.
|
|
105
|
+
- **ToS / rate-limit / ban risk.** This acts through the web API, not the
|
|
106
|
+
official API — high-frequency automation can get the account rate-limited or
|
|
107
|
+
suspended. Keep volume human-like.
|
|
108
|
+
- **Never print `X_COOKIES`** — it is full account access.
|
|
109
|
+
- **DMs are intentionally not exposed** by this skill.
|
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
x — read & act on X (Twitter) with the user's own login cookies (BYOC).
|
|
4
|
+
|
|
5
|
+
Drives X's internal web API through `twikit` (https://github.com/d60/twikit),
|
|
6
|
+
authenticated by the ``auth_token`` + ``ct0`` cookies the user captured with the
|
|
7
|
+
ACE extension. This acts as the user's REAL account, so every state-changing
|
|
8
|
+
command (post / thread / reply / quote / like / retweet / follow / delete) is
|
|
9
|
+
GATED by a trailing ``--confirm`` — without it, the command dry-runs.
|
|
10
|
+
|
|
11
|
+
The connector injects the cookie jar as a JSON env var ``X_COOKIES`` (a JSON list
|
|
12
|
+
of cookie dicts, each with at least ``name`` and ``value``). It is full account
|
|
13
|
+
access — NEVER echo or print it.
|
|
14
|
+
|
|
15
|
+
twikit is a scraper of X's non-public API: it can drift when X changes its
|
|
16
|
+
internal endpoints, and high-frequency use risks rate-limiting or account
|
|
17
|
+
suspension under X's ToS. Errors surface as clear messages rather than silent
|
|
18
|
+
breakage.
|
|
19
|
+
|
|
20
|
+
Examples:
|
|
21
|
+
python3 x.py whoami
|
|
22
|
+
python3 x.py search --query "python" --product Latest --limit 20
|
|
23
|
+
python3 x.py timeline --limit 20
|
|
24
|
+
python3 x.py user-tweets --user elonmusk --type Tweets --limit 20
|
|
25
|
+
python3 x.py tweet --id 1234567890
|
|
26
|
+
python3 x.py trends --category trending
|
|
27
|
+
python3 x.py post --text "hello world" --confirm
|
|
28
|
+
python3 x.py post --text "look" --media a.jpg,b.jpg --confirm
|
|
29
|
+
python3 x.py thread --text "1/2 first" --text "2/2 second" --confirm
|
|
30
|
+
python3 x.py like --id 1234567890 --confirm
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
import argparse
|
|
36
|
+
import asyncio
|
|
37
|
+
import json
|
|
38
|
+
import os
|
|
39
|
+
import sys
|
|
40
|
+
|
|
41
|
+
UA = (
|
|
42
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
|
43
|
+
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
_RAW = sys.argv[1:]
|
|
47
|
+
# --confirm is honored ONLY as the last token, and only one is stripped, so a
|
|
48
|
+
# tweet body that merely contains "--confirm" can never silently confirm a write.
|
|
49
|
+
CONFIRM = bool(_RAW) and _RAW[-1] == "--confirm"
|
|
50
|
+
ARGV = _RAW[:-1] if CONFIRM else list(_RAW)
|
|
51
|
+
|
|
52
|
+
# State-changing commands — dry-run unless the invocation ends with --confirm.
|
|
53
|
+
GATED = {
|
|
54
|
+
"post", "thread", "like", "unlike", "retweet", "unretweet",
|
|
55
|
+
"follow", "unfollow", "delete",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def out(obj) -> None:
|
|
60
|
+
print(json.dumps(obj, ensure_ascii=False, indent=2, default=str))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def die(msg: str, code: int = 1) -> None:
|
|
64
|
+
out({"error": msg})
|
|
65
|
+
sys.exit(code)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def load_cookie_dict() -> dict:
|
|
69
|
+
raw = os.environ.get("X_COOKIES")
|
|
70
|
+
if not raw:
|
|
71
|
+
die("X_COOKIES is not set — connect X (Twitter) at "
|
|
72
|
+
"https://auth.acedata.cloud/user/connections, then retry.")
|
|
73
|
+
try:
|
|
74
|
+
jar = json.loads(raw)
|
|
75
|
+
except json.JSONDecodeError as e:
|
|
76
|
+
die(f"X_COOKIES is not valid JSON: {e}")
|
|
77
|
+
if not isinstance(jar, list):
|
|
78
|
+
die(f"X_COOKIES must be a JSON list of cookies, got {type(jar).__name__}")
|
|
79
|
+
cookies = {}
|
|
80
|
+
for c in jar:
|
|
81
|
+
name, value = c.get("name"), c.get("value")
|
|
82
|
+
if name and value is not None:
|
|
83
|
+
cookies[name] = value
|
|
84
|
+
if "auth_token" not in cookies or "ct0" not in cookies:
|
|
85
|
+
die("X_COOKIES is missing auth_token / ct0 — re-capture the cookie on "
|
|
86
|
+
"x.com with the ACE extension, then reconnect at "
|
|
87
|
+
"https://auth.acedata.cloud/user/connections.")
|
|
88
|
+
return cookies
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def make_client():
|
|
92
|
+
from twikit import Client
|
|
93
|
+
proxy = (
|
|
94
|
+
os.environ.get("X_PROXY")
|
|
95
|
+
or os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy")
|
|
96
|
+
or os.environ.get("ALL_PROXY") or os.environ.get("all_proxy")
|
|
97
|
+
or None
|
|
98
|
+
)
|
|
99
|
+
client = Client("en-US", proxy=proxy, user_agent=UA)
|
|
100
|
+
client.set_cookies(load_cookie_dict())
|
|
101
|
+
return client
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# ── formatting ──────────────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
def fmt_user(u) -> dict:
|
|
107
|
+
return {
|
|
108
|
+
"id": str(getattr(u, "id", "")),
|
|
109
|
+
"name": getattr(u, "name", None),
|
|
110
|
+
"screen_name": getattr(u, "screen_name", None),
|
|
111
|
+
"url": f"https://x.com/{getattr(u, 'screen_name', '')}",
|
|
112
|
+
"followers_count": getattr(u, "followers_count", None),
|
|
113
|
+
"following_count": getattr(u, "following_count", None),
|
|
114
|
+
"statuses_count": getattr(u, "statuses_count", None),
|
|
115
|
+
"verified": getattr(u, "verified", None) or getattr(u, "is_blue_verified", None),
|
|
116
|
+
"description": (getattr(u, "description", None) or "")[:200],
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def fmt_tweet(t) -> dict:
|
|
121
|
+
author = getattr(t, "user", None)
|
|
122
|
+
sn = getattr(author, "screen_name", None) if author else None
|
|
123
|
+
tid = str(getattr(t, "id", ""))
|
|
124
|
+
return {
|
|
125
|
+
"id": tid,
|
|
126
|
+
"text": (getattr(t, "full_text", None) or getattr(t, "text", None) or "")[:280],
|
|
127
|
+
"author": sn,
|
|
128
|
+
"url": f"https://x.com/{sn}/status/{tid}" if sn and tid else None,
|
|
129
|
+
"created_at": getattr(t, "created_at", None),
|
|
130
|
+
"favorite_count": getattr(t, "favorite_count", None),
|
|
131
|
+
"retweet_count": getattr(t, "retweet_count", None),
|
|
132
|
+
"reply_count": getattr(t, "reply_count", None),
|
|
133
|
+
"quote_count": getattr(t, "quote_count", None),
|
|
134
|
+
"view_count": getattr(t, "view_count", None),
|
|
135
|
+
"lang": getattr(t, "lang", None),
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
async def resolve_user(client, target: str):
|
|
140
|
+
t = target.lstrip("@").strip()
|
|
141
|
+
if t.isdigit():
|
|
142
|
+
return await client.get_user_by_id(t)
|
|
143
|
+
return await client.get_user_by_screen_name(t)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ── read commands ───────────────────────────────────────────────────
|
|
147
|
+
|
|
148
|
+
async def cmd_whoami(client, _args):
|
|
149
|
+
u = await client.user()
|
|
150
|
+
out(fmt_user(u))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
async def cmd_search(client, args):
|
|
154
|
+
tweets = await client.search_tweet(args.query, args.product, count=args.limit)
|
|
155
|
+
items = list(tweets)[: args.limit]
|
|
156
|
+
out({"query": args.query, "product": args.product,
|
|
157
|
+
"count": len(items), "tweets": [fmt_tweet(t) for t in items]})
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
async def cmd_search_users(client, args):
|
|
161
|
+
users = await client.search_user(args.query, count=args.limit)
|
|
162
|
+
items = list(users)[: args.limit]
|
|
163
|
+
out({"query": args.query, "count": len(items),
|
|
164
|
+
"users": [fmt_user(u) for u in items]})
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
async def cmd_timeline(client, args):
|
|
168
|
+
tweets = await client.get_latest_timeline(count=args.limit)
|
|
169
|
+
items = list(tweets)[: args.limit]
|
|
170
|
+
out({"count": len(items), "tweets": [fmt_tweet(t) for t in items]})
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
async def cmd_user_tweets(client, args):
|
|
174
|
+
u = await resolve_user(client, args.user)
|
|
175
|
+
tweets = await client.get_user_tweets(u.id, args.type, count=args.limit)
|
|
176
|
+
items = list(tweets)[: args.limit]
|
|
177
|
+
out({"user": fmt_user(u), "type": args.type,
|
|
178
|
+
"count": len(items), "tweets": [fmt_tweet(t) for t in items]})
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
async def cmd_tweet(client, args):
|
|
182
|
+
t = await client.get_tweet_by_id(args.id)
|
|
183
|
+
out(fmt_tweet(t))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
async def cmd_trends(client, args):
|
|
187
|
+
trends = await client.get_trends(args.category, count=args.limit)
|
|
188
|
+
out({"category": args.category,
|
|
189
|
+
"trends": [{"name": getattr(x, "name", None),
|
|
190
|
+
"tweets_count": getattr(x, "tweets_count", None)}
|
|
191
|
+
for x in list(trends)[: args.limit]]})
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# ── write commands (GATED) ──────────────────────────────────────────
|
|
195
|
+
|
|
196
|
+
async def _upload_media(client, media_arg: str) -> list:
|
|
197
|
+
media_ids = []
|
|
198
|
+
for path in [p.strip() for p in media_arg.split(",") if p.strip()]:
|
|
199
|
+
if not os.path.isfile(path):
|
|
200
|
+
die(f"media file not found: {path}")
|
|
201
|
+
media_ids.append(await client.upload_media(path, wait_for_completion=True))
|
|
202
|
+
return media_ids
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _quote_note(args) -> dict:
|
|
206
|
+
return {
|
|
207
|
+
"reply_to": getattr(args, "reply_to", None),
|
|
208
|
+
"quote_url": getattr(args, "quote_url", None),
|
|
209
|
+
"media": getattr(args, "media", None),
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
async def cmd_post(client, args):
|
|
214
|
+
text = (args.text or "").strip()
|
|
215
|
+
if not text and not args.media:
|
|
216
|
+
die("provide --text and/or --media")
|
|
217
|
+
media_ids = await _upload_media(client, args.media) if args.media else None
|
|
218
|
+
tweet = await client.create_tweet(
|
|
219
|
+
text=text, media_ids=media_ids,
|
|
220
|
+
reply_to=args.reply_to, attachment_url=args.quote_url)
|
|
221
|
+
out({"ok": True, "posted": True, **fmt_tweet(tweet)})
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
async def cmd_thread(client, args):
|
|
225
|
+
texts = [t for t in (args.text or []) if t and t.strip()]
|
|
226
|
+
if len(texts) < 2:
|
|
227
|
+
die("a thread needs at least two --text segments")
|
|
228
|
+
media_ids = await _upload_media(client, args.media) if args.media else None
|
|
229
|
+
posted, reply_to = [], None
|
|
230
|
+
for i, text in enumerate(texts):
|
|
231
|
+
tweet = await client.create_tweet(
|
|
232
|
+
text=text.strip(),
|
|
233
|
+
media_ids=media_ids if i == 0 else None,
|
|
234
|
+
reply_to=reply_to)
|
|
235
|
+
reply_to = tweet.id
|
|
236
|
+
posted.append(fmt_tweet(tweet))
|
|
237
|
+
out({"ok": True, "posted": True, "count": len(posted), "tweets": posted})
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
async def cmd_like(client, args):
|
|
241
|
+
await client.favorite_tweet(args.id)
|
|
242
|
+
out({"ok": True, "liked": True, "tweet_id": args.id})
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
async def cmd_unlike(client, args):
|
|
246
|
+
await client.unfavorite_tweet(args.id)
|
|
247
|
+
out({"ok": True, "unliked": True, "tweet_id": args.id})
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
async def cmd_retweet(client, args):
|
|
251
|
+
await client.retweet(args.id)
|
|
252
|
+
out({"ok": True, "retweeted": True, "tweet_id": args.id})
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
async def cmd_unretweet(client, args):
|
|
256
|
+
await client.delete_retweet(args.id)
|
|
257
|
+
out({"ok": True, "unretweeted": True, "tweet_id": args.id})
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
async def cmd_follow(client, args):
|
|
261
|
+
u = await resolve_user(client, args.user)
|
|
262
|
+
await client.follow_user(u.id)
|
|
263
|
+
out({"ok": True, "followed": True, "user": u.screen_name, "user_id": str(u.id)})
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
async def cmd_unfollow(client, args):
|
|
267
|
+
u = await resolve_user(client, args.user)
|
|
268
|
+
await client.unfollow_user(u.id)
|
|
269
|
+
out({"ok": True, "unfollowed": True, "user": u.screen_name, "user_id": str(u.id)})
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
async def cmd_delete(client, args):
|
|
273
|
+
await client.delete_tweet(args.id)
|
|
274
|
+
out({"ok": True, "deleted": True, "tweet_id": args.id})
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def gated_dry_run(args) -> None:
|
|
278
|
+
"""Print what a state-changing command WOULD do, without any network call."""
|
|
279
|
+
cmd = args.command
|
|
280
|
+
fields: dict = {}
|
|
281
|
+
if cmd == "post":
|
|
282
|
+
fields = {"text_preview": (args.text or "")[:280], **_quote_note(args)}
|
|
283
|
+
elif cmd == "thread":
|
|
284
|
+
texts = [t for t in (args.text or []) if t and t.strip()]
|
|
285
|
+
fields = {"segments": len(texts), "preview": [t[:120] for t in texts],
|
|
286
|
+
"media_on_first": args.media}
|
|
287
|
+
elif cmd in ("follow", "unfollow"):
|
|
288
|
+
fields = {"user": args.user}
|
|
289
|
+
else: # like / unlike / retweet / unretweet / delete
|
|
290
|
+
fields = {"tweet_id": args.id}
|
|
291
|
+
out({"dry_run": True, "command": cmd, **fields,
|
|
292
|
+
"note": "Re-run with --confirm as the LAST argument to actually run "
|
|
293
|
+
"this. It acts on the user's REAL X account."})
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
COMMANDS = {
|
|
297
|
+
"whoami": cmd_whoami,
|
|
298
|
+
"search": cmd_search,
|
|
299
|
+
"search-users": cmd_search_users,
|
|
300
|
+
"timeline": cmd_timeline,
|
|
301
|
+
"user-tweets": cmd_user_tweets,
|
|
302
|
+
"tweet": cmd_tweet,
|
|
303
|
+
"trends": cmd_trends,
|
|
304
|
+
"post": cmd_post,
|
|
305
|
+
"thread": cmd_thread,
|
|
306
|
+
"like": cmd_like,
|
|
307
|
+
"unlike": cmd_unlike,
|
|
308
|
+
"retweet": cmd_retweet,
|
|
309
|
+
"unretweet": cmd_unretweet,
|
|
310
|
+
"follow": cmd_follow,
|
|
311
|
+
"unfollow": cmd_unfollow,
|
|
312
|
+
"delete": cmd_delete,
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
317
|
+
p = argparse.ArgumentParser(prog="x.py", description="X (Twitter) cookie CLI")
|
|
318
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
319
|
+
|
|
320
|
+
sub.add_parser("whoami", help="show the logged-in account")
|
|
321
|
+
|
|
322
|
+
sp = sub.add_parser("search", help="search tweets by keyword")
|
|
323
|
+
sp.add_argument("--query", required=True)
|
|
324
|
+
sp.add_argument("--product", choices=["Top", "Latest", "Media"], default="Latest")
|
|
325
|
+
sp.add_argument("--limit", type=int, default=20)
|
|
326
|
+
|
|
327
|
+
sp = sub.add_parser("search-users", help="search users by keyword")
|
|
328
|
+
sp.add_argument("--query", required=True)
|
|
329
|
+
sp.add_argument("--limit", type=int, default=20)
|
|
330
|
+
|
|
331
|
+
sp = sub.add_parser("timeline", help="my home timeline (latest)")
|
|
332
|
+
sp.add_argument("--limit", type=int, default=20)
|
|
333
|
+
|
|
334
|
+
sp = sub.add_parser("user-tweets", help="a user's tweets")
|
|
335
|
+
sp.add_argument("--user", required=True, help="@screen_name or numeric id")
|
|
336
|
+
sp.add_argument("--type", choices=["Tweets", "Replies", "Media", "Likes"],
|
|
337
|
+
default="Tweets")
|
|
338
|
+
sp.add_argument("--limit", type=int, default=20)
|
|
339
|
+
|
|
340
|
+
sp = sub.add_parser("tweet", help="single tweet detail")
|
|
341
|
+
sp.add_argument("--id", required=True)
|
|
342
|
+
|
|
343
|
+
sp = sub.add_parser("trends", help="trending topics")
|
|
344
|
+
sp.add_argument("--category",
|
|
345
|
+
choices=["trending", "for-you", "news", "sports", "entertainment"],
|
|
346
|
+
default="trending")
|
|
347
|
+
sp.add_argument("--limit", type=int, default=20)
|
|
348
|
+
|
|
349
|
+
sp = sub.add_parser("post", help="publish a tweet (GATED by trailing --confirm)")
|
|
350
|
+
sp.add_argument("--text", default="")
|
|
351
|
+
sp.add_argument("--media", help="comma-separated image/video file paths")
|
|
352
|
+
sp.add_argument("--reply-to", dest="reply_to", help="tweet id to reply to")
|
|
353
|
+
sp.add_argument("--quote-url", dest="quote_url", help="tweet URL to quote")
|
|
354
|
+
|
|
355
|
+
sp = sub.add_parser("thread", help="publish a thread (GATED by trailing --confirm)")
|
|
356
|
+
sp.add_argument("--text", action="append", help="one per tweet; repeat 2+ times")
|
|
357
|
+
sp.add_argument("--media", help="comma-separated paths, attached to the FIRST tweet")
|
|
358
|
+
|
|
359
|
+
for name in ("like", "unlike", "retweet", "unretweet", "delete"):
|
|
360
|
+
sp = sub.add_parser(name, help=f"{name} a tweet (GATED by trailing --confirm)")
|
|
361
|
+
sp.add_argument("--id", required=True)
|
|
362
|
+
|
|
363
|
+
for name in ("follow", "unfollow"):
|
|
364
|
+
sp = sub.add_parser(name, help=f"{name} a user (GATED by trailing --confirm)")
|
|
365
|
+
sp.add_argument("--user", required=True, help="@screen_name or numeric id")
|
|
366
|
+
|
|
367
|
+
return p
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
async def run(args) -> None:
|
|
371
|
+
client = make_client()
|
|
372
|
+
await COMMANDS[args.command](client, args)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def main() -> None:
|
|
376
|
+
args = build_parser().parse_args(ARGV)
|
|
377
|
+
# Gated commands dry-run offline (no cookies, no network) unless --confirm.
|
|
378
|
+
if args.command in GATED and not CONFIRM:
|
|
379
|
+
gated_dry_run(args)
|
|
380
|
+
return
|
|
381
|
+
try:
|
|
382
|
+
from twikit.errors import (
|
|
383
|
+
Unauthorized, Forbidden, TooManyRequests, NotFound,
|
|
384
|
+
TweetNotAvailable, UserNotFound, UserUnavailable,
|
|
385
|
+
AccountLocked, AccountSuspended, TwitterException,
|
|
386
|
+
)
|
|
387
|
+
except Exception as e: # twikit not importable
|
|
388
|
+
die(f"twikit is not available: {e}. Install with "
|
|
389
|
+
f"`pip install --user twikit`.")
|
|
390
|
+
try:
|
|
391
|
+
asyncio.run(run(args))
|
|
392
|
+
except (Unauthorized,) as e:
|
|
393
|
+
die(f"auth failed — cookie likely expired. Reconnect X at "
|
|
394
|
+
f"https://auth.acedata.cloud/user/connections. ({e})")
|
|
395
|
+
except (AccountLocked, AccountSuspended) as e:
|
|
396
|
+
die(f"account locked/suspended by X: {e}")
|
|
397
|
+
except TooManyRequests as e:
|
|
398
|
+
die(f"rate limited by X — wait and retry, or slow down. ({e})")
|
|
399
|
+
except (NotFound, TweetNotAvailable, UserNotFound, UserUnavailable) as e:
|
|
400
|
+
die(f"not found / unavailable: {e}")
|
|
401
|
+
except Forbidden as e:
|
|
402
|
+
die(f"forbidden by X (content rule, protected account, or ToS): {e}")
|
|
403
|
+
except TwitterException as e:
|
|
404
|
+
die(f"X API error: {e}")
|
|
405
|
+
except Exception as e:
|
|
406
|
+
# twikit scrapes X's non-public API; a bare error here usually means an
|
|
407
|
+
# expired cookie OR that X changed its internal endpoints and twikit
|
|
408
|
+
# needs upgrading (e.g. "Couldn't get KEY_BYTE indices" = transaction-id
|
|
409
|
+
# bootstrap drift → `pip install --user -U twikit`).
|
|
410
|
+
die(f"X request failed ({type(e).__name__}: {e}). Likely an expired "
|
|
411
|
+
f"cookie — reconnect at https://auth.acedata.cloud/user/connections "
|
|
412
|
+
f"— or twikit drift vs X's internal API (try `pip install --user -U "
|
|
413
|
+
f"twikit`).")
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
if __name__ == "__main__":
|
|
417
|
+
main()
|