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
@@ -1,466 +1,466 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """公众号选题对标(wxrank 微小榜数据)。你自己的 wxrank key,你自己充值,每次调用都先告诉你要花多少积分。
4
-
5
- 用法:
6
- python wxrank_topics.py balance 余额(免费)
7
- python wxrank_topics.py hot --keyword 出海 [--date 20261001 | --month 202610] [--min-read 1000] [--type 科技] [--n 20]
8
- 离线库里这个词阅读最高的文章(1 积分)
9
- python wxrank_topics.py search --keyword 出海 [--sort 新|热] [--page 1] 搜一搜文章列表(10 积分)
10
- python wxrank_topics.py accounts --keyword 出海 找公众号,拿原始ID 和 biz(10 积分)
11
- python wxrank_topics.py posts --wxid gh_xxx 某个号最近一页推文(5 积分)
12
- python wxrank_topics.py benchmark --wxid gh_xxx [--n 10] [--yes] 对标一个号:最近 N 篇各拉一次阅读在看分享,算阅读中位、爆款倍率、爆款分(5 + 2N 积分,先报价,加 --yes 才扣)
13
- python wxrank_topics.py article --url "https://mp.weixin.qq.com/s?__biz=..." 一篇文章的阅读 点赞 在看 分享 收藏 赞赏(2 积分,短链多 1 积分)
14
- python wxrank_topics.py feed [--group AI,热榜] [--keyword 副业,AI] [--n 15] [--hot-only] 读仓库每天自动更新的内容清单(免费 不花积分)
15
- python wxrank_topics.py direction --keywords 出海,副业,AI写作 [--month 202610] 方向比较:每个词看一次榜 出一张表(每词 1 积分)
16
- python wxrank_topics.py calendar --keyword 出海 [--n 10] [--per-week 2] [--start 2026-10-14] [--month 202610] 内容清单:清单里挑题 对照榜 排日期(1 积分)
17
-
18
- 凭据:~/.wxrank.env 一行 KEY=你的key(或环境变量 WXRANK_KEY)。注册和充值 https://data.wxrank.com ,100 积分 = 1 元。
19
- 纪律:只读;每天上限 WXRANK_DAILY_CAP 积分(默认 300);用量记 ~/.wxrank-usage.log;输出不含 key;只用标准库。
20
- 口径:wxrank 的数是实时抓的公开数,跟后台会差;爆款倍率 = 单篇阅读 ÷ 该号阅读中位;爆款分 = 阅读 + 3 × 分享(分享比阅读值钱)。只标注数字,选题是你定。
21
- """
22
- import argparse, datetime, io, json, os, re, statistics, sys, time, urllib.request, urllib.error
23
-
24
- try:
25
- sys.stdout.reconfigure(encoding="utf-8"); sys.stderr.reconfigure(encoding="utf-8")
26
- except Exception:
27
- pass
28
-
29
- BASE = "https://data.wxrank.com/weixin/"
30
- FEED_URL = os.environ.get("WECHAT_FEED_URL", "https://raw.githubusercontent.com/adsorgcn/WorkBuddy/main/data/hot/latest.json")
31
- FEED_LOCAL = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))), "data", "hot", "latest.json")
32
- ENV = os.path.join(os.path.expanduser("~"), ".wxrank.env")
33
- LOG = os.path.join(os.path.expanduser("~"), ".wxrank-usage.log")
34
- DAILY_CAP = int(os.environ.get("WXRANK_DAILY_CAP", "300"))
35
- ERR = {1000: "积分不足 或 key 不对(key 错时 wxrank 也回 1000)先核 ~/.wxrank.env 再去 data.wxrank.com 充值",
36
- 1001: "参数为空 或不是公众号文章链接", 1002: "请求失败或文章验证失败 可以重试一次", 1003: "获取失败 可以重试一次",
37
- 1004: "wxrank 服务异常 稍后再试", 1008: "请求太频繁 歇一会再查", 9999: "超过 QPS 上限 歇一秒再查"}
38
- TYPES = "时事 文化 健康 职场 学术 美食 民生 科技 情感 楼市 汽车 幽默 政务 财富 旅行 企业 时尚 美体 教育 体娱 百科 乐活 创业 文摘".split()
39
-
40
-
41
- def die(msg, code=1):
42
- print("错误:" + msg); sys.exit(code)
43
-
44
-
45
- def load_key():
46
- k = os.environ.get("WXRANK_KEY", "").strip()
47
- if not k and os.path.exists(ENV):
48
- for line in io.open(ENV, encoding="utf-8"):
49
- line = line.strip()
50
- if "=" in line and not line.startswith("#"):
51
- a, b = line.split("=", 1)
52
- if a.strip().upper() in ("KEY", "WXRANK_KEY"):
53
- k = b.strip().strip('"').strip("'")
54
- if not k:
55
- die("没找到 wxrank key。注册 https://data.wxrank.com 拿 key,写进 %s 一行 KEY=你的key" % ENV)
56
- if re.search(r"[\s\"'\\]", k):
57
- die("key 里有空白或引号,不合法")
58
- return k
59
-
60
-
61
- def today():
62
- return datetime.date.today().isoformat()
63
-
64
-
65
- def spent_today():
66
- if not os.path.exists(LOG):
67
- return 0
68
- s = 0
69
- for line in io.open(LOG, encoding="utf-8"):
70
- parts = line.split()
71
- if parts and parts[0] == today():
72
- for p in parts:
73
- if p.startswith("units="):
74
- try: s += int(p[6:])
75
- except ValueError: pass
76
- return s
77
-
78
-
79
- def logit(cmd, arg, rows, units):
80
- arg = re.sub(r"\s+", "_", arg)[:80] or "-"
81
- io.open(LOG, "a", encoding="utf-8").write("%s %s %s %s lines=%d units=%d\n" % (today(), datetime.datetime.now().strftime("%H:%M:%S"), cmd, arg, rows, units))
82
-
83
-
84
- def gate(units):
85
- s = spent_today()
86
- if s + units > DAILY_CAP:
87
- die("今天的 wxrank 额度到上限了(已用 %d 积分 上限 %d)明天再查,或者设环境变量 WXRANK_DAILY_CAP 调高" % (s, DAILY_CAP), 4)
88
-
89
-
90
- _last_call = [0.0]
91
-
92
-
93
- def call(endpoint, body, key):
94
- # QPS:搜索类每秒 3 个,阅读每秒 10 个;统一隔 0.4 秒
95
- wait = 0.4 - (time.time() - _last_call[0])
96
- if wait > 0:
97
- time.sleep(wait)
98
- _last_call[0] = time.time()
99
- body = dict(body); body["key"] = key
100
- req = urllib.request.Request(BASE + endpoint, data=json.dumps(body, ensure_ascii=False).encode("utf-8"), method="POST",
101
- headers={"Content-Type": "application/json", "User-Agent": "wechat-topic-hunter/1.0"})
102
- try:
103
- with urllib.request.urlopen(req, timeout=20) as r:
104
- raw = r.read().decode("utf-8", errors="replace")
105
- except urllib.error.HTTPError as e:
106
- raw = e.read().decode("utf-8", errors="replace")
107
- except Exception as e:
108
- die("连不上 wxrank(%s)稍后再试" % type(e).__name__)
109
- raw = raw.replace(key, "[key]")
110
- try:
111
- j = json.loads(raw)
112
- except Exception:
113
- die("wxrank 返回的不是 JSON:" + re.sub(r"\s+", " ", raw)[:120])
114
- code = j.get("code")
115
- if code != 0:
116
- die("wxrank 报错 code %s:%s" % (code, ERR.get(code, "未知错误码")))
117
- m = re.search(r"(\d+)", str(j.get("msg", "")))
118
- return j.get("data"), (int(m.group(1)) if m else None)
119
-
120
-
121
- def clean(s, n=0):
122
- s = re.sub(r"<[^>]*>", "", str(s if s is not None else ""))
123
- s = re.sub(r"\s+", " ", s).strip()
124
- return s[:n] if n else s
125
-
126
-
127
- def num(v):
128
- try: return int(float(v))
129
- except Exception: return 0
130
-
131
-
132
- def fmt_time(v):
133
- v = str(v or "")
134
- if v.isdigit() and len(v) >= 10:
135
- try: return datetime.datetime.fromtimestamp(int(v[:10])).strftime("%Y-%m-%d %H:%M")
136
- except Exception: return v
137
- return v[:16]
138
-
139
-
140
- def clean_url(u):
141
- u = u.strip().replace("&amp;", "&")
142
- if re.search(r"[\s\"'`$\\@]", u):
143
- die("链接里有空白、引号或特殊字符")
144
- u = u.split("#")[0]
145
- u = re.sub(r"^http://", "https://", u)
146
- if not u.startswith("https://mp.weixin.qq.com/"):
147
- die("只认 mp.weixin.qq.com 的文章链接")
148
- return u
149
-
150
-
151
- def tail(units, bal):
152
- print("本次 %d 积分|余额 %s|今天已用 %d 积分 上限 %d" % (units, ("%d 积分 约 %.2f 元" % (bal, bal / 100)) if bal is not None else "未知", spent_today(), DAILY_CAP))
153
-
154
-
155
- # ---------- commands ----------
156
- def cmd_balance(a, key):
157
- _, bal = call("score", {}, key)
158
- logit("balance", "-", 1, 0)
159
- print("wxrank 余额 %s 积分 约 %.2f 元|今天已用 %d 积分 上限 %d" % (bal, (bal or 0) / 100, spent_today(), DAILY_CAP))
160
- if bal == 0:
161
- print("余额为 0 也可能是 key 不对,先核 %s" % ENV)
162
-
163
-
164
- def cmd_hot(a, key):
165
- body = {"keyword": a.keyword, "content_type": "article"}
166
- if a.date: body["date"] = a.date
167
- elif a.month: body["month"] = a.month
168
- if a.min_read: body["min_read_num"] = a.min_read
169
- if a.type:
170
- if a.type not in TYPES: die("分类只认:" + " ".join(TYPES))
171
- body["wx_type"] = a.type
172
- gate(1)
173
- data, bal = call("artlist", body, key)
174
- lst = (data or {}).get("list") or []
175
- total = (data or {}).get("total")
176
- logit("hot", a.keyword, len(lst), 1)
177
- print("离线库「%s」%s:命中 %s 篇,取阅读最高的 %d 篇,按爆款分(阅读 + 3 × 分享)重排" % (a.keyword, a.date or a.month or "当月", total if total is not None else "?", min(len(lst), a.n)))
178
- rows = []
179
- for it in lst[: a.n]:
180
- rows.append({"read": num(it.get("read_num")), "look": num(it.get("look_num")), "share": num(it.get("share_num")), "words": num(it.get("word_num")),
181
- "type": clean(it.get("wx_type")), "biz": clean(it.get("wx_biz")), "time": fmt_time(it.get("pub_time")),
182
- "title": clean(it.get("title"), 60), "url": re.sub(r"\s+", "", str(it.get("art_url") or "")), "copyright": clean(it.get("copyright"))})
183
- for i, r in enumerate(sorted(rows, key=lambda x: x["read"] + 3 * x["share"], reverse=True), 1):
184
- print("%2d. 爆款分 %6d 阅读 %6d 在看 %4d 分享 %4d %4d 字 %s %s %s" % (i, r["read"] + 3 * r["share"], r["read"], r["look"], r["share"], r["words"], r["type"] or "-", r["time"], r["title"]))
185
- print(" biz %s %s" % (r["biz"], r["url"]))
186
- if not lst:
187
- print("没命中。换个更宽的词,或者去掉日期用当月(空列表也扣 1 积分)")
188
- else:
189
- out = os.path.join(os.getcwd(), "hot-%s-%s.json" % (re.sub(r"[^0-9A-Za-z一-鿿_-]", "", a.keyword)[:20], datetime.datetime.now().strftime("%Y%m%d-%H%M%S")))
190
- io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(rows, ensure_ascii=False, indent=1))
191
- print("明细已存:" + out + "(biz 可以拿去 accounts 反查原始ID,再用 benchmark 对标)")
192
- tail(1, bal)
193
-
194
-
195
- def cmd_search(a, key):
196
- st = {"新": 2, "热": 4}.get(a.sort, 0)
197
- gate(10)
198
- data, bal = call("getso", {"keyword": a.keyword, "sort_type": st, "page": a.page}, key)
199
- lst = data if isinstance(data, list) else []
200
- logit("search", a.keyword, len(lst), 10)
201
- print("搜一搜「%s」排序 %s 第 %d 页:%d 篇" % (a.keyword, a.sort or "不限", a.page, len(lst)))
202
- for i, it in enumerate(lst, 1):
203
- print("%2d. %s %s %s" % (i, fmt_time(it.get("pub_time")), clean(it.get("wx_name")), clean(it.get("title"), 60)))
204
- print(" %s" % re.sub(r"\s+", "", str(it.get("art_url") or "")))
205
- tail(10, bal)
206
-
207
-
208
- def cmd_accounts(a, key):
209
- gate(10)
210
- data, bal = call("getsu", {"keyword": a.keyword, "page": a.page}, key)
211
- lst = data if isinstance(data, list) else []
212
- logit("accounts", a.keyword, len(lst), 10)
213
- print("搜公众号「%s」第 %d 页:%d 个" % (a.keyword, a.page, len(lst)))
214
- for i, it in enumerate(lst, 1):
215
- print("%2d. %s 原始ID %s 微信号 %s 简介 %s" % (i, clean(it.get("wx_name")), clean(it.get("wx_user")), clean(it.get("wx_id")), clean(it.get("signature"), 40)))
216
- tail(10, bal)
217
-
218
-
219
- def fetch_posts(wxid, key):
220
- data, bal = call("getps", {"wxid": wxid}, key)
221
- lst = (data or {}).get("list") or []
222
- return lst, bal
223
-
224
-
225
- def cmd_posts(a, key):
226
- gate(5)
227
- lst, bal = fetch_posts(a.wxid, key)
228
- logit("posts", a.wxid, len(lst), 5)
229
- print("%s 最近一页推文 %d 篇(不翻页)" % (a.wxid, len(lst)))
230
- for i, it in enumerate(lst, 1):
231
- print("%2d. %s idx%s %s" % (i, fmt_time(it.get("pub_time")), re.search(r"idx=(\d)", str(it.get("art_url") or "")).group(1) if re.search(r"idx=(\d)", str(it.get("art_url") or "")) else "?", clean(it.get("title"), 60)))
232
- print(" %s" % re.sub(r"\s+", "", str(it.get("art_url") or "")))
233
- tail(5, bal)
234
-
235
-
236
- def read_article(url, key):
237
- data, bal = call("getrk", {"url": url}, key)
238
- d = data or {}
239
- return {"read": num(d.get("read_num")), "like": num(d.get("like_num")), "look": num(d.get("look_num")),
240
- "share": num(d.get("share_num")), "collect": num(d.get("collect_num")), "reward": num(d.get("reward_count"))}, bal
241
-
242
-
243
- def cmd_article(a, key):
244
- url = clean_url(a.url)
245
- units = 2
246
- if "__biz=" not in url:
247
- gate(3)
248
- data, _ = call("artinfo", {"url": url}, key)
249
- url = clean_url(str((data or {}).get("article_url") or ""))
250
- units = 3
251
- else:
252
- gate(2)
253
- r, bal = read_article(url, key)
254
- logit("article", url, 1, units)
255
- print("阅读 %d 点赞 %d 在看 %d 分享 %d 收藏 %d 赞赏 %d" % (r["read"], r["like"], r["look"], r["share"], r["collect"], r["reward"]))
256
- if r["read"]:
257
- print("互动合计 %d 占阅读 %.1f%%(只算比例 不下判断)" % (r["like"] + r["look"] + r["share"] + r["collect"], 100.0 * (r["like"] + r["look"] + r["share"] + r["collect"]) / r["read"]))
258
- tail(units, bal)
259
-
260
-
261
- def idx_of(it):
262
- """art_url 里的 idx=N:1 是每次推送的头条,2 起是次条。"""
263
- m = re.search(r"idx=(\d)", str(it.get("art_url") or ""))
264
- return int(m.group(1)) if m else None
265
-
266
-
267
- def cmd_benchmark(a, key):
268
- n = max(1, min(a.n, 20))
269
- units = 5 + 2 * n
270
- print("对标 %s:拉最近一页推文(5 积分)再给头 %d 篇各拉一次阅读在看分享(%d 积分),合计约 %d 积分 约 %.2f 元" % (a.wxid, n, 2 * n, units, units / 100))
271
- if not a.yes:
272
- print("确认就加 --yes 再跑一次。什么都没扣。")
273
- return
274
- gate(units)
275
- lst, bal = fetch_posts(a.wxid, key)
276
- logit("benchmark-posts", a.wxid, len(lst), 5)
277
- if not lst:
278
- print("这个号最近一页没有推文,或原始ID不对(5 积分已扣)"); tail(5, bal); return
279
- # 只查每次推送的头条(idx=1 或没有 idx 的):次条不代表这个号的水平,也省积分;顺序保持最新在前
280
- heads = [it for it in lst if (idx_of(it) or 1) == 1]
281
- rows = []
282
- spent = 5
283
- for it in heads[:n]:
284
- url = re.sub(r"\s+", "", str(it.get("art_url") or ""))
285
- try:
286
- u = clean_url(url)
287
- except SystemExit:
288
- continue
289
- r, bal = read_article(u, key)
290
- spent += 2
291
- rows.append({"title": clean(it.get("title"), 60), "time": fmt_time(it.get("pub_time")), "url": u, **r})
292
- logit("benchmark-reads", a.wxid, len(rows), spent - 5)
293
- if not rows:
294
- print("没拉到任何一篇的阅读"); tail(spent, bal); return
295
- reads = [r["read"] for r in rows]
296
- med = statistics.median(reads)
297
- print("%s:最近 %d 篇,阅读中位 %d,最高 %d,爆款倍率 %.1f(最高 ÷ 中位)" % (a.wxid, len(rows), med, max(reads), (max(reads) / med) if med else 0))
298
- print("按爆款分排(阅读 + 3 × 分享):")
299
- for r in sorted(rows, key=lambda x: x["read"] + 3 * x["share"], reverse=True):
300
- ratio = (r["read"] / med) if med else 0
301
- flag = " ← 跑赢本号 %.1f 倍" % ratio if med and ratio >= 2 else ""
302
- print(" 爆款分 %6d 阅读 %6d 在看 %4d 分享 %4d %s %s%s" % (r["read"] + 3 * r["share"], r["read"], r["look"], r["share"], r["time"], r["title"], flag))
303
- print("怎么用:倍率 2 以上的是这个号本身的读者都格外买账的题,看它们的标题公式和角度,不抄标题不搬内容,把你自己的经历、数据、实验揉进去再写。")
304
- out = os.path.join(os.getcwd(), "benchmark-%s-%s.json" % (re.sub(r"[^0-9A-Za-z_-]", "", a.wxid)[:30], datetime.datetime.now().strftime("%Y%m%d-%H%M%S")))
305
- io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps({"wxid": a.wxid, "median_read": med, "rows": rows}, ensure_ascii=False, indent=1))
306
- print("明细已存:" + out)
307
- tail(spent, bal)
308
-
309
-
310
- def load_feed():
311
- """仓库每天自动更新的内容清单。先读本仓库里的 data/hot/latest.json(在仓库里跑时),没有就从 GitHub raw 拉。"""
312
- if os.path.exists(FEED_LOCAL):
313
- try:
314
- return json.load(io.open(FEED_LOCAL, encoding="utf-8")), FEED_LOCAL
315
- except Exception:
316
- pass
317
- req = urllib.request.Request(FEED_URL, headers={"User-Agent": "wechat-topic-hunter/1.0"})
318
- try:
319
- with urllib.request.urlopen(req, timeout=20) as r:
320
- return json.loads(r.read().decode("utf-8", errors="replace")), FEED_URL
321
- except Exception as e:
322
- die("拉不到仓库清单(%s)。本机能上 GitHub 吗;上不了就直接跑 hot_sources.py 自己拉热点源" % type(e).__name__)
323
-
324
-
325
- def feed_rows(feed, groups=None, kws=None, hot_only=False, n=15):
326
- rows = []
327
- if hot_only:
328
- for r in feed.get("hot_now", []):
329
- rows.append(dict(r, group=r.get("group", "")))
330
- else:
331
- for g, lst in feed.get("groups", {}).items():
332
- if groups and g not in groups:
333
- continue
334
- rows.extend(lst[:n])
335
- out = []
336
- for r in rows:
337
- r = dict(r)
338
- r["time"] = r.get("published") or r.get("time") or "" # 合并组的领头条可能没时间,published 是组里最新的
339
- out.append(r)
340
- rows = out
341
- if kws:
342
- rows = [r for r in rows if any(k.lower() in r["title"].lower() for k in kws)]
343
- return rows
344
-
345
-
346
- def cmd_feed(a, key=None):
347
- feed, where = load_feed()
348
- groups = [x.strip() for x in (a.group or "").split(",") if x.strip()] or None
349
- kws = [x.strip() for x in (a.keyword or "").split(",") if x.strip()] or None
350
- rows = feed_rows(feed, groups, kws, a.hot_only, a.n)
351
- print("仓库内容清单 %s(%s):%d 条%s" % (feed.get("date"), "本地" if where == FEED_LOCAL else "GitHub", len(rows), ",只看多平台同聊" if a.hot_only else ""))
352
- cur = None
353
- for r in rows:
354
- if r.get("group") != cur and not a.hot_only:
355
- cur = r.get("group"); print("## %s" % cur)
356
- print("- [%d 个平台] %s | %s | %s | %s" % (r.get("platforms", 1), r["title"], r.get("source", ""), r.get("time") or "--", r.get("url") or "-"))
357
- print("这是需求侧(今天各平台在聊什么)。供给侧用 hot 看公众号上这个题读了多少、爆没爆,两边对上才是题。免费,没花积分。")
358
-
359
-
360
- def cmd_direction(a, key):
361
- words = [w.strip() for w in a.keywords.split(",") if w.strip()]
362
- if not (2 <= len(words) <= 8):
363
- die("--keywords 给 2 到 8 个词 逗号隔开")
364
- gate(len(words))
365
- table = []
366
- bal = None
367
- for w in words:
368
- body = {"keyword": w, "content_type": "article"}
369
- if a.month: body["month"] = a.month
370
- data, bal = call("artlist", body, key)
371
- lst = (data or {}).get("list") or []
372
- reads = sorted((num(it.get("read_num")) for it in lst), reverse=True)
373
- shares = [num(it.get("share_num")) for it in lst]
374
- top = lst[0] if lst else {}
375
- table.append({"keyword": w, "total": (data or {}).get("total"), "n": len(reads), "max_read": reads[0] if reads else 0,
376
- "median_read": int(statistics.median(reads)) if reads else 0, "over_10w": sum(1 for r in reads if r >= 100000),
377
- "max_share": max(shares) if shares else 0, "top_title": clean(top.get("title"), 40), "top_url": re.sub(r"\s+", "", str(top.get("art_url") or ""))})
378
- logit("direction", ",".join(words), len(table), len(words))
379
- print("方向比较(%s,每词取离线库阅读最高的一页):" % (a.month or "当月"))
380
- print("%-12s %7s %8s %8s %6s %7s %s" % ("方向词", "命中篇", "最高阅读", "中位阅读", "10万+", "最高分享", "最高那篇"))
381
- for r in sorted(table, key=lambda x: (x["over_10w"], x["median_read"]), reverse=True):
382
- print("%-12s %7s %8d %8d %6d %7d %s" % (r["keyword"], r["total"] if r["total"] is not None else "-", r["max_read"], r["median_read"], r["over_10w"], r["max_share"], r["top_title"]))
383
- print("怎么看:命中篇多说明有人在写,10万+ 多说明读者在;中位高说明普通一篇也有人看。你的号能不能挤进去,看你有没有独家。数字只标注,方向你定。")
384
- out = os.path.join(os.getcwd(), "direction-%s.json" % datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
385
- io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(table, ensure_ascii=False, indent=1))
386
- print("明细已存:" + out)
387
- tail(len(words), bal)
388
-
389
-
390
- def plan_dates(start, per_week, n):
391
- """从 start 起每周 per_week 篇的日期表:第 i 篇在 start 后 round(i*7/per_week) 天,平均下来每周正好 per_week 篇(2 篇/周=隔 4 天、3 天、4 天…)。"""
392
- return [start + datetime.timedelta(days=int(i * 7 / per_week + 0.5)) for i in range(n)]
393
-
394
-
395
- def cmd_calendar(a, key):
396
- # 参数先核完再扣积分
397
- kws = [x.strip() for x in a.keyword.split(",") if x.strip()]
398
- if not kws:
399
- die("--keyword 至少给一个词")
400
- if not (1 <= a.per_week <= 7):
401
- die("--per-week 1 到 7")
402
- try:
403
- start = datetime.date.fromisoformat(a.start) if a.start else datetime.date.today() + datetime.timedelta(days=1)
404
- except ValueError:
405
- die("--start 要写成 YYYY-MM-DD,例如 2026-10-14")
406
- feed, where = load_feed()
407
- rows = feed_rows(feed, None, kws, False, 50)
408
- if len(rows) < a.n:
409
- rows += [r for r in feed.get("hot_now", []) if r not in rows]
410
- rows = rows[: max(a.n, 1)]
411
- body = {"keyword": kws[0], "content_type": "article"}
412
- if a.month: body["month"] = a.month
413
- gate(1)
414
- data, bal = call("artlist", body, key)
415
- lst = (data or {}).get("list") or []
416
- logit("calendar", kws[0], len(lst), 1)
417
- supply = {"total": (data or {}).get("total"), "max_read": max([num(it.get("read_num")) for it in lst] or [0]),
418
- "titles": [clean(it.get("title"), 40) for it in lst[:5]]}
419
- plan = []
420
- for i, (r, d) in enumerate(zip(rows, plan_dates(start, a.per_week, len(rows))), 1):
421
- plan.append({"no": i, "date": d.isoformat(), "title": r["title"], "platforms": r.get("platforms", 1), "source": r.get("source", ""), "url": r.get("url", ""), "group": r.get("group", "")})
422
- print("内容清单「%s」%d 条,从 %s 起每周 %d 篇(需求侧来自仓库清单 %s;供给侧 公众号上「%s」%s 命中 %s 篇 最高阅读 %d)" % (
423
- kws[0], len(plan), start.isoformat(), a.per_week, feed.get("date"), kws[0], a.month or "当月", supply["total"], supply["max_read"]))
424
- print("| 序 | 计划日期 | 题 | 平台数 | 来源 | 链接 |")
425
- print("|---|---|---|---|---|---|")
426
- for p in plan:
427
- print("| %d | %s | %s | %d | %s | %s |" % (p["no"], p["date"], p["title"].replace("|", "|"), p["platforms"], p["source"], p["url"] or "-"))
428
- print("公众号上读得最多的 5 篇(看角度,不抄):" + ";".join(supply["titles"]))
429
- print("每条写之前再用 hot --keyword 题里的核心词 看一次这个题爆没爆(1 积分);独家栏自己填,没独家的题不建议写。")
430
- out = os.path.join(os.getcwd(), "calendar-%s-%s.json" % (re.sub(r"[^0-9A-Za-z一-鿿_-]", "", kws[0])[:20], datetime.datetime.now().strftime("%Y%m%d-%H%M%S")))
431
- io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps({"keyword": kws, "start": start.isoformat(), "per_week": a.per_week, "supply": supply, "plan": plan}, ensure_ascii=False, indent=1))
432
- print("清单已存:" + out)
433
- tail(1, bal)
434
-
435
-
436
- def main():
437
- ap = argparse.ArgumentParser(description="公众号选题对标(wxrank)")
438
- sub = ap.add_subparsers(dest="cmd")
439
- sub.add_parser("balance")
440
- p = sub.add_parser("hot"); p.add_argument("--keyword", required=True); p.add_argument("--date"); p.add_argument("--month"); p.add_argument("--min-read", type=int, default=0); p.add_argument("--type"); p.add_argument("--n", type=int, default=20)
441
- p = sub.add_parser("search"); p.add_argument("--keyword", required=True); p.add_argument("--sort", choices=["新", "热"]); p.add_argument("--page", type=int, default=1)
442
- p = sub.add_parser("accounts"); p.add_argument("--keyword", required=True); p.add_argument("--page", type=int, default=1)
443
- p = sub.add_parser("posts"); p.add_argument("--wxid", required=True)
444
- p = sub.add_parser("benchmark"); p.add_argument("--wxid", required=True); p.add_argument("--n", type=int, default=10); p.add_argument("--yes", action="store_true")
445
- p = sub.add_parser("article"); p.add_argument("--url", required=True)
446
- p = sub.add_parser("feed"); p.add_argument("--group"); p.add_argument("--keyword"); p.add_argument("--n", type=int, default=15); p.add_argument("--hot-only", action="store_true")
447
- p = sub.add_parser("direction"); p.add_argument("--keywords", required=True); p.add_argument("--month")
448
- p = sub.add_parser("calendar"); p.add_argument("--keyword", required=True); p.add_argument("--n", type=int, default=10); p.add_argument("--per-week", type=int, default=2); p.add_argument("--start"); p.add_argument("--month")
449
- a = ap.parse_args()
450
- if not a.cmd:
451
- print(__doc__); return
452
- if a.cmd in ("hot",) and a.date and not re.match(r"^\d{8}$", a.date):
453
- die("--date 格式 yyyymmdd")
454
- if a.cmd in ("hot", "direction", "calendar") and getattr(a, "month", None) and not re.match(r"^\d{6}$", a.month):
455
- die("--month 格式 yyyymm")
456
- if a.cmd == "feed":
457
- cmd_feed(a); return
458
- if a.cmd in ("posts", "benchmark") and not re.match(r"^[0-9A-Za-z_-]{1,64}$", a.wxid):
459
- die("--wxid 只认字母数字下划线减号(建议 gh_ 开头的原始ID)")
460
- key = load_key()
461
- {"balance": cmd_balance, "hot": cmd_hot, "search": cmd_search, "accounts": cmd_accounts, "posts": cmd_posts, "benchmark": cmd_benchmark, "article": cmd_article,
462
- "direction": cmd_direction, "calendar": cmd_calendar}[a.cmd](a, key)
463
-
464
-
465
- if __name__ == "__main__":
466
- main()
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """公众号选题对标(wxrank 微小榜数据)。你自己的 wxrank key,你自己充值,每次调用都先告诉你要花多少积分。
4
+
5
+ 用法:
6
+ python wxrank_topics.py balance 余额(免费)
7
+ python wxrank_topics.py hot --keyword 出海 [--date 20261001 | --month 202610] [--min-read 1000] [--type 科技] [--n 20]
8
+ 离线库里这个词阅读最高的文章(1 积分)
9
+ python wxrank_topics.py search --keyword 出海 [--sort 新|热] [--page 1] 搜一搜文章列表(10 积分)
10
+ python wxrank_topics.py accounts --keyword 出海 找公众号,拿原始ID 和 biz(10 积分)
11
+ python wxrank_topics.py posts --wxid gh_xxx 某个号最近一页推文(5 积分)
12
+ python wxrank_topics.py benchmark --wxid gh_xxx [--n 10] [--yes] 对标一个号:最近 N 篇各拉一次阅读在看分享,算阅读中位、爆款倍率、爆款分(5 + 2N 积分,先报价,加 --yes 才扣)
13
+ python wxrank_topics.py article --url "https://mp.weixin.qq.com/s?__biz=..." 一篇文章的阅读 点赞 在看 分享 收藏 赞赏(2 积分,短链多 1 积分)
14
+ python wxrank_topics.py feed [--group AI,热榜] [--keyword 副业,AI] [--n 15] [--hot-only] 读仓库每天自动更新的内容清单(免费 不花积分)
15
+ python wxrank_topics.py direction --keywords 出海,副业,AI写作 [--month 202610] 方向比较:每个词看一次榜 出一张表(每词 1 积分)
16
+ python wxrank_topics.py calendar --keyword 出海 [--n 10] [--per-week 2] [--start 2026-10-14] [--month 202610] 内容清单:清单里挑题 对照榜 排日期(1 积分)
17
+
18
+ 凭据:~/.wxrank.env 一行 KEY=你的key(或环境变量 WXRANK_KEY)。注册和充值 https://data.wxrank.com ,100 积分 = 1 元。
19
+ 纪律:只读;每天上限 WXRANK_DAILY_CAP 积分(默认 300);用量记 ~/.wxrank-usage.log;输出不含 key;只用标准库。
20
+ 口径:wxrank 的数是实时抓的公开数,跟后台会差;爆款倍率 = 单篇阅读 ÷ 该号阅读中位;爆款分 = 阅读 + 3 × 分享(分享比阅读值钱)。只标注数字,选题是你定。
21
+ """
22
+ import argparse, datetime, io, json, os, re, statistics, sys, time, urllib.request, urllib.error
23
+
24
+ try:
25
+ sys.stdout.reconfigure(encoding="utf-8"); sys.stderr.reconfigure(encoding="utf-8")
26
+ except Exception:
27
+ pass
28
+
29
+ BASE = "https://data.wxrank.com/weixin/"
30
+ FEED_URL = os.environ.get("WECHAT_FEED_URL", "https://raw.githubusercontent.com/adsorgcn/WorkBuddy/main/data/hot/latest.json")
31
+ FEED_LOCAL = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))), "data", "hot", "latest.json")
32
+ ENV = os.path.join(os.path.expanduser("~"), ".wxrank.env")
33
+ LOG = os.path.join(os.path.expanduser("~"), ".wxrank-usage.log")
34
+ DAILY_CAP = int(os.environ.get("WXRANK_DAILY_CAP", "300"))
35
+ ERR = {1000: "积分不足 或 key 不对(key 错时 wxrank 也回 1000)先核 ~/.wxrank.env 再去 data.wxrank.com 充值",
36
+ 1001: "参数为空 或不是公众号文章链接", 1002: "请求失败或文章验证失败 可以重试一次", 1003: "获取失败 可以重试一次",
37
+ 1004: "wxrank 服务异常 稍后再试", 1008: "请求太频繁 歇一会再查", 9999: "超过 QPS 上限 歇一秒再查"}
38
+ TYPES = "时事 文化 健康 职场 学术 美食 民生 科技 情感 楼市 汽车 幽默 政务 财富 旅行 企业 时尚 美体 教育 体娱 百科 乐活 创业 文摘".split()
39
+
40
+
41
+ def die(msg, code=1):
42
+ print("错误:" + msg); sys.exit(code)
43
+
44
+
45
+ def load_key():
46
+ k = os.environ.get("WXRANK_KEY", "").strip()
47
+ if not k and os.path.exists(ENV):
48
+ for line in io.open(ENV, encoding="utf-8"):
49
+ line = line.strip()
50
+ if "=" in line and not line.startswith("#"):
51
+ a, b = line.split("=", 1)
52
+ if a.strip().upper() in ("KEY", "WXRANK_KEY"):
53
+ k = b.strip().strip('"').strip("'")
54
+ if not k:
55
+ die("没找到 wxrank key。注册 https://data.wxrank.com 拿 key,写进 %s 一行 KEY=你的key" % ENV)
56
+ if re.search(r"[\s\"'\\]", k):
57
+ die("key 里有空白或引号,不合法")
58
+ return k
59
+
60
+
61
+ def today():
62
+ return datetime.date.today().isoformat()
63
+
64
+
65
+ def spent_today():
66
+ if not os.path.exists(LOG):
67
+ return 0
68
+ s = 0
69
+ for line in io.open(LOG, encoding="utf-8"):
70
+ parts = line.split()
71
+ if parts and parts[0] == today():
72
+ for p in parts:
73
+ if p.startswith("units="):
74
+ try: s += int(p[6:])
75
+ except ValueError: pass
76
+ return s
77
+
78
+
79
+ def logit(cmd, arg, rows, units):
80
+ arg = re.sub(r"\s+", "_", arg)[:80] or "-"
81
+ io.open(LOG, "a", encoding="utf-8").write("%s %s %s %s lines=%d units=%d\n" % (today(), datetime.datetime.now().strftime("%H:%M:%S"), cmd, arg, rows, units))
82
+
83
+
84
+ def gate(units):
85
+ s = spent_today()
86
+ if s + units > DAILY_CAP:
87
+ die("今天的 wxrank 额度到上限了(已用 %d 积分 上限 %d)明天再查,或者设环境变量 WXRANK_DAILY_CAP 调高" % (s, DAILY_CAP), 4)
88
+
89
+
90
+ _last_call = [0.0]
91
+
92
+
93
+ def call(endpoint, body, key):
94
+ # QPS:搜索类每秒 3 个,阅读每秒 10 个;统一隔 0.4 秒
95
+ wait = 0.4 - (time.time() - _last_call[0])
96
+ if wait > 0:
97
+ time.sleep(wait)
98
+ _last_call[0] = time.time()
99
+ body = dict(body); body["key"] = key
100
+ req = urllib.request.Request(BASE + endpoint, data=json.dumps(body, ensure_ascii=False).encode("utf-8"), method="POST",
101
+ headers={"Content-Type": "application/json", "User-Agent": "wechat-topic-hunter/1.0"})
102
+ try:
103
+ with urllib.request.urlopen(req, timeout=20) as r:
104
+ raw = r.read().decode("utf-8", errors="replace")
105
+ except urllib.error.HTTPError as e:
106
+ raw = e.read().decode("utf-8", errors="replace")
107
+ except Exception as e:
108
+ die("连不上 wxrank(%s)稍后再试" % type(e).__name__)
109
+ raw = raw.replace(key, "[key]")
110
+ try:
111
+ j = json.loads(raw)
112
+ except Exception:
113
+ die("wxrank 返回的不是 JSON:" + re.sub(r"\s+", " ", raw)[:120])
114
+ code = j.get("code")
115
+ if code != 0:
116
+ die("wxrank 报错 code %s:%s" % (code, ERR.get(code, "未知错误码")))
117
+ m = re.search(r"(\d+)", str(j.get("msg", "")))
118
+ return j.get("data"), (int(m.group(1)) if m else None)
119
+
120
+
121
+ def clean(s, n=0):
122
+ s = re.sub(r"<[^>]*>", "", str(s if s is not None else ""))
123
+ s = re.sub(r"\s+", " ", s).strip()
124
+ return s[:n] if n else s
125
+
126
+
127
+ def num(v):
128
+ try: return int(float(v))
129
+ except Exception: return 0
130
+
131
+
132
+ def fmt_time(v):
133
+ v = str(v or "")
134
+ if v.isdigit() and len(v) >= 10:
135
+ try: return datetime.datetime.fromtimestamp(int(v[:10])).strftime("%Y-%m-%d %H:%M")
136
+ except Exception: return v
137
+ return v[:16]
138
+
139
+
140
+ def clean_url(u):
141
+ u = u.strip().replace("&amp;", "&")
142
+ if re.search(r"[\s\"'`$\\@]", u):
143
+ die("链接里有空白、引号或特殊字符")
144
+ u = u.split("#")[0]
145
+ u = re.sub(r"^http://", "https://", u)
146
+ if not u.startswith("https://mp.weixin.qq.com/"):
147
+ die("只认 mp.weixin.qq.com 的文章链接")
148
+ return u
149
+
150
+
151
+ def tail(units, bal):
152
+ print("本次 %d 积分|余额 %s|今天已用 %d 积分 上限 %d" % (units, ("%d 积分 约 %.2f 元" % (bal, bal / 100)) if bal is not None else "未知", spent_today(), DAILY_CAP))
153
+
154
+
155
+ # ---------- commands ----------
156
+ def cmd_balance(a, key):
157
+ _, bal = call("score", {}, key)
158
+ logit("balance", "-", 1, 0)
159
+ print("wxrank 余额 %s 积分 约 %.2f 元|今天已用 %d 积分 上限 %d" % (bal, (bal or 0) / 100, spent_today(), DAILY_CAP))
160
+ if bal == 0:
161
+ print("余额为 0 也可能是 key 不对,先核 %s" % ENV)
162
+
163
+
164
+ def cmd_hot(a, key):
165
+ body = {"keyword": a.keyword, "content_type": "article"}
166
+ if a.date: body["date"] = a.date
167
+ elif a.month: body["month"] = a.month
168
+ if a.min_read: body["min_read_num"] = a.min_read
169
+ if a.type:
170
+ if a.type not in TYPES: die("分类只认:" + " ".join(TYPES))
171
+ body["wx_type"] = a.type
172
+ gate(1)
173
+ data, bal = call("artlist", body, key)
174
+ lst = (data or {}).get("list") or []
175
+ total = (data or {}).get("total")
176
+ logit("hot", a.keyword, len(lst), 1)
177
+ print("离线库「%s」%s:命中 %s 篇,取阅读最高的 %d 篇,按爆款分(阅读 + 3 × 分享)重排" % (a.keyword, a.date or a.month or "当月", total if total is not None else "?", min(len(lst), a.n)))
178
+ rows = []
179
+ for it in lst[: a.n]:
180
+ rows.append({"read": num(it.get("read_num")), "look": num(it.get("look_num")), "share": num(it.get("share_num")), "words": num(it.get("word_num")),
181
+ "type": clean(it.get("wx_type")), "biz": clean(it.get("wx_biz")), "time": fmt_time(it.get("pub_time")),
182
+ "title": clean(it.get("title"), 60), "url": re.sub(r"\s+", "", str(it.get("art_url") or "")), "copyright": clean(it.get("copyright"))})
183
+ for i, r in enumerate(sorted(rows, key=lambda x: x["read"] + 3 * x["share"], reverse=True), 1):
184
+ print("%2d. 爆款分 %6d 阅读 %6d 在看 %4d 分享 %4d %4d 字 %s %s %s" % (i, r["read"] + 3 * r["share"], r["read"], r["look"], r["share"], r["words"], r["type"] or "-", r["time"], r["title"]))
185
+ print(" biz %s %s" % (r["biz"], r["url"]))
186
+ if not lst:
187
+ print("没命中。换个更宽的词,或者去掉日期用当月(空列表也扣 1 积分)")
188
+ else:
189
+ out = os.path.join(os.getcwd(), "hot-%s-%s.json" % (re.sub(r"[^0-9A-Za-z一-鿿_-]", "", a.keyword)[:20], datetime.datetime.now().strftime("%Y%m%d-%H%M%S")))
190
+ io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(rows, ensure_ascii=False, indent=1))
191
+ print("明细已存:" + out + "(biz 可以拿去 accounts 反查原始ID,再用 benchmark 对标)")
192
+ tail(1, bal)
193
+
194
+
195
+ def cmd_search(a, key):
196
+ st = {"新": 2, "热": 4}.get(a.sort, 0)
197
+ gate(10)
198
+ data, bal = call("getso", {"keyword": a.keyword, "sort_type": st, "page": a.page}, key)
199
+ lst = data if isinstance(data, list) else []
200
+ logit("search", a.keyword, len(lst), 10)
201
+ print("搜一搜「%s」排序 %s 第 %d 页:%d 篇" % (a.keyword, a.sort or "不限", a.page, len(lst)))
202
+ for i, it in enumerate(lst, 1):
203
+ print("%2d. %s %s %s" % (i, fmt_time(it.get("pub_time")), clean(it.get("wx_name")), clean(it.get("title"), 60)))
204
+ print(" %s" % re.sub(r"\s+", "", str(it.get("art_url") or "")))
205
+ tail(10, bal)
206
+
207
+
208
+ def cmd_accounts(a, key):
209
+ gate(10)
210
+ data, bal = call("getsu", {"keyword": a.keyword, "page": a.page}, key)
211
+ lst = data if isinstance(data, list) else []
212
+ logit("accounts", a.keyword, len(lst), 10)
213
+ print("搜公众号「%s」第 %d 页:%d 个" % (a.keyword, a.page, len(lst)))
214
+ for i, it in enumerate(lst, 1):
215
+ print("%2d. %s 原始ID %s 微信号 %s 简介 %s" % (i, clean(it.get("wx_name")), clean(it.get("wx_user")), clean(it.get("wx_id")), clean(it.get("signature"), 40)))
216
+ tail(10, bal)
217
+
218
+
219
+ def fetch_posts(wxid, key):
220
+ data, bal = call("getps", {"wxid": wxid}, key)
221
+ lst = (data or {}).get("list") or []
222
+ return lst, bal
223
+
224
+
225
+ def cmd_posts(a, key):
226
+ gate(5)
227
+ lst, bal = fetch_posts(a.wxid, key)
228
+ logit("posts", a.wxid, len(lst), 5)
229
+ print("%s 最近一页推文 %d 篇(不翻页)" % (a.wxid, len(lst)))
230
+ for i, it in enumerate(lst, 1):
231
+ print("%2d. %s idx%s %s" % (i, fmt_time(it.get("pub_time")), re.search(r"idx=(\d)", str(it.get("art_url") or "")).group(1) if re.search(r"idx=(\d)", str(it.get("art_url") or "")) else "?", clean(it.get("title"), 60)))
232
+ print(" %s" % re.sub(r"\s+", "", str(it.get("art_url") or "")))
233
+ tail(5, bal)
234
+
235
+
236
+ def read_article(url, key):
237
+ data, bal = call("getrk", {"url": url}, key)
238
+ d = data or {}
239
+ return {"read": num(d.get("read_num")), "like": num(d.get("like_num")), "look": num(d.get("look_num")),
240
+ "share": num(d.get("share_num")), "collect": num(d.get("collect_num")), "reward": num(d.get("reward_count"))}, bal
241
+
242
+
243
+ def cmd_article(a, key):
244
+ url = clean_url(a.url)
245
+ units = 2
246
+ if "__biz=" not in url:
247
+ gate(3)
248
+ data, _ = call("artinfo", {"url": url}, key)
249
+ url = clean_url(str((data or {}).get("article_url") or ""))
250
+ units = 3
251
+ else:
252
+ gate(2)
253
+ r, bal = read_article(url, key)
254
+ logit("article", url, 1, units)
255
+ print("阅读 %d 点赞 %d 在看 %d 分享 %d 收藏 %d 赞赏 %d" % (r["read"], r["like"], r["look"], r["share"], r["collect"], r["reward"]))
256
+ if r["read"]:
257
+ print("互动合计 %d 占阅读 %.1f%%(只算比例 不下判断)" % (r["like"] + r["look"] + r["share"] + r["collect"], 100.0 * (r["like"] + r["look"] + r["share"] + r["collect"]) / r["read"]))
258
+ tail(units, bal)
259
+
260
+
261
+ def idx_of(it):
262
+ """art_url 里的 idx=N:1 是每次推送的头条,2 起是次条。"""
263
+ m = re.search(r"idx=(\d)", str(it.get("art_url") or ""))
264
+ return int(m.group(1)) if m else None
265
+
266
+
267
+ def cmd_benchmark(a, key):
268
+ n = max(1, min(a.n, 20))
269
+ units = 5 + 2 * n
270
+ print("对标 %s:拉最近一页推文(5 积分)再给头 %d 篇各拉一次阅读在看分享(%d 积分),合计约 %d 积分 约 %.2f 元" % (a.wxid, n, 2 * n, units, units / 100))
271
+ if not a.yes:
272
+ print("确认就加 --yes 再跑一次。什么都没扣。")
273
+ return
274
+ gate(units)
275
+ lst, bal = fetch_posts(a.wxid, key)
276
+ logit("benchmark-posts", a.wxid, len(lst), 5)
277
+ if not lst:
278
+ print("这个号最近一页没有推文,或原始ID不对(5 积分已扣)"); tail(5, bal); return
279
+ # 只查每次推送的头条(idx=1 或没有 idx 的):次条不代表这个号的水平,也省积分;顺序保持最新在前
280
+ heads = [it for it in lst if (idx_of(it) or 1) == 1]
281
+ rows = []
282
+ spent = 5
283
+ for it in heads[:n]:
284
+ url = re.sub(r"\s+", "", str(it.get("art_url") or ""))
285
+ try:
286
+ u = clean_url(url)
287
+ except SystemExit:
288
+ continue
289
+ r, bal = read_article(u, key)
290
+ spent += 2
291
+ rows.append({"title": clean(it.get("title"), 60), "time": fmt_time(it.get("pub_time")), "url": u, **r})
292
+ logit("benchmark-reads", a.wxid, len(rows), spent - 5)
293
+ if not rows:
294
+ print("没拉到任何一篇的阅读"); tail(spent, bal); return
295
+ reads = [r["read"] for r in rows]
296
+ med = statistics.median(reads)
297
+ print("%s:最近 %d 篇,阅读中位 %d,最高 %d,爆款倍率 %.1f(最高 ÷ 中位)" % (a.wxid, len(rows), med, max(reads), (max(reads) / med) if med else 0))
298
+ print("按爆款分排(阅读 + 3 × 分享):")
299
+ for r in sorted(rows, key=lambda x: x["read"] + 3 * x["share"], reverse=True):
300
+ ratio = (r["read"] / med) if med else 0
301
+ flag = " ← 跑赢本号 %.1f 倍" % ratio if med and ratio >= 2 else ""
302
+ print(" 爆款分 %6d 阅读 %6d 在看 %4d 分享 %4d %s %s%s" % (r["read"] + 3 * r["share"], r["read"], r["look"], r["share"], r["time"], r["title"], flag))
303
+ print("怎么用:倍率 2 以上的是这个号本身的读者都格外买账的题,看它们的标题公式和角度,不抄标题不搬内容,把你自己的经历、数据、实验揉进去再写。")
304
+ out = os.path.join(os.getcwd(), "benchmark-%s-%s.json" % (re.sub(r"[^0-9A-Za-z_-]", "", a.wxid)[:30], datetime.datetime.now().strftime("%Y%m%d-%H%M%S")))
305
+ io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps({"wxid": a.wxid, "median_read": med, "rows": rows}, ensure_ascii=False, indent=1))
306
+ print("明细已存:" + out)
307
+ tail(spent, bal)
308
+
309
+
310
+ def load_feed():
311
+ """仓库每天自动更新的内容清单。先读本仓库里的 data/hot/latest.json(在仓库里跑时),没有就从 GitHub raw 拉。"""
312
+ if os.path.exists(FEED_LOCAL):
313
+ try:
314
+ return json.load(io.open(FEED_LOCAL, encoding="utf-8")), FEED_LOCAL
315
+ except Exception:
316
+ pass
317
+ req = urllib.request.Request(FEED_URL, headers={"User-Agent": "wechat-topic-hunter/1.0"})
318
+ try:
319
+ with urllib.request.urlopen(req, timeout=20) as r:
320
+ return json.loads(r.read().decode("utf-8", errors="replace")), FEED_URL
321
+ except Exception as e:
322
+ die("拉不到仓库清单(%s)。本机能上 GitHub 吗;上不了就直接跑 hot_sources.py 自己拉热点源" % type(e).__name__)
323
+
324
+
325
+ def feed_rows(feed, groups=None, kws=None, hot_only=False, n=15):
326
+ rows = []
327
+ if hot_only:
328
+ for r in feed.get("hot_now", []):
329
+ rows.append(dict(r, group=r.get("group", "")))
330
+ else:
331
+ for g, lst in feed.get("groups", {}).items():
332
+ if groups and g not in groups:
333
+ continue
334
+ rows.extend(lst[:n])
335
+ out = []
336
+ for r in rows:
337
+ r = dict(r)
338
+ r["time"] = r.get("published") or r.get("time") or "" # 合并组的领头条可能没时间,published 是组里最新的
339
+ out.append(r)
340
+ rows = out
341
+ if kws:
342
+ rows = [r for r in rows if any(k.lower() in r["title"].lower() for k in kws)]
343
+ return rows
344
+
345
+
346
+ def cmd_feed(a, key=None):
347
+ feed, where = load_feed()
348
+ groups = [x.strip() for x in (a.group or "").split(",") if x.strip()] or None
349
+ kws = [x.strip() for x in (a.keyword or "").split(",") if x.strip()] or None
350
+ rows = feed_rows(feed, groups, kws, a.hot_only, a.n)
351
+ print("仓库内容清单 %s(%s):%d 条%s" % (feed.get("date"), "本地" if where == FEED_LOCAL else "GitHub", len(rows), ",只看多平台同聊" if a.hot_only else ""))
352
+ cur = None
353
+ for r in rows:
354
+ if r.get("group") != cur and not a.hot_only:
355
+ cur = r.get("group"); print("## %s" % cur)
356
+ print("- [%d 个平台] %s | %s | %s | %s" % (r.get("platforms", 1), r["title"], r.get("source", ""), r.get("time") or "--", r.get("url") or "-"))
357
+ print("这是需求侧(今天各平台在聊什么)。供给侧用 hot 看公众号上这个题读了多少、爆没爆,两边对上才是题。免费,没花积分。")
358
+
359
+
360
+ def cmd_direction(a, key):
361
+ words = [w.strip() for w in a.keywords.split(",") if w.strip()]
362
+ if not (2 <= len(words) <= 8):
363
+ die("--keywords 给 2 到 8 个词 逗号隔开")
364
+ gate(len(words))
365
+ table = []
366
+ bal = None
367
+ for w in words:
368
+ body = {"keyword": w, "content_type": "article"}
369
+ if a.month: body["month"] = a.month
370
+ data, bal = call("artlist", body, key)
371
+ lst = (data or {}).get("list") or []
372
+ reads = sorted((num(it.get("read_num")) for it in lst), reverse=True)
373
+ shares = [num(it.get("share_num")) for it in lst]
374
+ top = lst[0] if lst else {}
375
+ table.append({"keyword": w, "total": (data or {}).get("total"), "n": len(reads), "max_read": reads[0] if reads else 0,
376
+ "median_read": int(statistics.median(reads)) if reads else 0, "over_10w": sum(1 for r in reads if r >= 100000),
377
+ "max_share": max(shares) if shares else 0, "top_title": clean(top.get("title"), 40), "top_url": re.sub(r"\s+", "", str(top.get("art_url") or ""))})
378
+ logit("direction", ",".join(words), len(table), len(words))
379
+ print("方向比较(%s,每词取离线库阅读最高的一页):" % (a.month or "当月"))
380
+ print("%-12s %7s %8s %8s %6s %7s %s" % ("方向词", "命中篇", "最高阅读", "中位阅读", "10万+", "最高分享", "最高那篇"))
381
+ for r in sorted(table, key=lambda x: (x["over_10w"], x["median_read"]), reverse=True):
382
+ print("%-12s %7s %8d %8d %6d %7d %s" % (r["keyword"], r["total"] if r["total"] is not None else "-", r["max_read"], r["median_read"], r["over_10w"], r["max_share"], r["top_title"]))
383
+ print("怎么看:命中篇多说明有人在写,10万+ 多说明读者在;中位高说明普通一篇也有人看。你的号能不能挤进去,看你有没有独家。数字只标注,方向你定。")
384
+ out = os.path.join(os.getcwd(), "direction-%s.json" % datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
385
+ io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(table, ensure_ascii=False, indent=1))
386
+ print("明细已存:" + out)
387
+ tail(len(words), bal)
388
+
389
+
390
+ def plan_dates(start, per_week, n):
391
+ """从 start 起每周 per_week 篇的日期表:第 i 篇在 start 后 round(i*7/per_week) 天,平均下来每周正好 per_week 篇(2 篇/周=隔 4 天、3 天、4 天…)。"""
392
+ return [start + datetime.timedelta(days=int(i * 7 / per_week + 0.5)) for i in range(n)]
393
+
394
+
395
+ def cmd_calendar(a, key):
396
+ # 参数先核完再扣积分
397
+ kws = [x.strip() for x in a.keyword.split(",") if x.strip()]
398
+ if not kws:
399
+ die("--keyword 至少给一个词")
400
+ if not (1 <= a.per_week <= 7):
401
+ die("--per-week 1 到 7")
402
+ try:
403
+ start = datetime.date.fromisoformat(a.start) if a.start else datetime.date.today() + datetime.timedelta(days=1)
404
+ except ValueError:
405
+ die("--start 要写成 YYYY-MM-DD,例如 2026-10-14")
406
+ feed, where = load_feed()
407
+ rows = feed_rows(feed, None, kws, False, 50)
408
+ if len(rows) < a.n:
409
+ rows += [r for r in feed.get("hot_now", []) if r not in rows]
410
+ rows = rows[: max(a.n, 1)]
411
+ body = {"keyword": kws[0], "content_type": "article"}
412
+ if a.month: body["month"] = a.month
413
+ gate(1)
414
+ data, bal = call("artlist", body, key)
415
+ lst = (data or {}).get("list") or []
416
+ logit("calendar", kws[0], len(lst), 1)
417
+ supply = {"total": (data or {}).get("total"), "max_read": max([num(it.get("read_num")) for it in lst] or [0]),
418
+ "titles": [clean(it.get("title"), 40) for it in lst[:5]]}
419
+ plan = []
420
+ for i, (r, d) in enumerate(zip(rows, plan_dates(start, a.per_week, len(rows))), 1):
421
+ plan.append({"no": i, "date": d.isoformat(), "title": r["title"], "platforms": r.get("platforms", 1), "source": r.get("source", ""), "url": r.get("url", ""), "group": r.get("group", "")})
422
+ print("内容清单「%s」%d 条,从 %s 起每周 %d 篇(需求侧来自仓库清单 %s;供给侧 公众号上「%s」%s 命中 %s 篇 最高阅读 %d)" % (
423
+ kws[0], len(plan), start.isoformat(), a.per_week, feed.get("date"), kws[0], a.month or "当月", supply["total"], supply["max_read"]))
424
+ print("| 序 | 计划日期 | 题 | 平台数 | 来源 | 链接 |")
425
+ print("|---|---|---|---|---|---|")
426
+ for p in plan:
427
+ print("| %d | %s | %s | %d | %s | %s |" % (p["no"], p["date"], p["title"].replace("|", "|"), p["platforms"], p["source"], p["url"] or "-"))
428
+ print("公众号上读得最多的 5 篇(看角度,不抄):" + ";".join(supply["titles"]))
429
+ print("每条写之前再用 hot --keyword 题里的核心词 看一次这个题爆没爆(1 积分);独家栏自己填,没独家的题不建议写。")
430
+ out = os.path.join(os.getcwd(), "calendar-%s-%s.json" % (re.sub(r"[^0-9A-Za-z一-鿿_-]", "", kws[0])[:20], datetime.datetime.now().strftime("%Y%m%d-%H%M%S")))
431
+ io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps({"keyword": kws, "start": start.isoformat(), "per_week": a.per_week, "supply": supply, "plan": plan}, ensure_ascii=False, indent=1))
432
+ print("清单已存:" + out)
433
+ tail(1, bal)
434
+
435
+
436
+ def main():
437
+ ap = argparse.ArgumentParser(description="公众号选题对标(wxrank)")
438
+ sub = ap.add_subparsers(dest="cmd")
439
+ sub.add_parser("balance")
440
+ p = sub.add_parser("hot"); p.add_argument("--keyword", required=True); p.add_argument("--date"); p.add_argument("--month"); p.add_argument("--min-read", type=int, default=0); p.add_argument("--type"); p.add_argument("--n", type=int, default=20)
441
+ p = sub.add_parser("search"); p.add_argument("--keyword", required=True); p.add_argument("--sort", choices=["新", "热"]); p.add_argument("--page", type=int, default=1)
442
+ p = sub.add_parser("accounts"); p.add_argument("--keyword", required=True); p.add_argument("--page", type=int, default=1)
443
+ p = sub.add_parser("posts"); p.add_argument("--wxid", required=True)
444
+ p = sub.add_parser("benchmark"); p.add_argument("--wxid", required=True); p.add_argument("--n", type=int, default=10); p.add_argument("--yes", action="store_true")
445
+ p = sub.add_parser("article"); p.add_argument("--url", required=True)
446
+ p = sub.add_parser("feed"); p.add_argument("--group"); p.add_argument("--keyword"); p.add_argument("--n", type=int, default=15); p.add_argument("--hot-only", action="store_true")
447
+ p = sub.add_parser("direction"); p.add_argument("--keywords", required=True); p.add_argument("--month")
448
+ p = sub.add_parser("calendar"); p.add_argument("--keyword", required=True); p.add_argument("--n", type=int, default=10); p.add_argument("--per-week", type=int, default=2); p.add_argument("--start"); p.add_argument("--month")
449
+ a = ap.parse_args()
450
+ if not a.cmd:
451
+ print(__doc__); return
452
+ if a.cmd in ("hot",) and a.date and not re.match(r"^\d{8}$", a.date):
453
+ die("--date 格式 yyyymmdd")
454
+ if a.cmd in ("hot", "direction", "calendar") and getattr(a, "month", None) and not re.match(r"^\d{6}$", a.month):
455
+ die("--month 格式 yyyymm")
456
+ if a.cmd == "feed":
457
+ cmd_feed(a); return
458
+ if a.cmd in ("posts", "benchmark") and not re.match(r"^[0-9A-Za-z_-]{1,64}$", a.wxid):
459
+ die("--wxid 只认字母数字下划线减号(建议 gh_ 开头的原始ID)")
460
+ key = load_key()
461
+ {"balance": cmd_balance, "hot": cmd_hot, "search": cmd_search, "accounts": cmd_accounts, "posts": cmd_posts, "benchmark": cmd_benchmark, "article": cmd_article,
462
+ "direction": cmd_direction, "calendar": cmd_calendar}[a.cmd](a, key)
463
+
464
+
465
+ if __name__ == "__main__":
466
+ main()