> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# 新品Reel评论里哪些问题还没答？怎样连同回复一起核对？

> 从新品评论保存原句，选中需要上下文的问题展开回复，再交付有证据的已答、待补上下文和未观察到答案记录。

要查新品 Reel 评论里哪些问题已经有人回答，先用 `instagram.fetch_post_comments_v2` 读 Reel 的一级评论：把 Reel 的数字媒体 `pk` 作为 `media_id` 传入，结果导出为 `comments.csv`。挑出与配件、清洁或杯型有关的问题，再用 `instagram.fetch_comment_replies` 按问题所在的一级评论 ID 读回复。最后把每个问题标为 `answered`（已答）、`needs_context`（待补上下文）或 `no_answer_observed`（本轮未见答案）。

例如观众问「可以用矮杯吗」，就保留原句和 Reel 链接。有回复提到杯高限制时，把这条回复与问题配对，再拿杯高限制去核对产品说明。

## 一条问题怎样走到下一步？

1. **认准 Reel。** 复用已保存帖子详情里的媒体 ID，按[帖子到评论交接](/zh/faq/instagram-url-and-id)准备请求。
2. **保存一级评论。** 查看 `comments.csv` 里选定的页数，找出与产品使用有关的提问；归纳时把每条问题的原句放在旁边。
3. **读取选中问题的回复。** 一级评论下的回复预览不代表整楼已读完。某个问题需要上下文时，为这条一级评论生成回复请求，回复分支保存到单独目录。
4. **核对回复有没有回答问题。** 读问题和返回的回复；`resolution.json` 里的每个判断都用实际回复 ID 和逐字原句支持。
5. **交接后续工作。** 每个问题写清要核实什么、由谁核实。生成 `resolution.json` 不会回复观众，也不会关闭任何问题。

把审核交给已连接 BeatAPI 的助手时，可以这样布置：

> 整理这条新品Reel里与配件和清洁有关的提问。每条保留原句，选中需要上下文的楼层读回复。把有回复证据的答案、还缺条件的提问和本次未见答案的问题分别列出，说明下一步。

## 最后看哪几个结果？

| 产物                       | 怎么用                          |
| ------------------------ | ---------------------------- |
| `comments.csv`           | 每个已观察到的一级评论 ID 一行，含评论正文和来源请求 |
| `replies.csv`            | 一条选定一级评论下已观察到的回复             |
| 每个输出目录里的 `coverage.json` | Reel 与一级评论、已保存页数、计数和停止原因     |
| `resolution.json`        | 人工判断、支持判断的回复原句和缺少的上下文        |

`answered` 需要一条已保存回复的原文支持答案；`needs_context` 表示已保存的回复不足以判断；`no_answer_observed` 只描述本次保存的样本。使用任何答案之前，先与产品说明核对。

下面第 1–7 步依次完成取数、导出、读回复和审核。Python 脚本只处理已保存的文件；`save_call.sh` 每运行一次发一次数据请求。已有响应时直接复用。

## 1. 准备媒体 ID 和页数预算

使用已保存帖子详情里与 Reel 短码匹配的那条记录的原始数字字符串 `pk`，不用 URL 短码，也不用快照 CSV 的通用 `id` 列。[链接到评论的交接流程](/zh/faq/instagram-url-and-id)从 v2 的 `data.data.pk` 或 v3 匹配的 `data.items[].pk` 取值，生成完整的首页请求。复用[帖子快照指南](/zh/guides/instagram-post-snapshot)保存的帖子详情，不再付费转换。在请求记录里写明媒体 ID 属于哪条 Reel：评论响应本身不标明是哪条 Reel。

一级评论用 `data:instagram.fetch_post_comments_v2` 请求，当前单价见[价格页](https://beatapi.io/zh/pricing)。先定本轮购买的页数；一级评论、选中回复和可选详情的请求数分开计算。条数以实际返回为准，本地导出不发请求。

## 2. 保存第一页和请求记录

写好 `request-1.json`，把示例媒体 ID 换成已确认的数字媒体 ID：

```json
{"action":"instagram.fetch_post_comments_v2","params":{"media_id":"3766120364183949816","sort_order":"recent"}}
```

把下面的脚本保存为 `save_call.sh`，在已批准的页数预算内每页运行一次 `bash save_call.sh request-1.json root-call-1`。每次运行发一次收费请求，不重试；`curl -q` 忽略本机 curlrc 里的重试和重定向设置。输出目录必须事先不存在。

```bash
set -eu
request="$1"
folder="$2"
test -f "$request"
: "${BEATAPI_API_KEY:?Set BEATAPI_API_KEY locally}"
mkdir "$folder"
cp "$request" "$folder/request.json"
date -u +'%Y-%m-%dT%H:%M:%SZ' > "$folder/collected-at.txt"
curl -q --fail-with-body -sS https://api.beatapi.io/v1/social-data/call \
  -H "Authorization: Bearer $BEATAPI_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary "@$folder/request.json" \
  -D "$folder/headers.txt" -o "$folder/response.json" \
  -w '%{http_code}\n' > "$folder/http-status.txt"
python3 - "$folder" <<'PYTHON'
import json,pathlib,sys
p=pathlib.Path(sys.argv[1]);request=json.loads((p/'request.json').read_text())
status=int((p/'http-status.txt').read_text().strip())
if status!=200:raise ValueError('Stop and inspect the failed call')
entry={'action':request['action'],'params':request['params'],'http_status':status,
       'collected_at':(p/'collected-at.txt').read_text().strip(),
       'response_file':str((p/'response.json').resolve())}
(p/'entry.json').write_text(json.dumps(entry,ensure_ascii=False,indent=2),encoding='utf-8')
PYTHON
```

`save_call.sh` 保留实际提交的请求、响应头和正文、本机 UTC 请求开始时间和 HTTP 状态。`save_call.sh` 只在 HTTP 200 后生成 `entry.json`，`instagram_comments.py` 还会再检查响应包装。把每个生成的 `entry.json` 对象放进 `pages.json` 数组。下面的示例展示了 `pages.json` 的预期格式。curl、网络或 HTTP 失败时停止并保留目录，不要在同一目录再次运行 `save_call.sh`。日志里不写授权头。

```json
[{"action":"instagram.fetch_post_comments_v2","params":{"media_id":"3766120364183949816","sort_order":"recent"},"http_status":200,"collected_at":"2026-11-16T18:00:00Z","response_file":"root-call-1/response.json"}]
```

## 3. 导出已保存页面，准备下一页请求

把下面的脚本保存为 `instagram_comments.py`。脚本读取 `/v1/social-data/call` 的直接响应，不读 MCP 截断预览。相对的 `response_file` 路径按 `pages.json` 所在目录解析；`save_call.sh` 已经记录绝对路径。脚本检查所有页面属于同一媒体 ID 和同一明确排序、采集时间带时区且按时间先后排列、游标链连续。缺少 `data.comments` 的响应会让导出停止，不会当作空页。`comments.csv` 对每条一级评论保留第一次观察值，原始页保留之后的变化。回复不计入一级评论数。

```python
import csv, hashlib, json, pathlib, sys
from datetime import datetime
manifest_file, target = map(pathlib.Path, sys.argv[1:3])
entries = json.loads(manifest_file.read_text(encoding="utf-8"))
ACTION = "instagram.fetch_post_comments_v2"
if not isinstance(entries, list) or not 1 <= len(entries) <= 10:
    raise ValueError("Supply 1–10 ordered saved pages; this is the helper's cap")
rows, previews, evidence, seen, cursors, requests = [], [], [], set(), set(), set()
raw_pages = []
expected, media, sort, previous_time = None, None, None, None
stop = "saved_pages_exhausted"
def ident(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, (str, int)) or not str(v).isascii() or not str(v).isdigit() or not any(c != "0" for c in str(v)):
        raise ValueError("Expected a decimal ID")
    return str(v)
def safe(v):
    if v is None:
        return ""
    if not isinstance(v, (str, int, float, bool)):
        raise ValueError("Unexpected structured CSV field")
    s = str(v)
    return "'" + s if s.startswith(("=", "+", "-", "@", "\t", "\r", "\n")) else s
def scalar(v):
    if v is not None and (isinstance(v, bool) or not isinstance(v, (str, int))):
        raise ValueError("Unexpected count/timestamp type")
    if type(v) is int and abs(v) > 9007199254740991:
        raise ValueError("Unsafe numeric timestamp; retain original evidence")
    return v
def count(v):
    if v is None:
        return None
    if type(v) is int and 0 <= v <= 9007199254740991:
        return v
    if isinstance(v, str) and v.isascii() and v.isdigit():
        return v
    raise ValueError("Expected a nonnegative safe integer or original digit string count")
for index, entry in enumerate(entries):
    if stop != "saved_pages_exhausted":
        raise ValueError("Manifest continues after a terminal page")
    if type(entry.get("http_status")) is not int or not 100 <= entry["http_status"] <= 599:
        raise ValueError("HTTP status must be an integer from the actual request")
    params = entry["params"]
    if entry["action"] != ACTION or set(params) - {"media_id", "sort_order", "min_id"}:
        raise ValueError("Wrong action or unknown parameters")
    current_media, current_sort = ident(params["media_id"]), params["sort_order"]
    if current_sort not in ("recent", "popular"):
        raise ValueError("Set recent or popular explicitly")
    stamp = datetime.fromisoformat(entry["collected_at"].replace("Z", "+00:00"))
    if stamp.tzinfo is None or previous_time and stamp < previous_time:
        raise ValueError("Use chronological timezone-aware collection times")
    previous_time = stamp
    if index == 0:
        media, sort = current_media, current_sort
        if "min_id" in params:
            raise ValueError("First page must omit min_id")
    elif (current_media, current_sort) != (media, sort) or params.get("min_id") != expected:
        raise ValueError("Mixed target, sort, or broken cursor chain")
    source = manifest_file.parent / entry["response_file"]
    raw = source.read_bytes()
    raw_pages.append(raw)
    response = json.loads(raw)
    ev = {"page": index + 1, "source": str(source), "sha256": hashlib.sha256(raw).hexdigest(),
          "collected_at": entry["collected_at"], "params": params, "http_status": entry["http_status"]}
    evidence.append(ev)
    if entry["http_status"] != 200:
        error = response.get("error", {})
        if not isinstance(error, dict) or not isinstance(error.get("code"), str) or not error["code"]:
            raise ValueError("Non-200 entry requires a gateway error envelope")
        ev.update(request_id=error.get("request_id"), error_code=error.get("code"))
        stop = "gateway_failed"
        continue
    if response.get("status") != "succeeded" or response.get("action") != ACTION or response.get("error") is not None:
        raise ValueError("Saved response is not the requested successful action")
    request = response.get("request_id")
    if not isinstance(request, str) or not request.strip() or request in requests:
        raise ValueError("Missing/reused request ID")
    requests.add(request)
    ev["request_id"] = request
    data = response.get("data")
    if not isinstance(data, dict) or not isinstance(data.get("comments"), list):
        raise ValueError("Expected data.comments, not an empty-result fallback")
    page_ids = []
    for comment in data["comments"]:
        cid = ident(comment["pk"])
        page_ids.append(cid)
        if not isinstance(comment.get("text"), str):
            raise ValueError("Expected comment text")
        children = comment.get("preview_child_comments")
        if children is not None and not isinstance(children, list):
            raise ValueError("Unexpected preview container")
        if children:
            previews.append({"media_id": media, "root_comment_id": cid, "request_id": request,
                             "preview_child_comments": children})
        likes = count(comment.get("comment_like_count"))
        reply_count = count(comment.get("child_comment_count"))
        created = scalar(comment.get("created_at"))
        created_utc = scalar(comment.get("created_at_utc"))
        if cid in seen:
            continue
        seen.add(cid)
        rows.append({"media_id": media, "comment_id": cid, "text": comment["text"],
                     "likes": likes,
                     "created_at_raw": created,
                     "created_at_utc_raw": created_utc,
                     "reported_reply_count": reply_count,
                     "preview_objects": len(children) if children is not None else None,
                     "request_id": request, "collected_at": entry["collected_at"], "source_page": index + 1})
    ev.update(returned_root_objects=len(page_ids), reported_comment_count=count(data.get("comment_count")))
    more, cursor = data.get("has_more_headload_comments"), data.get("next_min_id")
    if not isinstance(more, bool):
        stop = "missing_more_flag"
    elif not more:
        stop = "provider_end"
    elif not page_ids:
        stop = "empty_page_with_more"
    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": {"media_id": media, "sort_order": sort, "min_id": expected}} if stop == "saved_pages_exhausted" and len(entries) < 10 else None
if stop == "saved_pages_exhausted" and len(entries) == 10:
    stop = "helper_page_cap"
target.mkdir(exist_ok=False)
columns = ["media_id", "comment_id", "text", "likes", "created_at_raw", "created_at_utc_raw", "reported_reply_count", "preview_objects", "request_id", "collected_at", "source_page"]
with (target / "comments.csv").open("x", encoding="utf-8-sig", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=columns)
    writer.writeheader()
    writer.writerows({k: safe(v) for k, v in row.items()} for row in rows)
with (target / "reply-previews.jsonl").open("x", encoding="utf-8") as f:
    for item in previews:
        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 = {"media_id": media, "sort_order": sort, "unique_root_comments": len(rows),
          "stop_reason": stop, "all_comments_collected": False, "reply_coverage": "previews_only",
          "duplicate_policy": "first_observation_csv_all_observations_raw", "pages": evidence}
(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({"roots": len(rows), "stop": stop, "next_request_prepared": bool(next_request)}))
```

## 4. 在预算内继续翻页

运行 `python3 instagram_comments.py pages.json review-1`。如果生成了 `review-1/next-request.json`，文件里的 `min_id` 就是上一页 `next_min_id` 的原样字符串。不要解析后重写 `next-request.json`，不要手改转义，也不要换媒体 ID 或排序后复用。决定购买下一页时运行 `bash save_call.sh review-1/next-request.json root-call-2`，把 `root-call-2/entry.json` 作为新对象追加到 `pages.json` 数组，再导出到新目录，例如 `review-2`。不编辑已保存的请求，不手工重建游标；终止页之后不再追加页面。

达到预算，或导出报告 `provider_end`、更多标记为 true 却返回空页、游标重复或缺失、更多标记不是布尔值、网关失败时，都停止。出现这些情况时 `instagram_comments.py` 不生成 `next-request.json`。字段缺失是需要上报的结构问题，不是零评论：保留响应和 request_id 联系支持，不要自动换另一个收费接口试探。成功返回 `comments: []` 且更多标记为 false 时，输出只有表头的 CSV，并记录正常结束。

## 5. 交付证据，不把样本说成全部评论

`comments.csv` 每个已观察到的一级评论 ID 一行，含原文（已做防表格公式转义）、点赞数、原始时间戳、声明回复数、预览对象数、请求 ID 和采集时间。在 Excel 里把媒体 ID 和评论 ID 按文本导入，防止长整数丢精度。零保持为零，缺失留空。原始时间戳不按猜测的时区或单位换算。表格有意不输出用户名和头像。

`reply-previews.jsonl` 把文档记录的回复预览对象挂在出现位置的一级评论下，不补造回复内部字段，也不代表完整楼层。`coverage.json` 记录每一页、页面哈希、声明总数和停止原因；`raw-page-*.json` 保存原始字节。这些源文件可能含个人信息，限制访问，对外另做脱敏副本。平台声明的总数不保证能取到多少条；到达 `provider_end` 也不代表已取到被删除、隐藏或私密的评论。

整理新品反馈时，在 `comments.csv` 的行上人工填写 `decision`、`topic` 和逐字来源原句。排除推广和重复内容时写明理由，并报告已审和未审的一级评论数以及 Reel 数。投诉只在已审样本内计数，计数不代表客户数、购买数、人群比例或产品缺陷。以公式字符开头的引文要对照原始 JSON 核对，不对照转义后的 CSV 单元格。承诺任何回复结果之前，先读[回复覆盖边界](/zh/faq/instagram-comment-coverage)。

## 证据和验证范围

评论 V2 响应的评论 ID、正文、计数、时间戳和游标字段都在 `data` 下。导出新一批数据前，先用已保存的响应核对 `data` 下的字段路径，并将本页示例中的占位 ID 和时间替换为实际请求值。

## 6. 为一个选定根评论展开回复证据表

某条一级评论提出了尚未解决的产品问题时，从 `comments.csv` 取这条一级评论的 `comment_id`。一级评论导出目录保持原样：`instagram_replies.py` 先核对一级评论所在原页的哈希、请求 ID，并确认这条一级评论确实出现，才接受回复页。预览对象不并入回复计数。

回复用 `data:instagram.fetch_comment_replies` 请求：传同一个媒体 ID，并把选中一级评论的 `pk` 作为 `comment_id`。每条一级评论的回复保存为独立分支，按计划页数和[当前价格](https://beatapi.io/zh/pricing)估算费用。

把第一条回复请求保存为 `reply-request-1.json`，两个示例 ID 换成选定的媒体 ID 和一级评论 ID。运行 `bash save_call.sh reply-request-1.json reply-call-1`，再把 `reply-call-1/entry.json` 放进 `reply-pages.json` 数组：

```json
{"action":"instagram.fetch_comment_replies","params":{"media_id":"3766120364183949816","comment_id":"17871667485468098"}}
```

```json
[{"action":"instagram.fetch_comment_replies","params":{"media_id":"3766120364183949816","comment_id":"17871667485468098"},"http_status":200,"collected_at":"2026-11-16T18:10:00Z","response_file":"reply-call-1/response.json"}]
```

请将上面示例中的 ID 和时间替换为实际请求值。把下面的脚本保存为 `instagram_replies.py`，运行 `python3 instagram_replies.py review-2 reply-pages.json replies-1`，其中 `review-2` 换成实际的一级评论导出目录。

```python
import csv, hashlib, json, pathlib, sys
from datetime import datetime
root_export, manifest_file, target = map(pathlib.Path, sys.argv[1:4])
root_report = json.loads((root_export / "coverage.json").read_text(encoding="utf-8"))
with (root_export / "comments.csv").open(encoding="utf-8-sig", newline="") as f:
    root_rows = list(csv.DictReader(f))
entries = json.loads(manifest_file.read_text(encoding="utf-8"))
ACTION = "instagram.fetch_comment_replies"
if not isinstance(entries, list) or not 1 <= len(entries) <= 10:
    raise ValueError("Supply 1–10 ordered saved pages; this is the helper's cap")
rows, previews, evidence, seen, cursors, requests = [], [], [], set(), set(), set()
raw_pages = []
expected, media, root_id, previous_time = None, None, None, None
stop = "saved_pages_exhausted"
def ident(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, (str, int)) or not str(v).isascii() or not str(v).isdigit() or not any(c != "0" for c in str(v)):
        raise ValueError("Expected a decimal ID")
    return str(v)
def safe(v):
    if v is None:
        return ""
    if not isinstance(v, (str, int, float, bool)):
        raise ValueError("Unexpected structured CSV field")
    s = str(v)
    return "'" + s if s.startswith(("=", "+", "-", "@", "\t", "\r", "\n")) else s
def scalar(v):
    if v is not None and (isinstance(v, bool) or not isinstance(v, (str, int))):
        raise ValueError("Unexpected count/timestamp type")
    if type(v) is int and abs(v) > 9007199254740991:
        raise ValueError("Unsafe numeric timestamp; retain original evidence")
    return v
def count(v):
    if v is None:
        return None
    if type(v) is int and 0 <= v <= 9007199254740991:
        return v
    if isinstance(v, str) and v.isascii() and v.isdigit():
        return v
    raise ValueError("Expected a nonnegative safe integer or original digit string count")
for index, entry in enumerate(entries):
    if stop != "saved_pages_exhausted":
        raise ValueError("Manifest continues after a terminal page")
    if type(entry.get("http_status")) is not int or not 100 <= entry["http_status"] <= 599:
        raise ValueError("HTTP status must be an integer from the actual request")
    params = entry["params"]
    if entry["action"] != ACTION or set(params) - {"media_id", "comment_id", "min_id"}:
        raise ValueError("Wrong action or unknown parameters")
    current_media, current_root = ident(params["media_id"]), ident(params["comment_id"])
    stamp = datetime.fromisoformat(entry["collected_at"].replace("Z", "+00:00"))
    if stamp.tzinfo is None or previous_time and stamp < previous_time:
        raise ValueError("Use chronological timezone-aware collection times")
    previous_time = stamp
    if index == 0:
        media, root_id = current_media, current_root
        matches = [row for row in root_rows if row["media_id"] == media and row["comment_id"] == root_id]
        if len(matches) != 1 or root_report["media_id"] != media:
            raise ValueError("Select one observed root from the previous export")
        root_row = matches[0]
        page_number = int(root_row["source_page"])
        root_raw = (root_export / ("raw-page-%02d.json" % page_number)).read_bytes()
        root_page = root_report["pages"][page_number - 1]
        if hashlib.sha256(root_raw).hexdigest() != root_page["sha256"]:
            raise ValueError("Root source hash mismatch")
        root_response = json.loads(root_raw)
        if root_response.get("action") != "instagram.fetch_post_comments_v2" or root_response.get("status") != "succeeded" or root_response.get("request_id") != root_row["request_id"] or root_response.get("error") is not None:
            raise ValueError("Invalid root source identity")
        if str(root_page["params"]["media_id"]) != media or not any(ident(x["pk"]) == root_id for x in root_response["data"]["comments"]):
            raise ValueError("Root does not belong to the saved request")
        if "min_id" in params:
            raise ValueError("First page must omit min_id")
    elif (current_media, current_root) != (media, root_id) or params.get("min_id") != expected:
        raise ValueError("Mixed media/root or broken cursor chain")
    source = manifest_file.parent / entry["response_file"]
    raw = source.read_bytes()
    raw_pages.append(raw)
    response = json.loads(raw)
    ev = {"page": index + 1, "source": str(source), "sha256": hashlib.sha256(raw).hexdigest(),
          "collected_at": entry["collected_at"], "params": params, "http_status": entry["http_status"]}
    evidence.append(ev)
    if entry["http_status"] != 200:
        error = response.get("error", {})
        if not isinstance(error, dict) or not isinstance(error.get("code"), str) or not error["code"]:
            raise ValueError("Non-200 entry requires a gateway error envelope")
        ev.update(request_id=error.get("request_id"), error_code=error.get("code"))
        stop = "gateway_failed"
        continue
    if response.get("status") != "succeeded" or response.get("action") != ACTION or response.get("error") is not None:
        raise ValueError("Saved response is not the requested successful action")
    request = response.get("request_id")
    if not isinstance(request, str) or not request.strip() or request in requests:
        raise ValueError("Missing/reused request ID")
    requests.add(request)
    ev["request_id"] = request
    data = response.get("data")
    if not isinstance(data, dict) or not isinstance(data.get("child_comments"), list):
        raise ValueError("Expected data.child_comments, not an empty-result fallback")
    page_ids = []
    for comment in data["child_comments"]:
        cid = ident(comment["pk"])
        page_ids.append(cid)
        if not isinstance(comment.get("text"), str):
            raise ValueError("Expected comment text")
        parent_id = ident(comment["parent_comment_id"])
        likes = count(comment.get("comment_like_count"))
        created = scalar(comment.get("created_at"))
        created_utc = scalar(comment.get("created_at_utc"))
        if cid in seen:
            continue
        seen.add(cid)
        rows.append({"media_id": media, "requested_root_id": root_id, "reply_id": cid, "parent_comment_id": parent_id, "text": comment["text"],
                     "likes": likes,
                     "created_at_raw": created,
                     "created_at_utc_raw": created_utc,
                     "request_id": request, "collected_at": entry["collected_at"], "source_page": index + 1})
    ev.update(returned_reply_objects=len(page_ids), reported_reply_count=count(data.get("child_comment_count")))
    page_info = data.get("page_info")
    more = data.get("has_more_tail_child_comments")
    cursor = page_info.get("next_min_id") if isinstance(page_info, dict) else None
    if not isinstance(more, bool):
        stop = "missing_more_flag"
    elif not more:
        stop = "provider_end"
    elif not page_ids:
        stop = "empty_page_with_more"
    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": {"media_id": media, "comment_id": root_id, "min_id": expected}} if stop == "saved_pages_exhausted" and len(entries) < 10 else None
if stop == "saved_pages_exhausted" and len(entries) == 10:
    stop = "helper_page_cap"
target.mkdir(exist_ok=False)
columns = ["media_id", "requested_root_id", "reply_id", "parent_comment_id", "text", "likes", "created_at_raw", "created_at_utc_raw", "request_id", "collected_at", "source_page"]
with (target / "replies.csv").open("x", encoding="utf-8-sig", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=columns)
    writer.writeheader()
    writer.writerows({k: safe(v) for k, v in row.items()} for row in rows)
for index, raw in enumerate(raw_pages):
    (target / ("raw-page-%02d.json" % (index + 1))).write_bytes(raw)
report = {"media_id": media, "requested_root_id": root_id, "unique_replies": len(rows),
          "root_request_id": root_row["request_id"], "root_sha256": root_page["sha256"],
          "stop_reason": stop, "all_replies_collected": False, "reply_coverage": "saved_reply_pages",
          "duplicate_policy": "first_observation_csv_all_observations_raw", "pages": evidence}
(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({"replies": len(rows), "stop": stop, "next_request_prepared": bool(next_request)}))
```

`replies.csv` 把 `requested_root_id` 和每条返回的 `parent_comment_id` 分开保存，因为回复的直接父评论不一定是请求的一级评论。每行保留原始回复 ID、正文、点赞数和原始时间戳。`coverage.json` 记录一级评论原页的哈希和为这条一级评论取到的回复页。复核时同时保留一级评论导出目录和回复目录。

回复分页通过 `data.page_info.next_min_id` 续页。响应元数据中可能同时包含 `next_min_child_cursor`，由于两个不同名字段不可互换，`instagram_replies.py` 不会用 `next_min_child_cursor` 代替。更多标记为 true 但缺少 `data.page_info.next_min_id` 时，脚本以 `missing_cursor` 停止，保留响应查证。游标正常时，`next-request.json` 写好同一媒体 ID、同一一级评论 ID 和游标，用于下一页收费请求。与一级评论相同，追加实际请求记录并导出到新目录。

审核每个问题时，把一级评论原文和 `replies.csv` 一起读，人工把 `resolution` 填为 answered、needs_context 或 no_answer_observed，并写上支持判断的回复 ID 和逐字原句。`provider_end` 只表示分页结束，不证明不存在隐藏或已删除的回复。整个流程不给评论者发消息。

## 标识符精度前提

超过 9007199254740991 的 JSON 裸数字按 float64 解码时会发生舍入，在到达 Python 脚本前就可能丢失精度，因此脚本拒绝超过 9007199254740991 的裸数字 ID，而原本以字符串返回的 ID 保持精确。不要给已经舍入的值加引号来“修复”：应停止本次导出，保存 request_id 查证。Python 大整数和表格文本格式都无法恢复已经舍入丢失的数字。

## 每个观测先校验，再去重

两个导出脚本在跳过重复 ID 之前，先校验计数、时间戳和返回的父评论 ID，所以后页的坏数据不会因为前页出现过同一 ID 而被跳过。合法的变化值仍按 CSV 保留首次观察值的规则处理；原始页保存每一次观察，CSV 不是合并后的最新状态。计数接受 0、安全范围内的非负整数和原始 ASCII 数字字符串；负值、缩写、布尔值或超出安全范围的裸数字会停止导出。缺失的计数留空。成功包装里同时带 error 时，脚本拒绝这份响应。

## 7. 把一个问题收口为有证据的人工审核结论

`replies.csv` 本身还不是产品支持结论。针对一条选定的一级评论，读一级评论和已保存的回复，再人工判断。只有拿得出已保存的回复 ID 和逐字匹配的支持原句时，才能用 `answered`。`needs_context` 表示已保存的证据不足；`no_answer_observed` 表示在已保存样本里没找到答案，不表示从来没有人回答。

用实际的一级评论 ID 和回复 ID 填写 `review.json`。下面的示例展示了 `review.json` 的预期格式：

```json
{"root_id":"11","decision":"answered","reply_id":"22","quote":"Open Settings","reviewer_note":"该回复提供了原问题所问的设置步骤，内容仍需产品负责人复核。"}
```

`no_answer_observed` 不填 `reply_id` 和 `quote`，在 `reviewer_note` 里写明审阅了哪些页。`needs_context` 可以附一条匹配的原句，也可以两个证据字段都不填。`resolve_question.py` 只检查证据能否对应到已保存的回复，不判断回复内容是否正确、建议是否有用。

把下面的脚本保存为 `resolve_question.py`，运行 `python3 resolve_question.py review-2 replies-1 review.json question-review`，把两个目录换成实际的一级评论导出目录和回复导出目录。输出的 `resolution.json` 包含选定的一级评论、人工判断、逐字原句及其来源、观察到的回复数和采集停止原因；`review-input.json` 保留原始人工输入。脚本不发 API 请求，也不回复评论者。

```python
import hashlib,json,pathlib,sys
roots,replies,review_path,out=map(pathlib.Path,sys.argv[1:5])
root_report=json.loads((roots/'coverage.json').read_text())
report=json.loads((replies/'coverage.json').read_text())
review_bytes=review_path.read_bytes();review=json.loads(review_bytes)
if not isinstance(review,dict):raise ValueError('Review must be an object')
for archive in (root_report,report):
    if not isinstance(archive,dict) or not isinstance(archive.get('pages'),list) or not 1<=len(archive['pages'])<=10:raise ValueError('Expected a bounded saved export')
def ident(x):
    if type(x) is int and 0 < x <= 9007199254740991:return str(x)
    if isinstance(x,str) and x.isascii() and x.isdigit() and any(c!='0' for c in x):return x
    raise ValueError('Expected an exact positive ID')
def load_page(folder,number,meta,action):
    raw=(folder/('raw-page-%02d.json'%number)).read_bytes()
    if hashlib.sha256(raw).hexdigest()!=meta.get('sha256'):raise ValueError('Changed source bytes')
    value=json.loads(raw)
    if not isinstance(value,dict) or value.get('action')!=action or value.get('status')!='succeeded' or value.get('error') is not None or value.get('request_id')!=meta.get('request_id') or not isinstance(value.get('request_id'),str) or not value['request_id'].strip():raise ValueError('Invalid saved response identity')
    return value
media=ident(report['media_id']);root_id=ident(report['requested_root_id'])
if ident(root_report['media_id'])!=media or ident(review['root_id'])!=root_id:raise ValueError('Mixed media/root')
root_matches=[]
for n,meta in enumerate(root_report['pages'],1):
    if meta.get('request_id')!=report.get('root_request_id'):continue
    value=load_page(roots,n,meta,'instagram.fetch_post_comments_v2')
    if ident(meta['params']['media_id'])!=media or meta['sha256']!=report.get('root_sha256'):raise ValueError('Wrong root source')
    for item in value['data']['comments']:
        if ident(item['pk'])==root_id:root_matches.append(item)
if not root_matches or not isinstance(root_matches[0].get('text'),str):raise ValueError('Missing root text')
if any(item.get('text')!=root_matches[0]['text'] for item in root_matches):raise ValueError('Conflicting root text in source page')
observed={};request_ids=set()
for n,meta in enumerate(report['pages'],1):
    if meta.get('http_status')!=200:raise ValueError('Resolve failed reply pages before final review')
    if ident(meta['params']['media_id'])!=media or ident(meta['params']['comment_id'])!=root_id:raise ValueError('Mixed reply request')
    value=load_page(replies,n,meta,'instagram.fetch_comment_replies')
    if value['request_id'] in request_ids:raise ValueError('Repeated response ID')
    request_ids.add(value['request_id'])
    items=value.get('data',{}).get('child_comments')
    if not isinstance(items,list):raise ValueError('Missing child comments')
    for item in items:
        key=ident(item['pk']);parent=ident(item['parent_comment_id']);text=item.get('text')
        if not isinstance(text,str):raise ValueError('Missing reply text')
        observed.setdefault(key,{'reply_id':key,'parent_comment_id':parent,'text':text,'request_id':value['request_id'],'source_sha256':meta['sha256'],'source_page':n})
if len(observed)!=report.get('unique_replies'):raise ValueError('Reply coverage count disagrees with source')
decision=review.get('decision');note=review.get('reviewer_note')
if decision not in ('answered','needs_context','no_answer_observed') or not isinstance(note,str) or not note.strip():raise ValueError('Supply manual decision and review note')
evidence=None
if decision in ('answered','needs_context') and review.get('reply_id') is not None:
    evidence=observed.get(ident(review['reply_id']));quote=review.get('quote')
    if evidence is None or not isinstance(quote,str) or not quote.strip() or quote not in evidence['text']:raise ValueError('Quote must match the saved reply exactly')
    evidence={k:v for k,v in evidence.items() if k!='text'};evidence['quote']=quote
elif decision=='answered':raise ValueError('Answered requires an exact reply quote')
elif review.get('reply_id') is not None or review.get('quote') not in (None,''):raise ValueError('No evidence must not carry an invented quote')
result={'media_id':media,'root_id':root_id,'root_text':root_matches[0]['text'],'decision':decision,'reviewer_note':note,'evidence':evidence,'observed_unique_replies':len(observed),'stop_reason':report['stop_reason'],'all_replies_collected':False,'root_source_sha256':report['root_sha256'],'review_sha256':hashlib.sha256(review_bytes).hexdigest(),'decision_source':'manual_review_not_automated_truth','scope':'Only supplied saved reply pages; no customer outreach or network call'}
out.mkdir();(out/'review-input.json').write_bytes(review_bytes);(out/'resolution.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
print(str(out))
```

`question-review` 目录作为私有工作资料保存，引用内容审阅后再对外分享。`resolve_question.py` 把引用原句与原始响应正文核对，不与防公式转义后的表格单元格核对。原始字节被改动、媒体 ID 或一级评论不对、ID 缺失、原句是编造的或覆盖数量不一致，都会让审核停止。本地哈希只证明文件前后一致，不是服务器签名。`answered` 是人工判断，不代表已验证购买、客服工单已解决或已取到全部回复。后续汇总时，不要把未审阅的一级评论算作未回答。