import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
if len(sys.argv) != 4 or sys.argv[1] not in {"list", "comments"}:
raise SystemExit("Usage: python3 channels_read.py list|comments VALUE NEW_DIRECTORY")
mode, value, directory = sys.argv[1:]
if not value.strip():
raise SystemExit("Supply a verified finder username or numeric work ID")
key = os.environ.get("BEATAPI_API_KEY")
if not key:
raise SystemExit("Set BEATAPI_API_KEY in your local environment")
if mode == "list":
action = "wechat_channels.v2.fetch_user_videos"
params = {"username": value, "last_buffer": "", "raw": False}
else:
action = "wechat_channels.v2.fetch_video_comments"
params = {"object_id": value, "comment_id": "", "last_buffer": "", "raw": False}
body = {"action": action, "params": params}
out = Path(directory)
out.mkdir(parents=True, exist_ok=False)
(out / "request.json").write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
started = datetime.now(timezone.utc).isoformat()
(out / "attempt.json").write_text(json.dumps({"started_at": started, "action": action}), encoding="utf-8")
request = Request("https://api.beatapi.io/v1/social-data/call",
data=json.dumps(body).encode("utf-8"), method="POST",
headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"})
try:
with urlopen(request, timeout=60) as response:
status, raw = response.status, response.read()
except HTTPError as error:
status, raw = error.code, error.read()
except URLError:
(out / "transport-error.json").write_text(json.dumps({"outcome": "unknown", "action": action}), encoding="utf-8")
raise SystemExit("No final response saved; review the attempted request before repeating")
(out / "response.json").write_bytes(raw)
(out / "call.json").write_text(json.dumps({"action": action, "params": params,
"http_status": status, "started_at": started,
"finished_at": datetime.now(timezone.utc).isoformat(),
"response_file": "response.json", "platform_review": "required"},
ensure_ascii=False, indent=2), encoding="utf-8")
try:
payload = json.loads(raw)
except (ValueError, UnicodeError):
raise SystemExit("Saved a non-JSON response; inspect response.json")
if status != 200 or not isinstance(payload, dict) or payload.get("status") != "succeeded" or payload.get("error") is not None or payload.get("action") != action:
raise SystemExit("Saved a failed or unexpected response; inspect response.json")
print("Saved response for platform-content review: " + str(out / "response.json"))