@acedatacloud/skills 2026.621.2 → 2026.621.4

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acedatacloud/skills",
3
- "version": "2026.621.2",
3
+ "version": "2026.621.4",
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",
@@ -0,0 +1,97 @@
1
+ ---
2
+ name: cn-blog
3
+ description: Read and publish on Chinese content platforms with the user's own login cookies (BYOC) — list their published articles with vote/comment stats, inspect one article, and publish a new article. Use when the user mentions 知乎 / Zhihu, "我的知乎文章", reading their article stats (点赞/评论), or publishing/发文 to Zhihu.
4
+ when_to_use: |
5
+ Trigger for anything on the user's Zhihu (知乎) account driven by their own
6
+ login cookie: show who they are, list their published articles with
7
+ vote-up / comment counts, look at one article's stats, or publish a new
8
+ article. This acts as the user's real account, so writes are gated behind
9
+ an explicit confirmation.
10
+ connections: [zhihu]
11
+ allowed_tools: [Bash]
12
+ license: Apache-2.0
13
+ metadata:
14
+ author: acedatacloud
15
+ version: "1.0"
16
+ ---
17
+
18
+ # cn-blog — Zhihu via your own cookies
19
+
20
+ Drives the user's **real** Zhihu account through the same web APIs the site's
21
+ own editor uses, authenticated by the login cookie they captured with the ACE
22
+ extension. No browser, no third-party deps — just `urllib`.
23
+
24
+ The connector injects the cookie jar as an env var:
25
+
26
+ - `ZHIHU_COOKIES` — a JSON array of `{name, value, domain, path, ...}` cookies.
27
+ **Secret — never echo or print it.** The CLI reads it for you.
28
+
29
+ ## CLI
30
+
31
+ The skill ships [`scripts/blog.py`](scripts/blog.py) — self-contained, stdlib only.
32
+
33
+ ```sh
34
+ BLOG=$SKILL_DIR/scripts/blog.py
35
+
36
+ # Read (run directly)
37
+ python3 $BLOG whoami # who is logged in
38
+ python3 $BLOG articles --limit 20 # my published articles + stats
39
+ python3 $BLOG article <article-id> # one article's details + stats
40
+ ```
41
+
42
+ ## Verify the connection first
43
+
44
+ ```sh
45
+ python3 $BLOG whoami
46
+ # → {"id": "...", "name": "崔庆才丨静觅", "url_token": "cui-qing-cai", ...}
47
+ ```
48
+
49
+ On a `401`/`403` the cookie is expired — tell the user to reconnect at
50
+ <https://auth.acedata.cloud/user/connections> (re-capture with the ACE
51
+ extension). Do **not** retry in a loop.
52
+
53
+ ## Reading recipes
54
+
55
+ | Goal | Command |
56
+ |---|---|
57
+ | Who am I | `python3 $BLOG whoami` |
58
+ | My latest articles + vote/comment counts | `python3 $BLOG articles --limit 20` |
59
+ | Next page | `python3 $BLOG articles --limit 20 --offset 20` |
60
+ | One article's stats | `python3 $BLOG article <id>` |
61
+
62
+ Stats come straight from Zhihu: `voteup_count` (赞同), `comment_count` (评论).
63
+ Zhihu does not expose per-article read counts on these endpoints.
64
+
65
+ ## Publishing — GATED (dry-run unless trailing `--confirm`)
66
+
67
+ `publish` writes to the user's real account. Without a trailing `--confirm` it
68
+ **dry-runs** (prints what it would do, changes nothing). `--confirm` is honored
69
+ **only as the last argument**, so a title/content containing "--confirm" can
70
+ never silently go live. Always show the dry-run to the user, get an explicit
71
+ "yes", then re-run with `--confirm` last.
72
+
73
+ ```sh
74
+ # Content is HTML. For Markdown, convert to HTML first.
75
+ python3 $BLOG publish --title "标题" --content-file article.html # dry-run
76
+ python3 $BLOG publish --title "标题" --content-file article.html --draft-only --confirm # save a private draft
77
+ python3 $BLOG publish --title "标题" --content-file article.html --confirm # PUBLIC, goes live
78
+ ```
79
+
80
+ - `--draft-only` stops after saving a private draft (safe — nothing public).
81
+ - Without `--draft-only`, the article is **published publicly** under the user's
82
+ name. Default to `--draft-only` unless the user clearly asked to go live.
83
+ - Images: only image URLs already reachable on the public web are kept as-is;
84
+ this CLI does not re-upload local images to Zhihu's CDN.
85
+
86
+ ## Gotchas — surface before the user is surprised
87
+
88
+ - **This is the user's real Zhihu account.** Confirm before any publish; reading
89
+ exposes their own private drafts.
90
+ - **Cookie expiry**: Zhihu cookies are short-lived. A `401`/`403` means
91
+ reconnect at auth.acedata.cloud/user/connections — never loop-retry.
92
+ - **ToS**: cookie automation is against most platforms' terms. This only ever
93
+ acts on the user's own account with their own captured cookie; the user owns
94
+ that risk. Never use it to scrape other people's content at scale.
95
+ - **Never print `ZHIHU_COOKIES`** — it is full account access.
96
+ - **Scope today**: Zhihu only. 掘金 / CSDN connectors exist in the vault and are
97
+ planned next; this skill will grow a `--platform` switch for them.
@@ -0,0 +1,349 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ cn-blog — read & publish on Chinese content platforms with the user's own
4
+ login cookies (BYOC). Standard-library only (urllib), no third-party deps,
5
+ so it runs in the bare sandbox without an image change.
6
+
7
+ The connector injects the user's cookie jar as a JSON env var named
8
+ ``<PLATFORM>_COOKIES`` (e.g. ``ZHIHU_COOKIES``) — a list of
9
+ ``{name, value, domain, path, ...}`` dicts captured by the ACE extension.
10
+
11
+ Read commands run directly. ``publish`` is GATED: without a trailing
12
+ ``--confirm`` it only dry-runs (prints what it would do, changes nothing).
13
+ ``--confirm`` is honored ONLY as the last argument, so a title/content that
14
+ merely contains "--confirm" can never silently go live.
15
+
16
+ Quick examples:
17
+ python3 $SKILL_DIR/scripts/blog.py whoami
18
+ python3 $SKILL_DIR/scripts/blog.py articles --limit 20
19
+ python3 $SKILL_DIR/scripts/blog.py article <article-id>
20
+ python3 $SKILL_DIR/scripts/blog.py drafts
21
+ python3 $SKILL_DIR/scripts/blog.py publish --title "T" --content-file a.html --draft-only --confirm
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import gzip
28
+ import json
29
+ import os
30
+ import sys
31
+ import urllib.error
32
+ import urllib.parse
33
+ import urllib.request
34
+
35
+ UA = (
36
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
37
+ "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
38
+ )
39
+
40
+ # --confirm is only honored as the LAST token so a value that merely
41
+ # contains "--confirm" can never silently confirm a write.
42
+ _RAW = sys.argv[1:]
43
+ CONFIRM = bool(_RAW) and _RAW[-1] == "--confirm"
44
+ ARGV = _RAW[:-1] if CONFIRM else list(_RAW)
45
+
46
+
47
+ def out(obj) -> None:
48
+ print(json.dumps(obj, ensure_ascii=False, indent=2, default=str))
49
+
50
+
51
+ def die(msg: str, code: int = 1) -> None:
52
+ out({"error": msg})
53
+ sys.exit(code)
54
+
55
+
56
+ # ── Cookie jar (from env) ───────────────────────────────────────────
57
+
58
+ def load_cookies(platform: str) -> list[dict]:
59
+ env = f"{platform.upper()}_COOKIES"
60
+ raw = os.environ.get(env)
61
+ if not raw:
62
+ die(
63
+ f"{env} is not set — connect the {platform} account at "
64
+ f"https://auth.acedata.cloud/user/connections, then retry."
65
+ )
66
+ try:
67
+ jar = json.loads(raw)
68
+ except json.JSONDecodeError as e:
69
+ die(f"{env} is not valid JSON: {e}")
70
+ if not isinstance(jar, list):
71
+ die(f"{env} must be a JSON list of cookies, got {type(jar).__name__}")
72
+ return jar
73
+
74
+
75
+ def _domain_matches(host: str, domain: str) -> bool:
76
+ # Browser-style domain match: a cookie scoped to ".zhihu.com" / "zhihu.com"
77
+ # is sent to zhihu.com and any subdomain; a host-only cookie matches exactly.
78
+ d = domain.lstrip(".").lower()
79
+ h = host.lower()
80
+ return not d or h == d or h.endswith("." + d)
81
+
82
+
83
+ def cookie_header(jar: list[dict], url: str) -> str:
84
+ # Only send a cookie to a host inside its domain scope, so a jar is never
85
+ # replayed outside the platform it was captured for (defense in depth — all
86
+ # request URLs here are first-party, but this future-proofs multi-platform).
87
+ host = urllib.parse.urlsplit(url).hostname or ""
88
+ # A domainless cookie has no scope of its own; only send it to a host the
89
+ # jar's domain-scoped cookies already cover (i.e. this jar's own platform),
90
+ # never fail-open to an arbitrary host.
91
+ host_in_scope = any(
92
+ c.get("domain") and _domain_matches(host, str(c["domain"])) for c in jar
93
+ )
94
+ parts = []
95
+ for c in jar:
96
+ name, value = c.get("name"), c.get("value")
97
+ if not name or value is None:
98
+ continue
99
+ domain = c.get("domain")
100
+ if domain:
101
+ if not _domain_matches(host, str(domain)):
102
+ continue
103
+ elif not host_in_scope:
104
+ continue
105
+ parts.append(f"{name}={value}")
106
+ return "; ".join(parts)
107
+
108
+
109
+ # ── HTTP (stdlib urllib) ────────────────────────────────────────────
110
+
111
+ def request(method: str, url: str, jar: list[dict], *, headers=None, body=None):
112
+ hdrs = {
113
+ "User-Agent": UA,
114
+ "Accept": "application/json, text/plain, */*",
115
+ "Cookie": cookie_header(jar, url),
116
+ }
117
+ if headers:
118
+ hdrs.update(headers)
119
+ data = None
120
+ if body is not None:
121
+ data = json.dumps(body).encode("utf-8")
122
+ hdrs.setdefault("Content-Type", "application/json")
123
+ req = urllib.request.Request(url, data=data, headers=hdrs, method=method)
124
+ try:
125
+ with urllib.request.urlopen(req, timeout=30) as resp:
126
+ raw = resp.read()
127
+ if resp.headers.get("Content-Encoding") == "gzip":
128
+ raw = gzip.decompress(raw)
129
+ return resp.status, raw.decode("utf-8", "replace")
130
+ except urllib.error.HTTPError as e:
131
+ raw = e.read()
132
+ try:
133
+ if e.headers.get("Content-Encoding") == "gzip":
134
+ raw = gzip.decompress(raw)
135
+ except Exception:
136
+ pass
137
+ return e.code, raw.decode("utf-8", "replace")
138
+ except urllib.error.URLError as e:
139
+ die(f"network error reaching {url}: {e.reason}")
140
+
141
+
142
+ def get_json(url: str, jar: list[dict], **kw):
143
+ status, text = request("GET", url, jar, **kw)
144
+ if status == 401 or status == 403:
145
+ die(
146
+ f"auth failed ({status}) on {url} — the cookie is likely expired. "
147
+ f"Reconnect at https://auth.acedata.cloud/user/connections."
148
+ )
149
+ try:
150
+ return status, json.loads(text)
151
+ except json.JSONDecodeError:
152
+ die(f"non-JSON response ({status}) from {url}: {text[:300]}")
153
+
154
+
155
+ # ── Zhihu ───────────────────────────────────────────────────────────
156
+
157
+ ZH = {
158
+ "me": "https://www.zhihu.com/api/v4/me",
159
+ "articles": "https://www.zhihu.com/api/v4/members/{token}/articles",
160
+ "article": "https://www.zhihu.com/api/v4/articles/{id}",
161
+ "create_draft": "https://zhuanlan.zhihu.com/api/articles/drafts",
162
+ }
163
+ ZH_FETCH = {"x-requested-with": "fetch"}
164
+
165
+
166
+ def zh_me(jar):
167
+ _, data = get_json(ZH["me"], jar, headers=ZH_FETCH)
168
+ if not data.get("id"):
169
+ die(f"could not read Zhihu profile (cookie expired?): {str(data)[:300]}")
170
+ return data
171
+
172
+
173
+ def cmd_whoami(jar, _args):
174
+ me = zh_me(jar)
175
+ out({
176
+ "id": str(me.get("id", "")),
177
+ "name": me.get("name"),
178
+ "url_token": me.get("url_token"),
179
+ "headline": me.get("headline"),
180
+ "articles_count": me.get("articles_count"),
181
+ "voteup_count": me.get("voteup_count"),
182
+ })
183
+
184
+
185
+ # Zhihu omits stats unless asked via `include`. This pulls the counts the
186
+ # user actually cares about onto each article in the list/detail responses.
187
+ ZH_ARTICLE_INCLUDE = "data[*].comment_count,voteup_count,created,updated,title,url"
188
+
189
+
190
+ def _https(url):
191
+ if isinstance(url, str) and url.startswith("http://"):
192
+ return "https://" + url[len("http://"):]
193
+ return url
194
+
195
+
196
+ def _fmt_article(a: dict) -> dict:
197
+ aid = a.get("id")
198
+ # Prefer the canonical public reader URL built from the id — the API's own
199
+ # `url` field is inconsistent (zhuanlan in the list, api.zhihu.com in detail).
200
+ return {
201
+ "id": str(aid) if aid is not None else None,
202
+ "title": a.get("title"),
203
+ "url": (f"https://zhuanlan.zhihu.com/p/{aid}" if aid else _https(a.get("url"))),
204
+ "voteup_count": a.get("voteup_count"),
205
+ "comment_count": a.get("comment_count"),
206
+ "created": a.get("created"),
207
+ "updated": a.get("updated"),
208
+ }
209
+
210
+
211
+ def cmd_articles(jar, args):
212
+ me = zh_me(jar)
213
+ token = me.get("url_token")
214
+ if not token:
215
+ die("Zhihu profile has no url_token; cannot list articles.")
216
+ url = ZH["articles"].format(token=token)
217
+ q = urllib.parse.urlencode({
218
+ "include": ZH_ARTICLE_INCLUDE,
219
+ "limit": args.limit,
220
+ "offset": args.offset,
221
+ })
222
+ _, data = get_json(f"{url}?{q}", jar, headers=ZH_FETCH)
223
+ items = data.get("data", []) if isinstance(data, dict) else []
224
+ out({
225
+ "total": (data.get("paging") or {}).get("totals") if isinstance(data, dict) else None,
226
+ "count": len(items),
227
+ "articles": [_fmt_article(a) for a in items],
228
+ })
229
+
230
+
231
+ def cmd_article(jar, args):
232
+ base = ZH["article"].format(id=args.id)
233
+ q = urllib.parse.urlencode({"include": "comment_count,voteup_count"})
234
+ _, a = get_json(f"{base}?{q}", jar, headers=ZH_FETCH)
235
+ if not isinstance(a, dict) or not a.get("id"):
236
+ die(f"article {args.id} not found or not accessible: {str(a)[:300]}")
237
+ res = _fmt_article(a)
238
+ res["content_excerpt"] = (a.get("excerpt") or "")[:200]
239
+ out(res)
240
+
241
+
242
+ def cmd_publish(jar, args):
243
+ if not args.title:
244
+ die("--title is required")
245
+ if not args.content_file and args.content is None:
246
+ die("provide --content-file <path> or --content <html>")
247
+ content = args.content
248
+ if args.content_file:
249
+ try:
250
+ with open(args.content_file, encoding="utf-8") as f:
251
+ content = f.read()
252
+ except OSError as e:
253
+ die(f"cannot read --content-file: {e}")
254
+
255
+ if not CONFIRM:
256
+ out({
257
+ "dry_run": True,
258
+ "command": "publish",
259
+ "platform": "zhihu",
260
+ "title": args.title,
261
+ "draft_only": args.draft_only,
262
+ "content_bytes": len(content or ""),
263
+ "note": "re-run with --confirm as the LAST argument to actually write. "
264
+ "Without --draft-only this publishes a PUBLIC article on the user's real account.",
265
+ })
266
+ return
267
+
268
+ # 1. create empty draft
269
+ status, text = request(
270
+ "POST", ZH["create_draft"], jar, headers=ZH_FETCH,
271
+ body={"title": args.title, "content": "", "delta_time": 0},
272
+ )
273
+ try:
274
+ created = json.loads(text)
275
+ except json.JSONDecodeError:
276
+ die(f"create-draft returned non-JSON ({status}): {text[:300]}")
277
+ draft_id = created.get("id")
278
+ if not draft_id:
279
+ die(f"create-draft failed ({status}): {str(created)[:300]}")
280
+
281
+ # 2. set draft content
282
+ status, text = request(
283
+ "PATCH", f"https://zhuanlan.zhihu.com/api/articles/{draft_id}/draft", jar,
284
+ headers=ZH_FETCH, body={"title": args.title, "content": content},
285
+ )
286
+ if status >= 400:
287
+ die(f"update-draft failed ({status}) for {draft_id}: {text[:300]}")
288
+
289
+ if args.draft_only:
290
+ out({
291
+ "ok": True,
292
+ "draft_only": True,
293
+ "draft_id": str(draft_id),
294
+ "edit_url": f"https://zhuanlan.zhihu.com/write?draftId={draft_id}",
295
+ })
296
+ return
297
+
298
+ # 3. publish (go live)
299
+ status, text = request(
300
+ "PUT", f"https://zhuanlan.zhihu.com/api/articles/{draft_id}/publish", jar,
301
+ headers=ZH_FETCH, body={},
302
+ )
303
+ if status >= 400:
304
+ die(f"publish failed ({status}) for {draft_id}; it remains a draft: {text[:300]}")
305
+ out({
306
+ "ok": True,
307
+ "published": True,
308
+ "article_id": str(draft_id),
309
+ "url": f"https://zhuanlan.zhihu.com/p/{draft_id}",
310
+ })
311
+
312
+
313
+ COMMANDS = {
314
+ "whoami": cmd_whoami,
315
+ "articles": cmd_articles,
316
+ "article": cmd_article,
317
+ "publish": cmd_publish,
318
+ }
319
+
320
+
321
+ def main() -> None:
322
+ p = argparse.ArgumentParser(prog="blog.py", description="cn-blog cookie CLI")
323
+ p.add_argument("--platform", default="zhihu", choices=["zhihu"],
324
+ help="content platform (only zhihu is implemented today)")
325
+ sub = p.add_subparsers(dest="command", required=True)
326
+
327
+ sub.add_parser("whoami", help="show the logged-in account")
328
+
329
+ sp = sub.add_parser("articles", help="list the user's published articles + stats")
330
+ sp.add_argument("--limit", type=int, default=20)
331
+ sp.add_argument("--offset", type=int, default=0)
332
+
333
+ sp = sub.add_parser("article", help="one article's details + stats")
334
+ sp.add_argument("id")
335
+
336
+ sp = sub.add_parser("publish", help="create/publish an article (GATED by trailing --confirm)")
337
+ sp.add_argument("--title")
338
+ sp.add_argument("--content", help="HTML content inline")
339
+ sp.add_argument("--content-file", help="path to an HTML file")
340
+ sp.add_argument("--draft-only", action="store_true",
341
+ help="create a draft only; do NOT go public")
342
+
343
+ args = p.parse_args(ARGV)
344
+ jar = load_cookies(args.platform)
345
+ COMMANDS[args.command](jar, args)
346
+
347
+
348
+ if __name__ == "__main__":
349
+ main()
@@ -1,118 +1,242 @@
1
1
  ---
2
2
  name: telegram
3
- description: Read, search and send personal Telegram messages list recent chats / contacts / groups, pull a conversation's history, search messages, and send a message driven by the Telethon MTProto client with the user's own account. Use when the user mentions Telegram, a Telegram chat/group/contact, "我的 Telegram", reading or replying to Telegram messages, or summarizing Telegram conversations.
3
+ description: Full personal Telegram control over MTProto (Telethon) with the user's own account list/search chats, read & summarize history, see unread, look up contacts & chat info, download media, and send / reply / forward / edit / delete / react / send files / mark read. Use when the user mentions Telegram, a Telegram chat/group/contact, "我的 Telegram", reading/replying/forwarding/summarizing Telegram messages, their unread Telegram, or sending a file/message on Telegram.
4
4
  when_to_use: |
5
- Trigger when the user wants to do anything with their personal Telegram
6
- account: list recent conversations, read / summarize the history of a chat
7
- or group, search their messages for a keyword, look up a contact, or send /
8
- reply to a message. This drives the user's OWN account over MTProto (not a
9
- bot), so it can see everything the user can see.
5
+ Trigger for anything on the user's personal Telegram account: list recent
6
+ conversations or just the unread ones, read / summarize a chat or group,
7
+ search one chat or across all chats, look up a contact or a chat's info,
8
+ download a photo/file from a message, or take an action send, reply,
9
+ forward, edit, delete, react, send a file, or mark a chat read. This drives
10
+ the user's OWN account over MTProto (not a bot), so it sees everything they see.
10
11
  connections: [telegram]
11
12
  allowed_tools: [Bash]
12
13
  license: Apache-2.0
13
14
  metadata:
14
15
  author: acedatacloud
15
- version: "1.0"
16
+ version: "1.1"
16
17
  ---
17
18
 
18
- We drive **personal** Telegram over the MTProto protocol with the
19
- [Telethon](https://docs.telethon.dev/) Python library — this acts as the user's own
20
- account (a "userbot"), so unlike the Bot API it can read full chat history, list every
21
- conversation, and message anyone the user can message.
19
+ We drive **personal** Telegram over MTProto with [Telethon](https://docs.telethon.dev/) —
20
+ this acts as the user's own account (a "userbot"), so unlike the Bot API it can read full
21
+ history, list every conversation, and act on anyone the user can reach.
22
22
 
23
- The user's credentials are injected as environment variables by the connector:
23
+ Credentials are injected as env vars by the connector:
24
24
 
25
- - `TELEGRAM_API_ID` — the app id (from my.telegram.org)
26
- - `TELEGRAM_API_HASH` — the app hash — **secret, never echo it**
27
- - `TELEGRAM_SESSION_STRING` — a Telethon `StringSession` = **full account access. Never log,
25
+ - `TELEGRAM_API_ID` — app id
26
+ - `TELEGRAM_API_HASH` — app hash — **secret, never echo**
27
+ - `TELEGRAM_SESSION_STRING` — Telethon `StringSession` = **full account access. Never log,
28
28
  echo, or print it.** Treat it like the account password.
29
29
 
30
30
  ## Setup — write the helper once per session
31
31
 
32
- `telethon` is preinstalled in the sandbox image. The helper is written to `./tg.py` **in the
33
- current working directory** (the per-session workdir) — not a shared global path like `/tmp`
34
- so concurrent sessions never race on or reuse each other's file.
32
+ `telethon` is preinstalled in the sandbox. The helper is written to `./tg.py` **in the current
33
+ working directory** (the per-session workdir) — not a shared global path so concurrent
34
+ sessions never race.
35
+
36
+ Every state-changing command (`send`, `reply`, `send-file`, `forward`, `edit`, `delete`,
37
+ `react`, `mark-read`) is **gated**: without a trailing `--confirm` it only DRY-RUNS (prints what
38
+ it would do, changes nothing). Read commands run directly. `--confirm` is honored **only as the
39
+ last argument** so a message/caption that merely contains "--confirm" can never silently confirm.
35
40
 
36
41
  ```sh
37
- # telethon is preinstalled; the `|| pip install` is a best-effort fallback only
38
- # (the sandbox is non-root, so a runtime install may not succeed — rely on the
39
- # preinstalled package).
40
42
  python3 -c "import telethon" 2>/dev/null || pip install --user --quiet telethon 2>/dev/null || true
41
43
 
42
44
  cat > ./tg.py <<'PY'
43
45
  import os, sys, json, asyncio
44
46
  from telethon import TelegramClient
45
47
  from telethon.sessions import StringSession
48
+ from telethon.tl import functions
49
+ from telethon.tl.types import ReactionEmoji
46
50
 
47
51
  API_ID = int(os.environ["TELEGRAM_API_ID"])
48
52
  API_HASH = os.environ["TELEGRAM_API_HASH"]
49
53
  SESSION = os.environ["TELEGRAM_SESSION_STRING"]
50
54
 
55
+ _raw = sys.argv[1:]
56
+ # --confirm is only honored as the LAST token, and only one is stripped, so a
57
+ # message/caption that merely contains "--confirm" cannot silently confirm a write.
58
+ CONFIRM = bool(_raw) and _raw[-1] == "--confirm"
59
+ a = _raw[:-1] if CONFIRM else list(_raw)
60
+ cmd = a[0] if a else "help"
61
+ args = a[1:]
62
+ GATED = {"send", "reply", "send-file", "forward", "edit", "delete", "react", "mark-read"}
63
+
64
+
65
+ def out(o):
66
+ print(json.dumps(o, ensure_ascii=False, default=str))
67
+
51
68
 
52
69
  async def resolve(client, target):
53
- # Accept a numeric id, @username, phone, or an exact chat display name.
70
+ # 1) try direct resolve; 2) fall back to scanning dialogs by id or exact name
71
+ # (StringSession doesn't persist the entity cache, so a numeric id from a
72
+ # previous invocation may need the dialog scan to recover its access hash).
73
+ for attempt in (lambda: client.get_entity(int(target)), lambda: client.get_entity(target)):
74
+ try:
75
+ return await attempt()
76
+ except Exception:
77
+ pass
78
+ ti = None
54
79
  try:
55
- return await client.get_entity(int(target))
80
+ ti = int(target)
56
81
  except (ValueError, TypeError):
57
82
  pass
58
- try:
59
- return await client.get_entity(target)
60
- except Exception:
61
- async for d in client.iter_dialogs():
62
- if d.name == target:
63
- return d.entity
64
- raise ValueError(f"could not resolve target: {target}")
83
+ async for d in client.iter_dialogs():
84
+ if (ti is not None and d.id == ti) or d.name == target:
85
+ return d.entity
86
+ raise ValueError(f"could not resolve target: {target}")
65
87
 
66
88
 
67
- async def main():
68
- cmd = sys.argv[1]
69
- async with TelegramClient(StringSession(SESSION), API_ID, API_HASH) as client:
89
+ def msg_row(m):
90
+ return {"id": m.id, "date": str(m.date), "out": m.out, "sender_id": m.sender_id,
91
+ "text": m.message, "media": bool(m.media)}
92
+
93
+
94
+ def need(n):
95
+ if len(args) < n:
96
+ raise ValueError(f"{cmd} needs {n} argument(s), got {len(args)}")
97
+
98
+
99
+ async def run():
100
+ if cmd in GATED and not CONFIRM:
101
+ out({"dry_run": True, "command": cmd, "args": args,
102
+ "note": "re-run with --confirm as the LAST argument to actually perform this write"})
103
+ return
104
+ async with TelegramClient(StringSession(SESSION), API_ID, API_HASH) as cl:
70
105
  if cmd == "whoami":
71
- me = await client.get_me()
72
- print(json.dumps({"id": me.id, "username": me.username,
73
- "name": ((me.first_name or "") + " " + (me.last_name or "")).strip()},
74
- ensure_ascii=False))
106
+ me = await cl.get_me()
107
+ out({"id": me.id, "username": me.username,
108
+ "name": ((me.first_name or "") + " " + (me.last_name or "")).strip(), "phone": me.phone})
109
+
75
110
  elif cmd == "list-chats":
76
- limit = int(sys.argv[2]) if len(sys.argv) > 2 else 20
77
- out = []
78
- async for d in client.iter_dialogs(limit=limit):
79
- out.append({"name": d.name, "id": d.id, "group": d.is_group,
111
+ limit = int(args[0]) if args and args[0].lstrip("-").isdigit() else 20
112
+ unread_only = "unread-only" in args
113
+ res = []
114
+ async for d in cl.iter_dialogs(limit=limit):
115
+ if unread_only and not d.unread_count:
116
+ continue
117
+ res.append({"name": d.name, "id": d.id, "group": d.is_group,
80
118
  "channel": d.is_channel, "user": d.is_user, "unread": d.unread_count})
81
- print(json.dumps(out, ensure_ascii=False))
119
+ out(res)
120
+
121
+ elif cmd == "unread":
122
+ res = []
123
+ async for d in cl.iter_dialogs():
124
+ if d.unread_count:
125
+ res.append({"name": d.name, "id": d.id, "unread": d.unread_count,
126
+ "group": d.is_group, "channel": d.is_channel})
127
+ out(sorted(res, key=lambda x: -x["unread"]))
128
+
82
129
  elif cmd == "get-messages":
83
- target = sys.argv[2]
84
- n = int(sys.argv[3]) if len(sys.argv) > 3 else 50
85
- ent = await resolve(client, target)
86
- out = []
87
- async for m in client.iter_messages(ent, limit=n):
88
- out.append({"id": m.id, "date": str(m.date), "out": m.out,
89
- "sender_id": m.sender_id, "text": m.message})
90
- out.reverse()
91
- print(json.dumps(out, ensure_ascii=False))
130
+ need(1); ent = await resolve(cl, args[0])
131
+ n = int(args[1]) if len(args) > 1 else 50
132
+ rows = [msg_row(m) async for m in cl.iter_messages(ent, limit=n)]
133
+ rows.reverse()
134
+ out(rows)
135
+
92
136
  elif cmd == "search":
93
- target, query = sys.argv[2], sys.argv[3]
94
- n = int(sys.argv[4]) if len(sys.argv) > 4 else 30
95
- ent = await resolve(client, target)
96
- out = []
97
- async for m in client.iter_messages(ent, search=query, limit=n):
98
- out.append({"id": m.id, "date": str(m.date), "sender_id": m.sender_id, "text": m.message})
99
- print(json.dumps(out, ensure_ascii=False))
137
+ need(2); ent = await resolve(cl, args[0])
138
+ q = args[1]; n = int(args[2]) if len(args) > 2 else 30
139
+ out([msg_row(m) async for m in cl.iter_messages(ent, search=q, limit=n)])
140
+
141
+ elif cmd == "search-global":
142
+ need(1); q = args[0]; n = int(args[1]) if len(args) > 1 else 30
143
+ rows = []
144
+ async for m in cl.iter_messages(None, search=q, limit=n):
145
+ r = msg_row(m); r["chat_id"] = m.chat_id
146
+ rows.append(r)
147
+ out(rows)
148
+
149
+ elif cmd == "contacts":
150
+ res = await cl(functions.contacts.GetContactsRequest(hash=0))
151
+ out([{"id": u.id, "username": u.username,
152
+ "name": ((u.first_name or "") + " " + (u.last_name or "")).strip(), "phone": u.phone}
153
+ for u in res.users])
154
+
155
+ elif cmd == "chat-info":
156
+ need(1); ent = await resolve(cl, args[0])
157
+ info = {"id": ent.id, "type": type(ent).__name__,
158
+ "title": getattr(ent, "title", None),
159
+ "name": ((getattr(ent, "first_name", "") or "") + " " + (getattr(ent, "last_name", "") or "")).strip() or None,
160
+ "username": getattr(ent, "username", None)}
161
+ try:
162
+ info["participants"] = (await cl.get_participants(ent, limit=1)).total
163
+ except Exception:
164
+ pass
165
+ out(info)
166
+
167
+ elif cmd == "message-link":
168
+ need(2); ent = await resolve(cl, args[0]); mid = int(args[1])
169
+ try:
170
+ r = await cl(functions.channels.ExportMessageLinkRequest(channel=ent, id=mid))
171
+ out({"link": r.link})
172
+ except Exception as e:
173
+ out({"error": f"links only available for channels/supergroups: {e}"})
174
+
175
+ elif cmd == "download-media":
176
+ need(2); ent = await resolve(cl, args[0]); mid = int(args[1])
177
+ outdir = args[2] if len(args) > 2 else "./tg_downloads"
178
+ os.makedirs(outdir, exist_ok=True)
179
+ m = await cl.get_messages(ent, ids=mid)
180
+ if not m or not m.media:
181
+ out({"error": "no media on that message"}); return
182
+ path = await cl.download_media(m, file=outdir)
183
+ out({"downloaded": path})
184
+
185
+ # ---- gated writes (need trailing --confirm) ----
100
186
  elif cmd == "send":
101
- # Gated: without --confirm this only DRY-RUNS (prints the intended
102
- # target + text and sends nothing). Pass --confirm to actually send.
103
- target, text = sys.argv[2], sys.argv[3]
104
- confirm = "--confirm" in sys.argv[4:]
105
- ent = await resolve(client, target)
106
- if not confirm:
107
- name = getattr(ent, "title", None) or getattr(ent, "first_name", None) or str(target)
108
- print(json.dumps({"dry_run": True, "would_send_to": name, "text": text,
109
- "note": "re-run with --confirm to actually send"}, ensure_ascii=False))
110
- return
111
- msg = await client.send_message(ent, text)
112
- print(json.dumps({"sent": True, "id": msg.id}, ensure_ascii=False))
187
+ need(2); ent = await resolve(cl, args[0])
188
+ m = await cl.send_message(ent, args[1])
189
+ out({"sent": True, "id": m.id})
190
+
191
+ elif cmd == "reply":
192
+ need(3); ent = await resolve(cl, args[0])
193
+ m = await cl.send_message(ent, args[2], reply_to=int(args[1]))
194
+ out({"sent": True, "id": m.id, "reply_to": int(args[1])})
195
+
196
+ elif cmd == "send-file":
197
+ need(2); ent = await resolve(cl, args[0])
198
+ caption = args[2] if len(args) > 2 else None
199
+ m = await cl.send_file(ent, args[1], caption=caption)
200
+ out({"sent": True, "id": m.id})
201
+
202
+ elif cmd == "forward":
203
+ need(3); src = await resolve(cl, args[0]); mid = int(args[1]); dst = await resolve(cl, args[2])
204
+ fwd = await cl.forward_messages(dst, mid, src)
205
+ out({"forwarded": True, "id": getattr(fwd, "id", None) or [x.id for x in fwd]})
206
+
207
+ elif cmd == "edit":
208
+ need(3); ent = await resolve(cl, args[0])
209
+ m = await cl.edit_message(ent, int(args[1]), args[2])
210
+ out({"edited": True, "id": m.id})
211
+
212
+ elif cmd == "delete":
213
+ need(2); ent = await resolve(cl, args[0])
214
+ await cl.delete_messages(ent, int(args[1]))
215
+ out({"deleted": True, "id": int(args[1])})
216
+
217
+ elif cmd == "react":
218
+ need(3); ent = await resolve(cl, args[0]); mid = int(args[1]); emoji = args[2]
219
+ await cl(functions.messages.SendReactionRequest(
220
+ peer=ent, msg_id=mid, reaction=[ReactionEmoji(emoticon=emoji)]))
221
+ out({"reacted": True, "id": mid, "emoji": emoji})
222
+
223
+ elif cmd == "mark-read":
224
+ need(1); ent = await resolve(cl, args[0])
225
+ await cl.send_read_acknowledge(ent)
226
+ out({"marked_read": True})
227
+
113
228
  else:
114
- print(json.dumps({"error": f"unknown command: {cmd}"}))
115
- sys.exit(1)
229
+ out({"error": f"unknown command: {cmd}"}); sys.exit(1)
230
+
231
+
232
+ async def main():
233
+ try:
234
+ await run()
235
+ except SystemExit:
236
+ raise
237
+ except Exception as e:
238
+ out({"error": f"{type(e).__name__}: {e}"})
239
+ sys.exit(1)
116
240
 
117
241
 
118
242
  asyncio.run(main())
@@ -120,76 +244,77 @@ PY
120
244
  echo "helper ready"
121
245
  ```
122
246
 
123
- ## Verify the connection (run this first)
247
+ ## Verify the connection first
124
248
 
125
249
  ```sh
126
250
  python3 ./tg.py whoami
127
- # → {"id": 8367450178, "username": "GermeyAce", "name": "Germey"}
251
+ # → {"id": 8367450178, "username": "GermeyAce", "name": "Germey", "phone": "..."}
128
252
  ```
129
253
 
130
- If this errors with an auth/session message, the stored session is dead (revoked or expired)
131
- tell the user to reconnect the Telegram connector at https://auth.acedata.cloud/user/connections.
254
+ On an auth/session error the stored session is dead tell the user to reconnect at
255
+ https://auth.acedata.cloud/user/connections.
132
256
 
133
- ## Recipes
257
+ ## Read recipes
134
258
 
135
- ### List recent conversations
259
+ | Goal | Command |
260
+ |---|---|
261
+ | Recent conversations | `python3 ./tg.py list-chats 20` |
262
+ | Only chats with unread (ranked) | `python3 ./tg.py unread` |
263
+ | A chat's history (oldest→newest) | `python3 ./tg.py get-messages <target> 50` |
264
+ | Search inside one chat | `python3 ./tg.py search <target> "kw" 30` |
265
+ | Search across ALL chats | `python3 ./tg.py search-global "kw" 30` |
266
+ | List contacts | `python3 ./tg.py contacts` |
267
+ | Info about a chat/user | `python3 ./tg.py chat-info <target>` |
268
+ | t.me link to a message | `python3 ./tg.py message-link <target> <msg_id>` |
136
269
 
137
- ```sh
138
- python3 ./tg.py list-chats 20
139
- # → [{"name":"Ace <> ConduitOS","id":-5287630726,"group":true,...,"unread":0}, ...]
140
- ```
270
+ `<target>` = numeric id (most reliable — from `list-chats`), `@username`, phone, or exact chat
271
+ name. In message rows, `out:true` = sent by the user; `media:true` = has an attachment.
141
272
 
142
- Use the returned `id` (or the exact `name`) as the target for the next calls.
273
+ **Summarize-unread pattern**: `unread` pick the chats that matter `get-messages <id> N` on
274
+ each → summarize. Don't dump 20k messages; sample the most-unread / most-relevant.
143
275
 
144
- ### Read a conversation's history (oldest→newest)
276
+ ## Media
145
277
 
146
278
  ```sh
147
- # target = numeric id, @username, phone, or exact chat name; second arg = how many messages
148
- python3 ./tg.py get-messages -5287630726 50
149
- python3 ./tg.py get-messages @some_username 30
279
+ # Download an attachment from a message returns the saved path
280
+ python3 ./tg.py download-media <target> <msg_id> ./tg_downloads
281
+ # Send a local file or a URL (optional caption) — GATED
282
+ python3 ./tg.py send-file <target> /path/or/https-url "caption" --confirm
150
283
  ```
151
284
 
152
- `out: true` means the message was sent BY the user; `sender_id` is the author. Summarize from
153
- the returned JSON.
285
+ To hand a downloaded file back to the user as a link, upload it to the CDN (see the
286
+ `cos-upload` skill) after `download-media`.
154
287
 
155
- ### Search inside a conversation
288
+ ## Write recipes all GATED (dry-run unless trailing `--confirm`)
156
289
 
157
- ```sh
158
- python3 ./tg.py search -5287630726 "keyword" 30
159
- ```
160
-
161
- (Server-side search is scoped to one chat. To search broadly, list chats first, then search the
162
- relevant ones.)
163
-
164
- ### Send / reply to a message — TWO-STEP, confirm first
165
-
166
- Sending posts a **real message as the user**, so it is gated:
290
+ Sending/editing/deleting acts as the **real user**. Always run the dry run first, show the user
291
+ exactly what will happen, get an explicit "yes", then re-run with `--confirm` as the **last
292
+ argument**. Never bulk-send.
167
293
 
168
294
  ```sh
169
- # Step 1 DRY RUN (default, sends nothing). Show this preview to the user.
170
- python3 ./tg.py send -5287630726 "Hi, following up on this."
171
- # {"dry_run": true, "would_send_to": "Ace <> ConduitOS", "text": "Hi, following up on this.", ...}
172
-
173
- # Step 2 only after the user explicitly says yes in the conversation, add --confirm:
174
- python3 ./tg.py send -5287630726 "Hi, following up on this." --confirm
175
- # {"sent": true, "id": 4502}
295
+ python3 ./tg.py send <target> "text" # dry_run; add --confirm to send
296
+ python3 ./tg.py reply <target> <msg_id> "text" --confirm
297
+ python3 ./tg.py forward <from_target> <msg_id> <to_target> --confirm
298
+ python3 ./tg.py edit <target> <msg_id> "new text" --confirm # own messages
299
+ python3 ./tg.py delete <target> <msg_id> --confirm # destructive
300
+ python3 ./tg.py react <target> <msg_id> "👍" --confirm
301
+ python3 ./tg.py mark-read <target> --confirm # sends read receipts
176
302
  ```
177
303
 
178
- **Always run the dry run first, show the user exactly who + what, and require an explicit "yes"
179
- before re-running with `--confirm`** — even if the original instruction said "just send it".
180
- Never bulk-send.
181
-
182
- ## Gotchas — surface these before the user is surprised
183
-
184
- - **This is the user's real account.** Sending posts as them; reading exposes all their private
185
- chats. Be conservative.
186
- - **`FloodWaitError`**: Telegram rate-limits userbots. If a call fails with a flood-wait of N
187
- seconds, tell the user to retry after N seconds — do not loop/retry aggressively (it escalates
188
- toward an account ban).
189
- - **Dead session**: a `session_string` can be revoked by the user from Telegram Settings
190
- Devices. On an `AuthKeyError` / unauthorized error, the fix is reconnecting the connector, not
191
- retrying.
192
- - **Never print `TELEGRAM_SESSION_STRING` or `TELEGRAM_API_HASH`** — they are full-account
193
- secrets. The helper never prints them; keep it that way.
194
- - **Resolving targets**: prefer the numeric `id` from `list-chats` (most reliable). Names work
195
- only on an exact match; usernames need the leading `@`.
304
+ The dry run returns `{"dry_run": true, "command": ..., "args": [...]}` present that to the
305
+ user verbatim as the confirmation prompt.
306
+
307
+ ## Gotchas — surface before the user is surprised
308
+
309
+ - **This is the user's real account.** Confirm before any write; reading exposes private chats.
310
+ - **`FloodWaitError`**: Telegram rate-limits userbots. On a flood-wait of N seconds, tell the
311
+ user to retry after N — never loop/retry aggressively (escalates toward a ban).
312
+ - **Dead session**: revoked from Telegram Settings Devices, or ~6-month inactivity. On
313
+ `AuthKeyError`/unauthorized, reconnect the connector (don't retry).
314
+ - **Never print `TELEGRAM_SESSION_STRING` / `TELEGRAM_API_HASH`** — full-account secrets.
315
+ - **Targets**: prefer the numeric `id` from `list-chats` (the helper recovers its access hash by
316
+ scanning dialogs); names need an exact match, usernames need a leading `@`.
317
+ - **`message-link`** only works for public channels/supergroups; private 1:1 / basic groups
318
+ return an error (no shareable link exists).
319
+ - **`edit`/`delete`** generally only apply to the user's own messages (admins can delete others
320
+ in groups they manage).