dsh-plugin-chuhai 0.3.5 → 0.3.7

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/books/ai-global-media/BOOK.md +131 -131
  3. package/books/ai-global-media/expert/SOURCE.json +43 -41
  4. package/books/ai-global-media/expert/agents/ilang-wechat-awesome.md +267 -267
  5. package/books/ai-global-media/expert/skills/remote-dispatch/SKILL.md +101 -101
  6. package/books/ai-global-media/expert/skills/remote-dispatch/references/gateway-api.md +58 -58
  7. package/books/ai-global-media/expert/skills/remote-dispatch/scripts/dispatch.py +299 -299
  8. package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.ps1 +74 -74
  9. package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.sh +94 -94
  10. package/books/ai-global-media/expert/skills/wechat-article/SKILL.md +80 -80
  11. package/books/ai-global-media/expert/skills/wechat-article/references/algorithm-and-rhythm.md +54 -54
  12. package/books/ai-global-media/expert/skills/wechat-article/references/compliance.md +68 -68
  13. package/books/ai-global-media/expert/skills/wechat-article/references/cover-prompt.md +19 -19
  14. package/books/ai-global-media/expert/skills/wechat-article/references/deai.md +64 -64
  15. package/books/ai-global-media/expert/skills/wechat-article/references/genes.md +168 -168
  16. package/books/ai-global-media/expert/skills/wechat-article/references/other-platforms.md +47 -47
  17. package/books/ai-global-media/expert/skills/wechat-article/references/self-check.md +32 -32
  18. package/books/ai-global-media/expert/skills/wechat-article/references/structures-and-titles.md +77 -77
  19. package/books/ai-global-media/expert/skills/wechat-article/references/wechat-format-and-api.md +61 -61
  20. package/books/ai-global-media/expert/skills/wechat-draft-push/SKILL.md +129 -129
  21. package/books/ai-global-media/expert/skills/wechat-draft-push/references/api-notes.md +168 -168
  22. package/books/ai-global-media/expert/skills/wechat-draft-push/references/html-rules.md +62 -62
  23. package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/cards.html +75 -75
  24. package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/newspic_cards.py +345 -345
  25. package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/wechat_draft.py +1023 -1023
  26. package/books/ai-global-media/expert/skills/wechat-topic-hunter/SKILL.md +125 -92
  27. package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/apify-wechat.md +90 -0
  28. package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/method.md +49 -49
  29. package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/wxrank-api.md +51 -51
  30. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/apify_wechat.py +578 -0
  31. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/hot_sources.py +553 -553
  32. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/sources.json +716 -714
  33. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/wxrank_topics.py +466 -466
  34. package/books/baowen/BOOK.md +83 -83
  35. package/package.json +1 -1
@@ -0,0 +1,578 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """公众号数据的另一条路:Apify 上的采集器 zen-studio/wechat-official-account-scraper。用你自己的 Apify 令牌,花的是你自己 Apify 账号里的额度。
4
+
5
+ 用法:
6
+ python apify_wechat.py me 账号套餐、本期已用、月上限(免费)
7
+ python apify_wechat.py viral [--date 2026-11-25] [--window 3d|7d|30d] [--pages 1] [--category 科技,财经] [--keyword 出海,AI] [--min-boost 0] [--n 30]
8
+ 低粉爆文日榜:小号里阅读远超平时的文章,每条带这个号平时的阅读和倍率
9
+ python apify_wechat.py search --keyword 出海,副业 [--pages 1] [--sort relevance|latest|hot] [--time all|day|week|halfYear]
10
+ 按词搜公众号文章
11
+ python apify_wechat.py metrics --url "<文章链接>[,<文章链接>]" 阅读 点赞 在看 分享 收藏 评论数
12
+ python apify_wechat.py accounts --keyword AI出海 [--pages 1] [--all] 按词找公众号:名称、微信号、原始ID、主体、原创篇数(--all 连视频号小程序一起列)
13
+ python apify_wechat.py history --account <gh_ 原始ID|微信号|号名|这个号任意一篇文章链接> [--pages 1]
14
+ 一个号的历史发文,带头条阅读中位和每篇的倍率
15
+ python apify_wechat.py detail --url "<文章链接>" 正文、作者、是否原创、发文地区
16
+ python apify_wechat.py comments --url "<文章链接>" [--pages 1] 精选留言
17
+ python apify_wechat.py index --keyword 出海,AI 微信指数,近 30 天每天的热度
18
+ python apify_wechat.py suggest --keyword 副业,出海 联想词:微信搜一搜里别人接着这个词在搜什么
19
+ python apify_wechat.py run --op <操作名> [--keyword a,b] [--url u1,u2] [--account x,y] [--link 短链或长链] [--pages N] [--json '{"字段":"值"}']
20
+ 采集器其余操作原样跑,结果存文件。16 个操作名见 references/apify-wechat.md
21
+ 付费命令都可以加:--max-usd 1.0(这次运行最多花多少美元,到了采集器自己停,默认 1)、--save 结果.json(原始结果落盘)。
22
+
23
+ 凭据:~/.apify.env 一行 TOKEN=你的令牌(或环境变量 APIFY_TOKEN)。没有 Apify 账号先注册:https://www.apify.com?fpr=tqio9f
24
+ (这是我们的推广链接;免费套餐每月有 5 美元额度)。令牌在 https://console.apify.com/settings/integrations 的 Personal API tokens 里建。
25
+ 纪律:只读;令牌走请求头、不进输出;按条计费的单价和这次的封顶先打印再跑;只用标准库;不填采集器输入里的 feedback 字段。
26
+ 口径:数字是采集器当场从微信拿的公开数,跟公众号后台会差。爆文榜的倍率 = 这篇阅读 ÷ 这个号近 90 天的阅读基线,是采集器算好的;
27
+ history 的倍率 = 这篇阅读 ÷ 这个号这批头条的阅读中位,是本脚本按微信列表里给的阅读算的。只标注数字,选题是你定。
28
+ """
29
+ import argparse, datetime, io, json, os, re, statistics, sys, time, urllib.error, urllib.parse, urllib.request
30
+
31
+ try:
32
+ sys.stdout.reconfigure(encoding="utf-8"); sys.stderr.reconfigure(encoding="utf-8")
33
+ except Exception:
34
+ pass
35
+
36
+ API = "https://api.apify.com/v2"
37
+ ACTOR = "zen-studio~wechat-official-account-scraper"
38
+ SIGNUP = "https://www.apify.com?fpr=tqio9f"
39
+ TOKENS_PAGE = "https://console.apify.com/settings/integrations"
40
+ BILLING_PAGE = "https://console.apify.com/billing"
41
+ ENV = os.path.join(os.path.expanduser("~"), ".apify.env")
42
+ OPS = ["articleSearch", "accountSearch", "miniProgramSearch", "searchSuggestions", "wechatIndexSearch", "articleDetail", "articleMetrics",
43
+ "articleComments", "articleCommentReplies", "convertArticleLink", "accountBasicInfo", "accountPrincipalInfo", "accountOriginalCount",
44
+ "accountTodayArticles", "accountHistoryArticles", "viralArticles"]
45
+ # 采集器页面 2026-11-25 的按条单价(美元,免费档;付费档略低,Starter 档低粉爆文 0.011、找号 0.007、联想词与指数 0.28,档位越高越低)。只用来在跑之前报个数,实际以 Apify 账单为准。
46
+ START_FEE = 0.05
47
+ UNIT_PRICE = {"viralArticles": 0.012, "articleSearch": 0.006, "accountHistoryArticles": 0.006, "articleMetrics": 0.03, "articleDetail": 0.03,
48
+ "articleComments": 0.003, "articleCommentReplies": 0.025, "wechatIndexSearch": 0.30, "searchSuggestions": 0.30,
49
+ "accountSearch": 0.008, "miniProgramSearch": 0.015, "convertArticleLink": 0.025, "accountBasicInfo": 0.03,
50
+ "accountPrincipalInfo": 0.03, "accountOriginalCount": 0.03, "accountTodayArticles": 0.006}
51
+ DONE = ("SUCCEEDED", "FAILED", "TIMED-OUT", "ABORTED")
52
+
53
+
54
+ def die(msg, code=1):
55
+ print("错误:" + msg); sys.exit(code)
56
+
57
+
58
+ def decode_env(raw):
59
+ """.apify.env 多半是用户在 Windows 上用记事本或 PowerShell 写的:可能带 BOM,也可能是 UTF-16。都要读得出。"""
60
+ if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
61
+ return raw.decode("utf-16", "replace")
62
+ return raw.decode("utf-8-sig", "replace")
63
+
64
+
65
+ def parse_env(text):
66
+ """从 .apify.env 的内容里取令牌:认 TOKEN / APIFY_TOKEN / APIFY_API_TOKEN 三种写法。"""
67
+ for line in text.replace("\ufeff", "").replace("\x00", "").splitlines():
68
+ line = line.strip()
69
+ if "=" in line and not line.startswith("#"):
70
+ k, v = line.split("=", 1)
71
+ if k.strip().upper() in ("TOKEN", "APIFY_TOKEN", "APIFY_API_TOKEN"):
72
+ return v.strip().strip('"').strip("'")
73
+ return ""
74
+
75
+
76
+ def load_token():
77
+ t = (os.environ.get("APIFY_TOKEN") or os.environ.get("APIFY_API_TOKEN") or "").strip()
78
+ if not t and os.path.exists(ENV):
79
+ t = parse_env(decode_env(io.open(ENV, "rb").read()))
80
+ if not t:
81
+ die("没找到 Apify 令牌。\n 1 没账号先注册:%s (我们的推广链接;免费套餐每月有 5 美元额度)\n 2 在 %s 的 Personal API tokens 里建一个令牌\n 3 写进 %s 一行 TOKEN=你的令牌(自己写,别贴进对话)" % (SIGNUP, TOKENS_PAGE, ENV))
82
+ if not re.match(r"^[A-Za-z0-9_\-]{20,200}$", t):
83
+ die("令牌格式不对:只能是字母数字下划线减号。检查 %s 里那一行" % ENV)
84
+ return t
85
+
86
+
87
+ def api(tok, method, path, body=None, query=None, timeout=90):
88
+ url = API + path + ("?" + urllib.parse.urlencode(query) if query else "")
89
+ data = json.dumps(body, ensure_ascii=False).encode("utf-8") if body is not None else None
90
+ req = urllib.request.Request(url, data=data, method=method)
91
+ req.add_header("Authorization", "Bearer " + tok)
92
+ req.add_header("User-Agent", "wechat-topic-hunter/apify")
93
+ if data is not None:
94
+ req.add_header("Content-Type", "application/json; charset=utf-8")
95
+ code = 200
96
+ try:
97
+ with urllib.request.urlopen(req, timeout=timeout) as r:
98
+ raw = r.read()
99
+ except urllib.error.HTTPError as e:
100
+ code, raw = e.code, e.read()
101
+ except Exception as e:
102
+ die("连不上 api.apify.com(%s)。这是这台机器到 Apify 的网络问题,稍后再试" % type(e).__name__, 3)
103
+ try:
104
+ j = json.loads(raw.decode("utf-8", "replace"))
105
+ except Exception:
106
+ die("Apify 返回的不是 JSON(HTTP %s):%s" % (code, re.sub(r"\s+", " ", raw[:160].decode("utf-8", "replace"))))
107
+ if code >= 400:
108
+ err = (j.get("error") or {}) if isinstance(j, dict) else {}
109
+ if code == 401:
110
+ die("Apify 不认这个令牌(HTTP 401)。去 %s 核对,或重新建一个写进 %s" % (TOKENS_PAGE, ENV))
111
+ die("Apify 报错 HTTP %s %s:%s" % (code, err.get("type") or "", err.get("message") or str(j)[:200]))
112
+ return j
113
+
114
+
115
+ def split_csv(s, limit=50):
116
+ out = [x.strip() for x in re.split(r"[,,]", s or "") if x.strip()]
117
+ if len(out) > limit:
118
+ die("一次最多 %d 个,给了 %d 个" % (limit, len(out)))
119
+ return out
120
+
121
+
122
+ def clean_url(u):
123
+ u = u.strip().replace("&amp;", "&")
124
+ if re.search(r"[\s\"'`$\\@]", u):
125
+ die("链接里有空白、引号或特殊字符:" + u[:60])
126
+ u = re.sub(r"^http://", "https://", u.split("#")[0])
127
+ if not u.startswith("https://mp.weixin.qq.com/"):
128
+ die("只认 mp.weixin.qq.com 的文章链接:" + u[:60])
129
+ return u
130
+
131
+
132
+ def split_urls(s):
133
+ # 链接里本身可能有逗号以外的各种字符,只按逗号后面紧跟 http 的地方切
134
+ return [clean_url(x) for x in re.split(r"[,,]\s*(?=https?://)", s or "") if x.strip()]
135
+
136
+
137
+ def short_url(u):
138
+ """榜单和搜索给的链接带一长串 chksm、scene,打印时只留能打开文章的那几个参数。"""
139
+ u = str(u or "").replace("&amp;", "&").split("#")[0]
140
+ m = re.match(r"^https?://mp\.weixin\.qq\.com/s\?(.+)$", u)
141
+ if not m:
142
+ return re.sub(r"^http://", "https://", u)
143
+ q = urllib.parse.parse_qs(m.group(1), keep_blank_values=True)
144
+ keep = [(k, q[k][0]) for k in ("__biz", "mid", "idx", "sn") if k in q]
145
+ if len(keep) < 4:
146
+ return re.sub(r"^http://", "https://", u)
147
+ return "https://mp.weixin.qq.com/s?" + "&".join("%s=%s" % kv for kv in keep)
148
+
149
+
150
+ def clean(s, n=0):
151
+ s = re.sub(r"<[^>]*>", "", str(s if s is not None else ""))
152
+ s = re.sub(r"\s+", " ", s).strip()
153
+ return (s[:n - 1] + "…") if n and len(s) > n else s
154
+
155
+
156
+ def num(v):
157
+ try: return int(float(v))
158
+ except Exception: return 0
159
+
160
+
161
+ BEIJING = datetime.timezone(datetime.timedelta(hours=8))
162
+
163
+
164
+ def fmt_ts(v):
165
+ """时间戳一律按北京时间显示,机器在哪个时区都一样。"""
166
+ try:
167
+ v = int(float(v))
168
+ return datetime.datetime.fromtimestamp(v, BEIJING).strftime("%Y-%m-%d %H:%M") if v > 0 else ""
169
+ except Exception:
170
+ return str(v or "")[:16]
171
+
172
+
173
+ def region(v):
174
+ """发文地区、留言地区在采集器里是一个对象:国内给省,国外给国家。"""
175
+ if isinstance(v, dict):
176
+ return v.get("province_name") or v.get("country_name") or ""
177
+ return str(v or "")
178
+
179
+
180
+ def split_rows(items):
181
+ """采集器的数据行都带 operation;不带的是它给的通知行(免费次数用完、免费预览暂停、某些条目被跳过)。"""
182
+ rows = [x for x in items if isinstance(x, dict)]
183
+ return [x for x in rows if x.get("operation")], [x for x in rows if not x.get("operation")]
184
+
185
+
186
+ def group_by_target(rows):
187
+ """一次运行可以带多个词、多个号,采集器在每行的 queryTarget 里写它属于哪一个。按出现顺序分组。"""
188
+ order, groups = [], {}
189
+ for r in rows:
190
+ k = str(r.get("queryTarget") or "")
191
+ if k not in groups:
192
+ groups[k] = []; order.append(k)
193
+ groups[k].append(r)
194
+ return [(k, groups[k]) for k in order]
195
+
196
+
197
+ def notice_text(n):
198
+ msg = clean(n.get("message") or json.dumps(n, ensure_ascii=False), 300)
199
+ if n.get("limitReached"):
200
+ return "采集器说:%s\n 这个账号在这个采集器上的免费次数用完了(%s/%s)。在 Apify 后台升级套餐后继续:%s" % (msg, n.get("freeRunsUsed"), n.get("freeRunsLimit"), BILLING_PAGE)
201
+ if n.get("temporarilyUnavailable"):
202
+ return "采集器说:%s\n 这是采集器对免费套餐的临时限制,过一会再试,或在 Apify 后台升级套餐:%s" % (msg, BILLING_PAGE)
203
+ return "采集器说:" + msg
204
+
205
+
206
+ def quote(op, max_usd):
207
+ p = UNIT_PRICE.get(op)
208
+ unit = ("每条约 %s 美元" % p) if p else "每条单价见采集器页面"
209
+ print("报价(2026-11-25 抄的单价,以 Apify 账单为准):每次运行启动 %s 美元,%s。这次最多花 %.2f 美元,到了采集器自己停。" % (START_FEE, unit, max_usd))
210
+
211
+
212
+ def run_actor(tok, inp, max_usd, timeout_s):
213
+ q = {"waitForFinish": 60, "maxTotalChargeUsd": max_usd, "timeout": timeout_s}
214
+ run = api(tok, "POST", "/acts/%s/runs" % ACTOR, body=inp, query=q).get("data") or {}
215
+ if not run.get("id"):
216
+ die("运行没启动起来:" + json.dumps(run, ensure_ascii=False)[:200])
217
+ t0 = time.time()
218
+ while run.get("status") not in DONE and time.time() - t0 < timeout_s + 60:
219
+ run = api(tok, "GET", "/actor-runs/%s" % run["id"], query={"waitForFinish": 60}).get("data") or run
220
+ if run.get("status") not in DONE:
221
+ die("等了 %d 秒运行还没结束(运行号 %s),去 Apify 后台看它的状态" % (int(time.time() - t0), run.get("id")))
222
+ items = api(tok, "GET", "/datasets/%s/items" % run.get("defaultDatasetId"), query={"clean": "true", "format": "json"})
223
+ if not isinstance(items, list):
224
+ items = []
225
+ if run.get("status") != "SUCCEEDED":
226
+ print("这次运行没成功(%s):%s" % (run.get("status"), clean(run.get("statusMessage"), 200)))
227
+ print(" 多半是采集器或微信那头临时出问题,过一会原样再跑一次。没拿到数据的运行只扣启动费。")
228
+ return run, items
229
+
230
+
231
+ def finish(run, inp, items, save, n_rows):
232
+ """落盘原始结果(如果要),再报这次大约花了多少。"""
233
+ if save:
234
+ keep = {k: run.get(k) for k in ("id", "status", "startedAt", "finishedAt", "statusMessage")}
235
+ io.open(save, "w", encoding="utf-8", newline="\n").write(json.dumps({"input": inp, "run": keep, "items": items}, ensure_ascii=False, indent=1))
236
+ print("原始结果已存:" + save)
237
+ est = estimate_usd(inp.get("operation"), n_rows)
238
+ print("这次拿回 %d 行数据|%s准数看 Apify 后台这次运行的账,本期总用量跑 me 看。" % (n_rows, ("按单价估约 %.3f 美元|" % est) if est is not None else ""))
239
+
240
+
241
+ def estimate_usd(op, n_rows):
242
+ """按上面那张单价表估这次花了多少:一次启动费 + 拿回的数据行数 × 这个操作的单价。单价表里没有的操作不估。
243
+ 不用 Apify 回的计费数:它刚跑完时会滞后好几秒到一两分钟,当场读不准。"""
244
+ p = UNIT_PRICE.get(op)
245
+ if p is None:
246
+ return None
247
+ return round(START_FEE + max(0, n_rows) * p, 3)
248
+
249
+
250
+ def fetch(tok, a, inp):
251
+ quote(inp["operation"], a.max_usd)
252
+ run, items = run_actor(tok, inp, a.max_usd, a.timeout)
253
+ rows, notices = split_rows(items)
254
+ for n in notices:
255
+ print(notice_text(n))
256
+ if not rows and not notices and run.get("status") == "SUCCEEDED" and run.get("statusMessage"):
257
+ print("采集器说:" + clean(run.get("statusMessage"), 200)) # 跑成功但一行都没有时,它会在这里说原因
258
+ return run, items, rows
259
+
260
+
261
+ # ---------- 低粉爆文榜 ----------
262
+ def filter_viral(rows, cats, kws, min_boost):
263
+ out = []
264
+ for r in rows:
265
+ if cats and str(r.get("accountCategory") or "") not in cats:
266
+ continue
267
+ hay = (str(r.get("title") or "") + " " + str(r.get("accountName") or "")).lower()
268
+ if kws and not any(k.lower() in hay for k in kws):
269
+ continue
270
+ if min_boost and float(r.get("boostRatio") or 0) < min_boost:
271
+ continue
272
+ out.append(r)
273
+ return sorted(out, key=lambda r: num(r.get("rank")) or 10 ** 6)
274
+
275
+
276
+ def category_counts(rows):
277
+ c = {}
278
+ for r in rows:
279
+ k = str(r.get("accountCategory") or "").strip() or "未分类"
280
+ c[k] = c.get(k, 0) + 1
281
+ return sorted(c.items(), key=lambda kv: -kv[1])
282
+
283
+
284
+ def cmd_viral(a, tok):
285
+ inp = {"operation": "viralArticles", "rankingWindow": a.window, "maxPages": a.pages}
286
+ if a.date:
287
+ dates = split_csv(a.date)
288
+ if [d for d in dates if not re.match(r"^\d{4}-\d{2}-\d{2}$", d)]:
289
+ die("--date 格式 YYYY-MM-DD,多个用逗号隔开")
290
+ inp["rankingDates"] = dates
291
+ run, items, rows = fetch(tok, a, inp)
292
+ if rows:
293
+ cats, kws = set(split_csv(a.category)), split_csv(a.keyword)
294
+ picked = filter_viral(rows, cats, kws, a.min_boost)
295
+ print("低粉爆文榜 %s 窗口 %s:拿回 %d 条,筛后 %d 条,列前 %d 条" % (rows[0].get("rankingDate") or "", rows[0].get("rankingWindow") or a.window, len(rows), len(picked), min(a.n, len(picked))))
296
+ print("这页的分类:" + "、".join("%s %d" % kv for kv in category_counts(rows)) + "(榜不能按词或分类去取,只能拿回来筛;想要的分类少就加 --pages)")
297
+ for r in picked[:a.n]:
298
+ print("#%s [%s] 阅读 %s|平时 %s|倍率 %.1f|分享 %s|评论 %s|%s|%s" % (r.get("rank"), r.get("accountCategory") or "未分类", num(r.get("read_num")), num(r.get("accountReadBaseline")),
299
+ float(r.get("boostRatio") or 0), num(r.get("share_count")), num(r.get("comment_count")), clean(r.get("accountName"), 20), clean(r.get("title"), 40)))
300
+ print(" " + short_url(r.get("url")))
301
+ print("阅读显示 100001 的是 10 万加。倍率只是标注,题写不写你定;拿的是题材和角度,不搬正文。")
302
+ finish(run, inp, items, a.save, len(rows))
303
+
304
+
305
+ # ---------- 搜文章 ----------
306
+ def cmd_search(a, tok):
307
+ kws = split_csv(a.keyword)
308
+ if not kws:
309
+ die("--keyword 不能为空")
310
+ inp = {"operation": "articleSearch", "keywords": kws, "maxPages": a.pages, "sortBy": a.sort, "publishTime": a.time}
311
+ run, items, rows = fetch(tok, a, inp)
312
+ for kw, mine in group_by_target(rows):
313
+ print("「%s」搜到 %d 篇:" % (kw, len(mine)))
314
+ for r in mine:
315
+ src = r.get("source") if isinstance(r.get("source"), dict) else {}
316
+ print(" %s|%s|%s" % (fmt_ts(r.get("timestamp") or r.get("date")), clean(src.get("title"), 20), clean(r.get("title"), 46)))
317
+ print(" " + short_url(r.get("doc_url")))
318
+ if rows:
319
+ print("搜索结果不带阅读数。要看哪篇读了多少,把链接交给 metrics(按篇计费)。")
320
+ finish(run, inp, items, a.save, len(rows))
321
+
322
+
323
+ # ---------- 单篇数据 ----------
324
+ def cmd_metrics(a, tok):
325
+ urls = split_urls(a.url)
326
+ if not urls:
327
+ die("--url 不能为空")
328
+ inp = {"operation": "articleMetrics", "articleUrls": urls}
329
+ run, items, rows = fetch(tok, a, inp)
330
+ for r in rows:
331
+ print("阅读 %d|点赞 %d|在看 %d|分享 %d|收藏 %d|评论 %d" % (num(r.get("read_num")), num(r.get("old_like_count")), num(r.get("like_count")),
332
+ num(r.get("share_count")), num(r.get("collect_count")), num(r.get("comment_count"))))
333
+ print(" " + short_url(r.get("queryTarget")))
334
+ if rows:
335
+ print("点赞取的是 old_like_count、在看取的是 like_count(微信接口的老叫法)。阅读显示 100001 的是 10 万加。")
336
+ finish(run, inp, items, a.save, len(rows))
337
+
338
+
339
+ # ---------- 找号 ----------
340
+ def account_rows(rows, include_all=False):
341
+ """按词搜号的结果里混着视频号、小程序,默认只留公众号(订阅号和服务号都是公众号)。"""
342
+ return [r for r in rows if include_all or str(r.get("accTypeName") or "") in ("公众号", "服务号")]
343
+
344
+
345
+ def cmd_accounts(a, tok):
346
+ kws = split_csv(a.keyword)
347
+ if not kws:
348
+ die("--keyword 不能为空")
349
+ inp = {"operation": "accountSearch", "keywords": kws, "maxPages": a.pages}
350
+ run, items, rows = fetch(tok, a, inp)
351
+ for kw, mine in group_by_target(rows):
352
+ mine = [r for r in mine if r.get("userName")] # 微信搜索夹带的提示行(如开启位置)没有原始ID,不是账号
353
+ print("「%s」搜到 %d 个账号,其中公众号 %d 个:" % (kw, len(mine), len(account_rows(mine))))
354
+ for r in account_rows(mine, a.all):
355
+ print(" [%s] %s|微信号 %s|原始ID %s|主体 %s|%s|%s" % (r.get("accTypeName") or "未知", clean(r.get("nickName") or r.get("title"), 24), r.get("aliasName") or "无", r.get("userName") or "无",
356
+ clean(r.get("principalName"), 24) or "未知", "已认证" if r.get("verified") else "未认证", clean(r.get("originalContentStr"), 16) or "原创数未知"))
357
+ if r.get("signature"):
358
+ print(" " + clean(r.get("signature"), 90))
359
+ if rows:
360
+ print("把原始ID 交给 history,看这个号最近发了什么、哪篇读得多。")
361
+ finish(run, inp, items, a.save, len(rows))
362
+
363
+
364
+ # ---------- 一个号的历史发文 ----------
365
+ def parse_reads(desc):
366
+ """历史发文列表里微信给的阅读写在 showDesc 里:Reads: 763、Reads: 92k、Reads: 100k+(中文界面是 阅读 763、阅读 9.2万、阅读 10万+)。
367
+ 取成 (整数, 是不是带加号的下限);认不出给 (None, False)。过万的微信只给到千位,所以是约数。"""
368
+ m = re.search(r"(?:Reads?|阅读)\s*[::]?\s*([\d.]+)\s*([kKwW万]?)\s*(\+?)", re.sub(r"\s+", " ", str(desc or "")))
369
+ if not m:
370
+ return None, False
371
+ try:
372
+ v = float(m.group(1))
373
+ except ValueError:
374
+ return None, False
375
+ v *= 1000 if m.group(2) in ("k", "K") else (10000 if m.group(2) in ("w", "W", "万") else 1)
376
+ return int(v), bool(m.group(3))
377
+
378
+
379
+ def head_median(rows):
380
+ """这批发文里头条(每次推送的第 1 条,itemIndex 从 1 起,2026-11-26 实测)的阅读中位。次条不代表这个号的水平,不算。少于 3 篇头条不算,给 None。"""
381
+ reads = [parse_reads(r.get("showDesc"))[0] for r in rows if num(r.get("itemIndex")) == 1]
382
+ reads = [x for x in reads if x is not None]
383
+ return int(statistics.median(reads)) if len(reads) >= 3 else None
384
+
385
+
386
+ def cmd_history(a, tok):
387
+ accounts = [clean_url(x) if x.startswith("http") else x for x in split_csv(a.account)]
388
+ if not accounts:
389
+ die("--account 不能为空")
390
+ inp = {"operation": "accountHistoryArticles", "accounts": accounts, "maxPages": a.pages}
391
+ run, items, rows = fetch(tok, a, inp)
392
+ for acc, mine in group_by_target(rows):
393
+ med = head_median(mine)
394
+ print("%s 的历史发文 %d 篇%s:" % (acc[:40], len(mine), ("|头条阅读中位 %d" % med) if med else ""))
395
+ for r in mine:
396
+ reads, plus = parse_reads(r.get("showDesc"))
397
+ if reads is None:
398
+ tag = clean(r.get("showDesc"), 30)
399
+ else:
400
+ tag = "阅读 %d%s" % (reads, "+" if plus else "") + ("|倍率 %.1f" % (reads / float(med)) if med else "")
401
+ print(" %s|第 %s 条|%s|%s" % (fmt_ts(r.get("publishTimestamp") or r.get("sendTime")), r.get("itemIndex") or "?", clean(r.get("title"), 44), tag))
402
+ print(" " + short_url(r.get("url") or r.get("contentUrl")))
403
+ if rows:
404
+ print("第 1 条是那次推送的头条。倍率 = 这篇阅读 ÷ 这批头条的阅读中位,2 以上是这个号的读者格外买账的题。")
405
+ print("阅读是微信列表里给的数:过万只到千位,10 万以上只显示 100000+。要准数把链接交给 metrics。")
406
+ finish(run, inp, items, a.save, len(rows))
407
+
408
+
409
+ # ---------- 正文 ----------
410
+ def cmd_detail(a, tok):
411
+ urls = split_urls(a.url)
412
+ if not urls:
413
+ die("--url 不能为空")
414
+ inp = {"operation": "articleDetail", "articleUrls": urls}
415
+ run, items, rows = fetch(tok, a, inp)
416
+ for r in rows:
417
+ text = str(r.get("contentText") or "")
418
+ print("《%s》%s|作者 %s|%s|原创 %s|发文地区 %s|正文 %d 字" % (clean(r.get("title"), 60), clean(r.get("accountName"), 20), clean(r.get("author"), 16) or "未署名",
419
+ str(r.get("publishTime") or "")[:16], "是" if r.get("isOriginal") else "否", region(r.get("ipRegion")) or "未知", len(text)))
420
+ print(" 开头:" + clean(text, 300))
421
+ if rows:
422
+ print("正文只当素材看题材、角度、结构,不搬运、不洗稿。全文加 --save 落盘。")
423
+ finish(run, inp, items, a.save, len(rows))
424
+
425
+
426
+ # ---------- 留言 ----------
427
+ def cmd_comments(a, tok):
428
+ urls = split_urls(a.url)
429
+ if not urls:
430
+ die("--url 不能为空")
431
+ inp = {"operation": "articleComments", "articleUrls": urls, "maxPages": a.pages}
432
+ run, items, rows = fetch(tok, a, inp)
433
+ if rows:
434
+ print("留言 %d 条(按点赞从高到低):" % len(rows))
435
+ for r in sorted(rows, key=lambda r: -num(r.get("like_num"))):
436
+ print(" 赞 %d|%s|%s|%s|回复 %d" % (num(r.get("like_num")), clean(r.get("nick_name"), 14), region(r.get("ip_wording")), clean(r.get("content"), 120), num(r.get("replyTotalCount"))))
437
+ finish(run, inp, items, a.save, len(rows))
438
+
439
+
440
+ # ---------- 微信指数 ----------
441
+ def index_stats(points):
442
+ """dataPoints = [{index, timestamp}],按时间排好后给:最新、最高、最低、平均、近 7 天均值比前 7 天均值的变化(百分比,算不了给 None)。"""
443
+ pts = sorted([p for p in points or [] if isinstance(p, dict)], key=lambda p: num(p.get("timestamp")))
444
+ vals = [num(p.get("index")) for p in pts]
445
+ if not vals:
446
+ return None
447
+ last7, prev7 = vals[-7:], vals[-14:-7]
448
+ change = None
449
+ if len(prev7) == 7 and sum(prev7) > 0:
450
+ change = round(100.0 * (sum(last7) / 7.0 - sum(prev7) / 7.0) / (sum(prev7) / 7.0), 1)
451
+ return {"n": len(vals), "latest": vals[-1], "max": max(vals), "min": min(vals), "avg": int(sum(vals) / len(vals)), "change7": change,
452
+ "tail": [(fmt_ts(p.get("timestamp"))[5:10], num(p.get("index"))) for p in pts[-7:]]}
453
+
454
+
455
+ def cmd_index(a, tok):
456
+ kws = split_csv(a.keyword)
457
+ if not kws:
458
+ die("--keyword 不能为空")
459
+ inp = {"operation": "wechatIndexSearch", "keywords": kws}
460
+ run, items, rows = fetch(tok, a, inp)
461
+ for r in rows:
462
+ s = index_stats(r.get("dataPoints"))
463
+ if not s:
464
+ print("「%s」没拿到指数" % r.get("queryTarget")); continue
465
+ ch = ("近 7 天均值比前 7 天 %+.1f%%" % s["change7"]) if s["change7"] is not None else "数据点不够算周变化"
466
+ print("「%s」微信指数 %d 天:最新 %d|最高 %d|最低 %d|平均 %d|%s" % (r.get("queryTarget"), s["n"], s["latest"], s["max"], s["min"], s["avg"], ch))
467
+ print(" 近 7 天:" + " ".join("%s %d" % t for t in s["tail"]))
468
+ finish(run, inp, items, a.save, len(rows))
469
+
470
+
471
+ # ---------- 联想词 ----------
472
+ def suggestion_words(row):
473
+ """联想词在 suggestions 里,一般是一串字符串;万一是对象就取里面像词的那个字段。"""
474
+ out = []
475
+ for x in row.get("suggestions") or []:
476
+ w = x if isinstance(x, str) else (x.get("word") or x.get("title") or x.get("query") or "") if isinstance(x, dict) else ""
477
+ if clean(w):
478
+ out.append(clean(w))
479
+ return out
480
+
481
+
482
+ def cmd_suggest(a, tok):
483
+ kws = split_csv(a.keyword)
484
+ if not kws:
485
+ die("--keyword 不能为空")
486
+ inp = {"operation": "searchSuggestions", "keywords": kws}
487
+ run, items, rows = fetch(tok, a, inp)
488
+ for r in rows:
489
+ words = suggestion_words(r)
490
+ print("「%s」的联想词 %d 个:%s" % (r.get("queryTarget"), len(words), "、".join(words)))
491
+ if rows:
492
+ print("联想词是微信搜一搜里别人接着这个词在搜的。挑跟品类对得上的当候选题的核心词,再用 index 看热度、用 search 看有没有人写。")
493
+ finish(run, inp, items, a.save, len(rows))
494
+
495
+
496
+ # ---------- 其余操作原样跑 ----------
497
+ def run_input(op, keyword, url, account, pages, extra_json, link=None):
498
+ """通用入口的输入:操作名只认那 16 个;--json 里的额外字段原样带上,但不让它改 operation,也不带 feedback(那是给采集器作者留言用的)。"""
499
+ if op not in OPS:
500
+ die("--op 只认这 16 个:" + " ".join(OPS))
501
+ inp = {"operation": op}
502
+ if keyword: inp["keywords"] = split_csv(keyword)
503
+ if url: inp["articleUrls"] = split_urls(url)
504
+ if account: inp["accounts"] = split_csv(account)
505
+ if link: inp["links"] = split_urls(link)
506
+ if pages: inp["maxPages"] = pages
507
+ if extra_json:
508
+ try:
509
+ extra = json.loads(extra_json)
510
+ except Exception as e:
511
+ die("--json 不是合法 JSON:%s" % e)
512
+ if not isinstance(extra, dict):
513
+ die("--json 要是一个对象")
514
+ extra.pop("feedback", None)
515
+ extra.pop("operation", None)
516
+ inp.update(extra)
517
+ return inp
518
+
519
+
520
+ def cmd_run(a, tok):
521
+ inp = run_input(a.op, a.keyword, a.url, a.account, a.pages, a.json, a.link)
522
+ run, items, rows = fetch(tok, a, inp)
523
+ save = a.save or ("apify-%s-%s.json" % (a.op, time.strftime("%Y%m%d-%H%M%S")))
524
+ print("%s 返回 %d 行。" % (a.op, len(rows)))
525
+ if rows:
526
+ print("第一行的字段:" + ", ".join(list(rows[0].keys())[:40]))
527
+ finish(run, inp, items, save, len(rows))
528
+
529
+
530
+ def cmd_me(a, tok):
531
+ me = api(tok, "GET", "/users/me").get("data") or {}
532
+ plan = me.get("plan") or {}
533
+ lim = api(tok, "GET", "/users/me/limits").get("data") or {}
534
+ cyc, cur, lm = lim.get("monthlyUsageCycle") or {}, lim.get("current") or {}, lim.get("limits") or {}
535
+ print("Apify 账号 %s|套餐 %s|%s" % (me.get("username"), plan.get("id") or "未知", "付费套餐" if me.get("isPaying") else "免费套餐"))
536
+ print("本期 %s 到 %s|已用 %.2f 美元|月上限 %s 美元" % (str(cyc.get("startAt") or "")[:10], str(cyc.get("endAt") or "")[:10], cur.get("monthlyUsageUsd") or 0, lm.get("maxMonthlyUsageUsd")))
537
+ print("额度用到月上限就停。付费套餐可以在 %s 的 Limits 里调上限;免费套餐要继续用就在那里升级。" % BILLING_PAGE)
538
+
539
+
540
+ def main():
541
+ ap = argparse.ArgumentParser(description="公众号数据(Apify 采集器 zen-studio/wechat-official-account-scraper,用你自己的令牌)")
542
+ sub = ap.add_subparsers(dest="cmd")
543
+ sub.add_parser("me")
544
+
545
+ def paid(name):
546
+ p = sub.add_parser(name)
547
+ p.add_argument("--max-usd", type=float, default=1.0, help="这次运行最多花多少美元,默认 1")
548
+ p.add_argument("--save", help="原始结果存到这个文件")
549
+ p.add_argument("--timeout", type=int, default=600, help="最多等多少秒,默认 600")
550
+ return p
551
+
552
+ p = paid("viral"); p.add_argument("--date"); p.add_argument("--window", choices=["3d", "7d", "30d"], default="7d"); p.add_argument("--pages", type=int, default=1)
553
+ p.add_argument("--category"); p.add_argument("--keyword"); p.add_argument("--min-boost", type=float, default=0); p.add_argument("--n", type=int, default=30)
554
+ p = paid("search"); p.add_argument("--keyword", required=True); p.add_argument("--pages", type=int, default=1)
555
+ p.add_argument("--sort", choices=["relevance", "latest", "hot"], default="relevance"); p.add_argument("--time", choices=["all", "day", "week", "halfYear"], default="all")
556
+ p = paid("metrics"); p.add_argument("--url", required=True)
557
+ p = paid("accounts"); p.add_argument("--keyword", required=True); p.add_argument("--pages", type=int, default=1); p.add_argument("--all", action="store_true", help="连视频号、小程序一起列")
558
+ p = paid("history"); p.add_argument("--account", required=True); p.add_argument("--pages", type=int, default=1)
559
+ p = paid("detail"); p.add_argument("--url", required=True)
560
+ p = paid("comments"); p.add_argument("--url", required=True); p.add_argument("--pages", type=int, default=1)
561
+ p = paid("index"); p.add_argument("--keyword", required=True)
562
+ p = paid("suggest"); p.add_argument("--keyword", required=True)
563
+ p = paid("run"); p.add_argument("--op", required=True); p.add_argument("--keyword"); p.add_argument("--url"); p.add_argument("--account"); p.add_argument("--link"); p.add_argument("--pages", type=int); p.add_argument("--json")
564
+ a = ap.parse_args()
565
+ if not a.cmd:
566
+ print(__doc__); return
567
+ if a.cmd != "me":
568
+ if a.max_usd <= 0:
569
+ die("--max-usd 要大于 0")
570
+ if getattr(a, "pages", None) is not None and not 1 <= a.pages <= 50:
571
+ die("--pages 在 1 到 50 之间")
572
+ tok = load_token()
573
+ {"me": cmd_me, "viral": cmd_viral, "search": cmd_search, "metrics": cmd_metrics, "accounts": cmd_accounts, "history": cmd_history,
574
+ "detail": cmd_detail, "comments": cmd_comments, "index": cmd_index, "suggest": cmd_suggest, "run": cmd_run}[a.cmd](a, tok)
575
+
576
+
577
+ if __name__ == "__main__":
578
+ main()