跳到导航

Telegram 公开频道消息怎么有界采集并归档?

使用 telegram.web.fetch_post_detail 可重新读取单条 Telegram 公告并与已存版本比对变更;使用 telegram.web.fetch_channel_posts、archive_telegram.py、受控游标翻页和 build_archive_report.py 可为周报归档近期公告并生成可回查证据包。Telegram 频道管理员可以编辑已发布的消息,因此复核旧公告与查找新发布消息是两项独立任务。Telegram 频道说明

例如你周一把一条活动公告发给同事,周三有人问集合地点是不是改了。手里有原消息链接和周一保存的内容时,重新读取这条消息,把两个版本并排比较。

群里贴了旧公告,怎么确认变更?

把 t.me/example/123 这样的链接拆成频道用户名 example 和整数消息 ID 123,再换成你实际链接里的值。把下面的 JSON POST 到 https://api.beatapi.io/v1/social-data/call,使用 BeatAPI Bearer 鉴权。

{"action":"telegram.web.fetch_post_detail","params":{"channel":"example","post_id":123}}
  1. 确认返回的就是你转发的那条公告。
  2. 在交接表里记下消息链接、核对时间、旧地点、当前地点和本次请求号。
  3. 周一的存档写 A 门、最新版本写 C 门时,通知同事按 C 门集合,并附上原公告链接。只有当前版本时,报告当前地点和读取时间。

要把近期几条公告一起放进周报,按下面第 1–7 步操作。

1. 设定有界目标

先选一个公开频道,取一页近期公告(limit: 20)作为周报素材。每个列表分页和每次单条详情都按一次请求单独计费,单价见 BeatAPI 价格页。

2. 获取首次消息

curl --fail-with-body -sS https://api.beatapi.io/v1/social-data/call \
-H "Authorization: Bearer $BEATAPI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"action":"telegram.web.fetch_channel_posts","params":{"channel":"<channel_username>","limit":20}}' \
-o telegram-page-1.json

把 <channel_username> 换成频道用户名。HTTP 请求失败时保留错误输出并停止,不运行归档步骤。后续每次请求都用新的原始文件名保存。

3. 校验并归档原始响应

把下面的脚本保存为 archive_telegram.py。archive_telegram.py 校验业务状态、动作和 data 对象,校验游标类型,保存完整的返回对象,并拒绝覆盖已有的归档文件。

import json,pathlib,sys
source,target=map(pathlib.Path,sys.argv[1:3])
r=json.loads(source.read_text(encoding="utf-8"))
if r.get("status")!="succeeded" or r.get("action")!="telegram.web.fetch_channel_posts":
raise ValueError("Expected successful Telegram channel posts")
data=r.get("data")
if not isinstance(data,dict): raise ValueError("Expected channel response object")
if not isinstance(r.get("request_id"),str) or not r["request_id"].strip():raise ValueError("Missing request_id")
paging=data.get("pagination")
if paging is None:paging={}
if not isinstance(paging,dict): raise ValueError("Invalid pagination")
cursors={}
for name in ("before_cursor","after_cursor"):
value=paging.get(name)
if value is not None and (isinstance(value,bool) or not isinstance(value,int)):
raise ValueError("Cursor must be an integer")
cursors[name]=value
with target.open("x",encoding="utf-8") as f:
json.dump({"action":r["action"],"request_id":r.get("request_id"),"data":data},f,ensure_ascii=False,indent=2)
print(json.dumps(cursors))

4. 执行和核对

python3 archive_telegram.py telegram-page-1.json telegram-archive-1.json

归档文件保留 action、request_id 和 data。另外保存一份请求清单,记录频道、翻页方向、参数和采集时间。保存成功不代表已取回全部历史消息。archive_telegram.py 只保存原始对象;第 6 步的 build_archive_report.py 读取官方说明里的消息数组。

5. 仅在预算内继续

  1. 取更旧的消息时,把打印出的 before_cursor 作为 before 传入;取更新的消息时,把 after_cursor 作为 after 传入。
  2. channel 和 limit 保持不变,每一页用新文件名保存。
  3. 游标缺失、重复或达到请求上限时停止。游标缺失不是重新请求第一页的理由。

每次后续请求单独计入预算。频道搜索和评论使用各自的动作,不使用 before 和 after 翻页参数。

频道与消息标识 · 分页与搜索

BeatAPI 清洗并原样透传 data,返回 data.messages、data.channel_info 以及包含整数游标 before_cursor 和 after_cursor 的 data.pagination。

6. 交付能回查原文的多页归档

交给同事四样材料:每页原始响应、请求清单、逐条消息文件 message-records.jsonl 和范围报告 report.json。build_archive_report.py 把 data.messages 里的每个对象写成 JSONL 的一行。同事要核对某条公告时,用记录里的请求号和页内位置打开原始响应页,再打开对应的 Telegram 消息。

每一页的原始响应都保留。同事在 message-records.jsonl 里打开一条消息时,请求号和页内位置能找回包含这条消息的那次响应。

保存 manifest.json,每个请求填写实际的请求完成时间(带时区),每个 response_file 写该次请求的原始响应文件名。下面的示例展示了单页 manifest.json 的预期格式:

[{"params":{"channel":"YOUR_CHANNEL","limit":20},"collected_at":"2026-11-16T14:00:00+00:00","response_file":"telegram-page-1.json"}]

把下面的脚本保存为 build_archive_report.py,并在 manifest.json 里逐页记录真实参数。build_archive_report.py 拒绝混用频道或 limit、重复的请求或请求 ID、不递增的时间、失败响应和断开的游标链。脚本复制原始字节并记录每个文件的 SHA-256,不修改源文件。report.json 里的 message_count 保持 null,因为页数不是消息数。

import datetime,hashlib,json,pathlib,sys
manifest=pathlib.Path(sys.argv[1])
target=pathlib.Path(sys.argv[2])
entries=json.loads(manifest.read_text(encoding="utf-8"))
if not isinstance(entries,list) or not entries:raise ValueError("Nonempty manifest required")
pages=[];seen=set();request_ids=set();channel=None;blobs=[];direction=None;last_time=None;batch_limit=None;records=[]
for entry in entries:
params=entry["params"]
name=params["channel"]
if not isinstance(name,str) or not name.strip():raise ValueError("Channel required")
if channel is None:channel=name
if name!=channel:raise ValueError("Do not mix channels")
stamp=entry["collected_at"]
dt=datetime.datetime.fromisoformat(stamp.replace("Z","+00:00"))
if dt.tzinfo is None:raise ValueError("Use timestamp with timezone")
if last_time is not None and dt <= last_time:raise ValueError("Request times must increase")
last_time=dt
if set(params)-{"channel","limit","before","after"}:raise ValueError("Unknown request parameter")
limit=params.get("limit",20)
if type(limit) is not int or not 1<=limit<=100:raise ValueError("limit must be 1-100")
if batch_limit is None:batch_limit=limit
if limit!=batch_limit:raise ValueError("Keep limit unchanged within a scan")
before=params.get("before",0);after=params.get("after",0)
if type(before) is not int or type(after) is not int:raise ValueError("Request cursors must be integers")
if before and after:raise ValueError("Conflicting directions")
active="before" if before else ("after" if after else None)
if pages:
if active is None:raise ValueError("Do not restart at the initial page")
if direction is not None and active!=direction:raise ValueError("Use separate scans for older and newer pages")
previous=pages[-1]["returned_cursors"][active+"_cursor"]
if previous in (None,0) or params[active]!=previous:raise ValueError("Cursor does not continue the previous response")
if active:direction=active
canonical={"channel":name,"limit":limit,"before":before,"after":after}
identity=json.dumps(canonical,sort_keys=True)
if identity in seen:raise ValueError("Repeated request parameters")
seen.add(identity)
path=pathlib.Path(entry["response_file"])
if not path.is_absolute():path=manifest.parent/path
raw=path.read_bytes();r=json.loads(raw)
if r.get("status")!="succeeded" or r.get("action")!="telegram.web.fetch_channel_posts":
raise ValueError("Failed or wrong action")
request_id=r.get("request_id")
if not isinstance(request_id,str) or not request_id.strip() or request_id in request_ids:
raise ValueError("Distinct nonempty request_id required")
request_ids.add(request_id)
if not isinstance(r.get("data"),dict):raise ValueError("Missing data object")
messages=r["data"].get("messages")
if not isinstance(messages,list) or any(not isinstance(message,dict) for message in messages):
raise ValueError("Expected documented data.messages array of objects")
for index,message in enumerate(messages):
records.append({"channel":name,"request_id":request_id,"collected_at":stamp,
"source_sha256":hashlib.sha256(raw).hexdigest(),"page_index":len(pages),
"message_index":index,"message":message})
paging=r["data"].get("pagination")
if paging is None:paging={}
if not isinstance(paging,dict):raise ValueError("Invalid pagination object")
cursors={key:paging.get(key) for key in ("before_cursor","after_cursor")}
for value in cursors.values():
if value is not None and (isinstance(value,bool) or not isinstance(value,int)):
raise ValueError("Invalid cursor")
filename="page-"+str(len(pages)+1)+".json"
blobs.append((filename,raw))
pages.append({"params":params,"collected_at":stamp,"request_id":r.get("request_id"),
"source_file":str(path),"archived_file":filename,
"sha256":hashlib.sha256(raw).hexdigest(),"returned_cursors":cursors,"message_records":len(messages)})
report={"state":"partial","channel":channel,"pages":pages,"direction":direction,"limit":batch_limit,
"message_count":None,"message_records":len(records),"count_basis":"Occurrences, not unique messages",
"coverage":"Recorded requests only; not full history",
"generated_at":datetime.datetime.now(datetime.timezone.utc).isoformat()}
target.mkdir() # Refuse existing directories; all source validation happened above.
for filename,raw in blobs:(target/filename).write_bytes(raw)
with (target/"message-records.jsonl").open("x",encoding="utf-8") as output:
for record in records:output.write(json.dumps(record,ensure_ascii=False)+"\n")
(target/"report.json").write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding="utf-8")
print(str(target/"report.json"))
python3 build_archive_report.py manifest.json telegram-evidence-batch-1

打开 report.json,逐项把原文件、request_id、时间和返回的游标与保存的响应核对。游标缺失或为零时结束该方向;零是第一次请求的默认值,不代表可以从第一页重来。较旧和较新的扫描分成不同批次(同一批内的要求见下一段)。游标缺失只结束本批,不证明历史已经完整。目标目录必须还不存在;磁盘写入中断时,先检查写了一半的目录,再换一个新目录名重试。build_archive_report.py 不联网。

同一批内保持频道、limit 和翻页方向不变,实际请求时间递增,下一页的游标必须来自上一份已保存的响应。build_archive_report.py 校验的是请求证据的连续性,不把页数当作消息数。

7. 审阅消息记录并保留每条记录的出处

BeatAPI 在 data 下返回 messages、channel_info 和 pagination,因此消息数组路径为 data.messages。证据包生成的 message-records.jsonl 每行保存一个完整的消息对象,以及频道、request_id、采集时间、原始响应的 SHA-256 和页内位置。

用 JSONL 查看器打开 message-records.jsonl,按以下顺序审阅:

  1. 按 request_id 或 page_index 筛选,找到记录所在的原始页。message_index 是从零开始的页内位置,不是 Telegram 消息 ID。
  2. message_records 是返回记录的出现次数。跨页重叠的记录原样保留,两条正文相同的不同消息不会被合并。
  3. 空的 messages 数组生成空的 JSONL 文件;缺少 messages 数组时直接报错,不当作零条。
  4. 消息对象内部的 ID 和正文字段尚未核实,所以证据包不含规范化的正文 CSV,message_records 也不是唯一消息数。

channel_info 和其他字段保留在原始页里。签名媒体链接不是永久文件;没有相应权利时不下载、不再托管。对外分享前,先在副本里去掉个人信息,原始证据私下保存。