跳到导航

每天检查同行公众号,怎样找出值得补读的新文章?

要每天从同行公众号里找出值得补读的新文章:每天用 wechat_mp.v2.fetch_account_articles 从每个账号文章列表的第一页开始取,并按「账号 + app_msg_id + idx」与已存记录比对。同一天的一轮扫描里,下一页用这一轮返回的 next_offset;换一天重新从第一页开始。第 8 步的 wechat_sync.py 把新发现的文章写进 new-articles.csv,比对状态保存在 state.json。只对选中的文章用 wechat_mp.v2.fetch_article_detail_h5 读正文。交给同事的是新发现的文章、每篇值得读的理由和实际查过的范围。

用一次查新说明结果怎么读

例如你跟踪同行的产品公告,今天查三页,发现一篇今天发的《价格调整》和一篇之前漏掉的上月活动通知。两篇都进入 new-articles.csv,在工作表中把《价格调整》标为「今天发布」,把活动通知标为「今天发现的旧文」。已知文章只改了标题时,从 changed-articles.csv 打开原文复查改了什么。两个 CSV 文件都可按文章键关联到原始链接。

如果查到第三页就用完页数预算,写明「检查三页」及停止原因。遇到失败时,保留上一轮状态,先复用已保存的响应。用 state.json 做下一轮比对,阅读判断写在独立的工作表。要每日定时触发并通知群,见n8n 查新与飞书提醒。

1. 先准备已有文章表

每篇文章至少保留账号 username、内容栏目、文章唯一键、标题、文章 URL、首次发现时间和原始响应文件。唯一键使用已核对的文章 ID 或稳定的文章链接,不使用标题。

调用 data:wechat_mp.v2.fetch_account_articles 时明确传 raw:false。已核对的简化结构包含 data.biz_username、data.articles[]、data.next_offset 和 data.is_end(0/1),每篇文章含 app_msg_id、idx、title、digest、url、create_time 和 update_time。BeatAPI 将简化结果直接保留在 data 中返回,不改写成其他平台的结构。默认的 raw=true 响应是嵌套的群发条目,不能交给第 8 步的 wechat_sync.py。

wechat_sync.py 使用账号内的 app_msg_id:idx 唯一键,同一次群发里的次条不会被并成一篇。下表是本地列,不是 API 路径。

本地列用途
article_key区分文章,同一账号内稳定;跨账号合并时连同账号去重
article_url后续读取正文的真实文章 URL
first_seen_at首次在本地发现,不冒充发布时间
last_seen_at本轮再次看到的时间
content_tab文章、视频等栏目,各栏目的游标不混用

2. 核对合同并设定范围

curl -sS https://api.beatapi.io/v1/capabilities/inspect \
-H 'Content-Type: application/json' \
-d '{"reference":"data:wechat_mp.v2.fetch_account_articles"}'

用上面的免费 Inspect 请求确认当前输入和价格。首次运行限定一个账号、文章栏目、最多三页;三页只是示例上限,不保证覆盖每个账号。更早的文章用历史文章指南补齐。

3. 每轮从第一页重新取

查新文章时,不要接着上次历史导出末尾的游标往下取。首个请求不传 offset:

curl -sS https://api.beatapi.io/v1/social-data/call \
-H "Authorization: Bearer $BEATAPI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"action":"wechat_mp.v2.fetch_account_articles","params":{"username":"<username>","item_show_type":0,"raw":false}}' \
-o wechat-sync-page-1.json

每轮建一个独立目录,保留全部原始响应、request_id、查询时间和输入,不覆盖上一轮。确认业务结果成功、结构符合已核对的映射后才处理记录;解析错误不能记成“没有新文章”。

4. 比对文章键,并决定下一页

把本页返回的文章映射进自己的文章表,按账号和 article_key 与历史表比对:新键加入待保存清单;已有的键更新 last_seen_at;已有键的标题变化记为修改,不算新发布的文章。

下一页传本轮实际返回的 next_offset,按字符串原样保存。不要自增 next_offset,也不跨账号或栏目复用。每轮记录已用过的游标:游标重复、出现业务错误或到达三页上限时停止,并记录原因。

不能“遇到第一篇旧文章就停止”。fetch_account_articles 的合同不保证严格按时间倒序,旧文章后面仍可能出现新文章。达到扫描上限也不等于列表已经取完。要减少遗漏,就扩大受控的回看范围、提高检查频率或定期深扫,并始终写明实际查过的范围。

5. 只为选中的新文章读正文

先把新发现的文章列表交给用户筛选,再只对需要全文的 URL 调用 wechat_mp.v2.fetch_article_detail_h5。每次读取详情单独计费,列表里发现十篇新文章,不代表要读十篇正文。

同一 article_key 的正文已保存时可以复用。要发现文章被修改,需要另定刷新策略:“已见过这个键”不能证明内容没有变。见正文读取步骤。

6. 保存进度、恢复与外部调度

把每批校验过的已保存页面导出到新目录。本地写文件失败时,先重放已保存的 JSON 并按唯一键去重,不重新付费查询。一次失败的运行不能清空上一次成功的历史表。

记录每轮的页数、新键数、停止原因和原始响应位置。自动化运行时,持久化、并发锁与重试规则由你自己的系统负责;外部定时器负责触发,写入飞书或数据库是另外的接入。本页步骤不提供现成的定时监控服务。

7. 计算调用次数和验收

本轮读 P 页列表、N 篇选定正文,共需 P + N 次平台查询;各动作的价格以当前 Inspect 结果为准,后续模型分析另计。列表会忽略 page_size,不要按 page_size 估算采集条数。

验收时检查四种情况:同一份本地响应处理两次,不新增重复文章;一页旧文章后面夹一篇新文章,仍能发现这篇新文章;页面失败、游标重复、达到上限三种情况,都不能输出“账号今天无更新”。定时器是否运行、跨系统写入是否成功,分别验收。

第 8 步的 wechat_sync.py 不联网,仅在本地按已公开的 raw:false 字段映射校验已保存响应。

历史完整性与遗漏 · 条数与栏目 · 公众号问题索引

8. 运行已保存页面的增量处理器

给 wechat_sync.py 传入已从文章详情确认的规范 gh_ username。API 也接受自定义微信号,但 wechat_sync.py 要求规范账号,才能直接对照响应里的 biz_username。旧状态文件作为证据保持不变。首次运行时,旧状态参数写成 -;首次运行只记录已观察到的页面,不是完整历史库。把后续新增称为“新文章”之前,先把已有的历史行按相同的账号/app_msg_id/idx 状态格式导入,或重放这些历史行已保存的简化页面。

pages.json 记录实际参数、HTTP 状态、时间和相对响应路径;下面的 pages.json 是占位清单,不是真实请求。采集时给第 3 节的 curl 加 --max-time 30 和 -w '%{http_code}\n',记录真实状态。网络超时不是空响应,也不能证明没有扣费;保留这次尝试,查看用量后再决定是否重试。

[{"action":"wechat_mp.v2.fetch_account_articles","params":{"username":"gh_example","raw":false,"item_show_type":0},"http_status":200,"collected_at":"2026-11-16T18:00:00Z","response_file":"wechat-sync-page-1.json"}]

把下面的代码保存为 wechat_sync.py。初始化运行 python3 wechat_sync.py - pages.json scan-001;下一次日扫描运行 python3 wechat_sync.py scan-001/state.json today-pages.json scan-002。每轮日扫描从空 offset 开始,输出目录必须是新目录。校验失败时 wechat_sync.py 也不改动旧状态文件。wechat_sync.py 每轮最多处理三页,不安装定时任务。

import csv, hashlib, json, pathlib, sys
from datetime import datetime
previous, manifest_path, target = sys.argv[1:4]
manifest_path, target = pathlib.Path(manifest_path), pathlib.Path(target)
entries = json.loads(manifest_path.read_text(encoding="utf-8"))
ACTION = "wechat_mp.v2.fetch_account_articles"
if not isinstance(entries, list) or not 1 <= len(entries) <= 3:
raise ValueError("Supply 1–3 saved pages for this bounded incremental scan")
state = {"version": 1, "username": None, "item_show_type": 0, "articles": []} if previous == "-" else json.loads(pathlib.Path(previous).read_text(encoding="utf-8"))
if state.get("version") != 1 or state.get("item_show_type") != 0 or not isinstance(state.get("articles"), list):
raise ValueError("Expected the article-tab state produced by this helper")
def number(v):
if type(v) is int and v > 9007199254740991:
raise ValueError("Unsafe numeric ID; require an originally string-encoded ID")
if isinstance(v, bool) or not isinstance(v, (int, str)) or not str(v).isdigit() or int(v) < 1:
raise ValueError("Expected positive article ID/position")
return str(int(v))
def stamp(v):
t = datetime.fromisoformat(v.replace("Z", "+00:00"))
if t.tzinfo is None:
raise ValueError("Collection times must include timezone")
return t
def key(row):
return number(row["app_msg_id"]) + ":" + number(row["idx"])
records = {}
for row in state["articles"]:
k = key(row)
if k in records:
raise ValueError("Duplicate article identity in old state")
stamp(row["first_seen_at"]); stamp(row["last_seen_at"])
records[k] = row
initial = set(records)
new, changed, observed, request_ids, cursors = set(), set(), set(), set(), set()
pages, raw_pages, observations = [], [], []
expected, username, last_time = None, state["username"], None
stop = "saved_pages_exhausted"
watermark = stamp(state["last_collected_at"]) if state.get("last_collected_at") else None
processed = state.get("processed_requests", {})
if not isinstance(processed, dict):
raise ValueError("Invalid processed-request ledger")
metadata = ("title", "digest", "url", "create_time", "update_time")
for index, entry in enumerate(entries):
if stop != "saved_pages_exhausted":
raise ValueError("Manifest contains pages after terminal response")
params = entry["params"]
if entry.get("action") != ACTION or params.get("raw") is not False or (type(params.get("item_show_type")) is not int or params["item_show_type"] != 0):
raise ValueError("Use the article tab and raw=false explicitly")
if set(params) - {"username", "raw", "item_show_type", "offset", "page_size"}:
raise ValueError("Unexpected parameters")
account = params["username"]
if not isinstance(account, str) or not account.startswith("gh_"):
raise ValueError("This helper uses the account's verified gh_ username")
if username is None:
username = account
if account != username:
raise ValueError("Mixed account or old state belongs to another account")
if index == 0 and params.get("offset") not in (None, ""):
raise ValueError("Each new scan starts at the first page")
if index > 0 and params.get("offset") != expected:
raise ValueError("Broken offset chain")
current_time = stamp(entry["collected_at"])
if last_time and current_time < last_time:
raise ValueError("Manifest times must be chronological")
last_time = current_time
http = entry["http_status"]
if type(http) is not int or not 100 <= http <= 599:
raise ValueError("Record the actual integer HTTP status")
path = manifest_path.parent / entry["response_file"]
raw = path.read_bytes(); raw_pages.append(raw)
result = json.loads(raw)
page = {"page": index + 1, "params": params, "collected_at": entry["collected_at"], "http_status": http,
"source": str(path), "sha256": hashlib.sha256(raw).hexdigest()}
pages.append(page)
if http != 200:
error = result.get("error", {})
if not isinstance(error, dict) or not isinstance(error.get("code"), str) or not error["code"]:
raise ValueError("Expected gateway error envelope")
page.update(error_code=error["code"], request_id=error.get("request_id"))
stop = "gateway_failed"
continue
if result.get("action") != ACTION or result.get("status") != "succeeded":
raise ValueError("Wrong action or unsuccessful response")
request = result.get("request_id")
if not isinstance(request, str) or not request.strip() or request in request_ids:
raise ValueError("Missing/repeated request ID")
request_ids.add(request); page["request_id"] = request
replayed = request in processed
signature = {"sha256": page["sha256"], "params": params, "collected_at": entry["collected_at"]}
if replayed and processed[request] != signature:
raise ValueError("Processed request was changed")
if not replayed and watermark and current_time < watermark:
raise ValueError("Do not apply older unseen observations")
page["replayed"] = replayed
data = result.get("data")
if not isinstance(data, dict) or data.get("biz_username") != username or not isinstance(data.get("articles"), list):
raise ValueError("Expected simplified article list for the same account")
for article in data["articles"]:
k = key(article)
if not isinstance(article.get("title"), str) or not isinstance(article.get("url"), str) or not article["url"]:
raise ValueError("Article requires title and URL")
for field in metadata:
if article.get(field) is not None and (isinstance(article[field], bool) or not isinstance(article[field], (str, int))):
raise ValueError("Unexpected article field type")
values = {field: article.get(field) for field in metadata}
observations.append({"article_key": k, "page": index + 1, "request_id": request, "article": article})
observed.add(k)
if replayed:
if k not in records:
raise ValueError("Processed request refers to a missing stored article")
continue
prior = records.get(k)
if prior is None:
new.add(k)
elif k in initial and any(prior.get(field) != values[field] for field in metadata):
changed.add(k)
record = {"app_msg_id": number(article["app_msg_id"]), "idx": number(article["idx"]), **values,
"first_seen_at": prior["first_seen_at"] if prior else entry["collected_at"],
"last_seen_at": entry["collected_at"], "last_request_id": request}
records[k] = record
if not replayed:
processed[request] = signature
state["last_collected_at"] = entry["collected_at"]
watermark = current_time
page["returned_objects"] = len(data["articles"])
end, cursor = data.get("is_end"), data.get("next_offset")
if type(end) not in (bool, int) or end not in (0, 1):
stop = "missing_end_flag"
elif end == 1:
stop = "provider_end"
elif not data["articles"]:
stop = "empty_page_before_end"
elif not isinstance(cursor, str) or not cursor:
stop = "missing_cursor"
elif cursor in cursors:
stop = "repeated_cursor"
else:
cursors.add(cursor); expected = cursor
next_request = {"action": ACTION, "params": {"username": username, "raw": False, "item_show_type": 0, "offset": expected}} if stop == "saved_pages_exhausted" and len(entries) < 3 else None
if stop == "saved_pages_exhausted" and len(entries) == 3:
stop = "scan_page_cap"
state.update(username=username, articles=[records[k] for k in sorted(records)], processed_requests=processed)
target.mkdir(exist_ok=False)
def safe(v):
if v is None:
return ""
value = str(v)
return "'" + value if value.startswith(("=", "+", "-", "@", "\t", "\r", "\n")) else value
columns = ["app_msg_id", "idx", *metadata, "first_seen_at", "last_seen_at", "last_request_id"]
for name, keys in [("new-articles.csv", new), ("changed-articles.csv", changed)]:
with (target / name).open("x", encoding="utf-8-sig", newline="") as f:
writer = csv.DictWriter(f, fieldnames=columns); writer.writeheader()
writer.writerows({field: safe(records[k].get(field)) for field in columns} for k in sorted(keys))
(target / "state.json").write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
with (target / "observations.jsonl").open("x", encoding="utf-8") as f:
for item in observations:
f.write(json.dumps(item, ensure_ascii=False) + "\n")
for index, raw in enumerate(raw_pages):
(target / ("raw-page-%02d.json" % (index + 1))).write_bytes(raw)
report = {"username": username, "new_articles": len(new), "changed_known_articles": len(changed),
"observed_keys": len(observed), "stored_articles": len(records), "stop_reason": stop,
"complete_history": False, "publication_dates_inferred": False, "pages": pages}
(target / "coverage.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
if next_request:
(target / "next-request.json").write_text(json.dumps(next_request, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({"new": len(new), "changed": len(changed), "stop": stop}))

交付 new-articles.csv 用来挑选要读的正文,changed-articles.csv 用来查看已知 ID 的列表元数据变化;state.json 是下一轮的输入。发布/更新时间的原值与首次/最近观察时间分开保存。ID 保留为字符串,导入表格时把 ID 列设为文本。只有 CSV 文件对公式前缀做转义,原文仍保留在观察记录和原始页中。

coverage.json 记录上限、错误和每个源文件的哈希;observations.jsonl 保留重复观察和原始对象。旧文章后面夹着新文章时,新文章仍会处理;相同 app_msg_id、不同 idx 的两篇文章分开保留。用输出状态重放同一批页面不会新增 ID。列表元数据变化不能证明正文变了,首次发现也不是发布时间。

如果同一轮还要继续取页,next-request.json 已包含原样的 next_offset。只在预算内执行新增的收费请求,追加这次请求的实际日志,再用完整的扩展清单对照本轮开始前的同一个旧状态,导出到另一个新目录,不要用中间输出状态。对照开始前的旧状态,才能保留这一轮完整的新文章集合。用输出状态精确重放也可行:处理账本核对请求 ID、原字节哈希、参数和时间,已应用的观察直接跳过,不会把较新的标题回滚。已处理请求的证据被改动,或出现更旧的未见请求时,wechat_sync.py 会拒绝。末页失败时,之前成功的页面仍保留并标记 gateway_failed;新条数为零不能说成“整个账号没有更新”。达到上限表示更旧的页面没有查过。每个账号只允许一个写入者,wechat_sync.py 不是并发数据库。

十个账号每个查一页,共十次列表调用。正文只对入选文章读取,另行计次。设置定时前,在 BeatAPI 价格页核算预算。

标识符精度前提

JSON 中不带引号的裸数字按 float64 解码时,超过 9007199254740991 的数字 ID 在 wechat_sync.py 读取前就可能已经舍入。wechat_sync.py 直接拒绝此类裸数字 ID,以字符串返回的 ID 保持精确。不要给已经舍入的值加引号假装修复:遇到拒绝时停止导出,保存 request_id 查证。Python 大整数和表格文本格式都无法恢复解码阶段已经舍入的数字。

选中文章怎样交给知识库?

先用本页的增量流程生成带来源的选中链接清单。目标知识库支持导入文章 URL 时,先导入一条链接,核对导入后的标题、原文和目标目录;需要导入正文文件时,接正文与 Markdown 入库。在清单中分别记录待导入、成功和失败的链接,重试只取失败的链接。ima 等目标库使用你已核实的导入方式。增量结果记录的是发现了哪些文章,不是哪些已经导入。

导入 ima 知识库