"""Python 3.9+ | Set APIFY_TOKEN locally, then run: python tiktok_report.py @duolingo""" import argparse import http.client import json import os import random import re import sys import time ACTOR = "solidscrape~tiktok-save-share-benchmark" ACTIVE = {"READY", "RUNNING", "TIMING-OUT", "ABORTING"} def request(method, path, body=None): # One HTTPS request per call. Never automatically replay a paid launch. conn = http.client.HTTPSConnection("api.apify.com", timeout=45) try: conn.request(method, "/v2/" + path, body=json.dumps(body) if body is not None else None, headers={"Authorization": "Bearer " + os.environ["APIFY_TOKEN"], "Content-Type": "application/json"}) response = conn.getresponse() return response.status, json.loads(response.read()) finally: conn.close() def launch(profile): deadline = time.monotonic() + 120 delay = 3 while True: status, payload = request("POST", f"acts/{ACTOR}/runs?maxTotalChargeUsd=0.49", {"profile": profile}) if status == 201: return payload["data"]["id"] error = payload.get("error", {}) if error.get("type") != "concurrent-runs-limit-exceeded": raise RuntimeError(f"Launch response {status}: {error.get('message', 'unexpected response')}") remaining = deadline - time.monotonic() if remaining <= 0: raise RuntimeError("No slot became available within two minutes. No run was accepted.") wait = min(remaining, delay + random.random()) print(f"Launch refused: all slots busy. Retrying in {wait:.1f}s.", file=sys.stderr, flush=True) time.sleep(wait) delay = min(delay * 2, 15) def read(path): status, data = request("GET", path) if status != 200: raise RuntimeError(f"Read failed ({status}): {data.get('error', {}).get('message')}") return data def main(): parser = argparse.ArgumentParser(description="Get one TikTok profile report as JSON.") target = parser.add_mutually_exclusive_group(required=True) target.add_argument("profile", nargs="?", help="public TikTok handle") target.add_argument("--resume", metavar="RUN_ID", help="read an existing run without starting another") args = parser.parse_args() if not os.environ.get("APIFY_TOKEN"): parser.error("Set APIFY_TOKEN in your environment.") run_id = args.resume if run_id and not re.fullmatch(r"[A-Za-z0-9]+", run_id): parser.error("Expected an Apify run ID.") if not run_id: try: run_id = launch(args.profile) except (OSError, http.client.HTTPException, ValueError, KeyError) as exc: raise RuntimeError("Launch outcome unknown. Check Apify Console > Runs for a run ID " "and use --resume before submitting another request.") from exc print(f"Run ID: {run_id}. To reconnect: python tiktok_report.py --resume {run_id}", file=sys.stderr, flush=True) while True: run = read(f"actor-runs/{run_id}?waitForFinish=20")["data"] if run["status"] not in ACTIVE: break time.sleep(1) if run["status"] != "SUCCEEDED": raise RuntimeError(f"Run {run_id} ended with {run['status']}. Check its log in Console.") rows = read(f"datasets/{run['defaultDatasetId']}/items?limit=2") if len(rows) != 1: raise RuntimeError(f"Expected one report, received {len(rows)}.") print(json.dumps(rows[0], ensure_ascii=True, indent=2)) if __name__ == "__main__": try: main() except (RuntimeError, OSError, http.client.HTTPException, ValueError, KeyError) as exc: sys.exit(str(exc))