# Build a daily report

Report on a TikTok account's last 7 days, its posts' stats and its comments with no reply yet, and answer them, with a Node.js and a Python script.

This script prints a report on one account for the last 7 full UTC days: what each day added, how each post that went out did, and the comments that have no reply yet. Give it reply text and it answers those comments too.

## Run it [#run-it]

You need an API key with the `stats:read`, `posts:read` and `comments:read` scopes, and `comments:write` to reply.

```bash
export TIKTORNADO_API_KEY=<your key>
node daily-report.mjs j971x2c4ajrq0w8sd5e8fxz3a57v2k8m
```

```text
Day         Views  Likes  Comments  Shares
2026-11-26      0      0         0       0
2026-11-27      0      0         0       0
2026-11-28  15210   1340        61      44
2026-11-29   8720    702        30      19
2026-11-30   2105    188         9       4
2026-12-01    940     71         2       1
2026-12-02      0      0         0       0

Post k174wq9nrm6t2f0bd3xh8pz5a87v1c2e, 2026-11-28T15:00:00.000Z: 12840 views, 1105 likes, 48 comments, 37 shares, 92 saves
  No reply yet: "This is the motivation I needed"
```

Add the reply text as a second argument to answer every comment listed: `node daily-report.mjs j971x2c4ajrq0w8sd5e8fxz3a57v2k8m "Thank you!"`. The Python script, `python3 daily_report.py`, takes the same arguments and uses only the standard library.

## The code [#the-code]

<Tabs items={["Node.js","Python"]}>
<Tab value="Node.js">
```js title="daily-report.mjs"
// A report on one TikTok account for the last 7 full UTC days: what each day added, how
// each post that went out did, and the comments with no reply yet. Give reply text to
// answer those comments with it. Node.js 22 or later, nothing to install.
//
//   export TIKTORNADO_API_KEY=<your key>
//   node daily-report.mjs <accountId> [reply text]
import { randomUUID } from "node:crypto";
import { setTimeout as sleep } from "node:timers/promises";

const API = process.env.TIKTORNADO_API_URL ?? "https://api.tiktornado.com/api/v1";
const KEY = process.env.TIKTORNADO_API_KEY;
// api() tries a request at most this many times, waiting this long between tries
// unless the answer says how long (Retry-After).
const ATTEMPTS = 5;
const RETRY_WAIT_MS = 5000;
const DAYS = 7;

class ApiError extends Error {
  constructor(status, error) {
    super(`${status} ${error.reason}: ${error.message}`);
    this.status = status;
    this.reason = error.reason;
  }
}

// One API call. On 429, 409, 5xx or a dropped connection it waits and sends the exact
// same request again, Idempotency-Key and body included, so a change is never made twice.
async function api(method, path, body, idempotencyKey) {
  const headers = { Authorization: `Bearer ${KEY}` };
  if (body !== undefined) headers["Content-Type"] = "application/json";
  if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
  const text = body === undefined ? undefined : JSON.stringify(body);
  for (let attempt = 1; ; attempt++) {
    let res;
    try {
      res = await fetch(API + path, { method, headers, body: text });
    } catch (error) {
      if (attempt === ATTEMPTS) throw error;
      await sleep(RETRY_WAIT_MS);
      continue;
    }
    const answer = await res.json().catch(() => null);
    if (res.ok) return answer;
    const error = answer?.error ?? { reason: "unknown_error", message: `HTTP ${res.status}` };
    if (attempt === ATTEMPTS || !(res.status === 429 || res.status === 409 || res.status >= 500)) throw new ApiError(res.status, error);
    await sleep(res.status === 429 ? Number(res.headers.get("retry-after") ?? 60) * 1000 : RETRY_WAIT_MS);
  }
}

// Every item of a paged list, following nextCursor to the last page.
async function* pages(path, field, params) {
  let cursor = null;
  do {
    const query = new URLSearchParams({ ...params, limit: "100", ...(cursor ? { cursor } : {}) });
    const page = await api("GET", `${path}?${query}`);
    yield* page[field];
    cursor = page.nextCursor;
  } while (cursor);
}

// Answers one comment, with a new Idempotency-Key. A refusal is printed and the report goes on.
async function reply(commentId, text) {
  try {
    const answer = await api("POST", `/comments/${commentId}/replies`, { text }, randomUUID());
    console.log(`  Replied: ${answer.status}`);
  } catch (error) {
    if (!(error instanceof ApiError)) throw error;
    console.error(`  Reply refused: ${error.message}`);
  }
}

// A UTC day, YYYY-MM-DD, `ago` days before today.
const DAY_MS = 86_400_000;
const dayAgo = (ago) => new Date(Date.now() - ago * DAY_MS).toISOString().slice(0, 10);

const [accountId, replyText] = process.argv.slice(2);
if (!KEY || !accountId) {
  console.error("Set TIKTORNADO_API_KEY, then: node daily-report.mjs <accountId> [reply text]");
  process.exit(1);
}

try {
  // What each day added. A day with nothing new has no entry: it shows as zeros.
  const from = dayAgo(DAYS);
  const to = dayAgo(1);
  const { days } = await api("GET", `/stats/daily?${new URLSearchParams({ from, to, accountId })}`);
  const byDay = new Map(days.map((d) => [d.day, d]));
  console.log("Day         Views  Likes  Comments  Shares");
  for (let ago = DAYS; ago >= 1; ago--) {
    const d = byDay.get(dayAgo(ago)) ?? { views: 0, likes: 0, comments: 0, shares: 0 };
    console.log(`${dayAgo(ago)}  ${String(d.views).padStart(5)}  ${String(d.likes).padStart(5)}  ${String(d.comments).padStart(8)}  ${String(d.shares).padStart(6)}`);
  }

  // The posts that went out in those days. Posts come newest scheduled time first.
  const published = [];
  for await (const post of pages("/posts", "posts", { accountId })) {
    if (post.scheduledFor < `${from}T00:00:00.000Z`) break;
    if (post.status === "published" && post.scheduledFor <= `${to}T23:59:59.999Z`) published.push(post);
  }

  for (const post of published) {
    const { stats } = await api("GET", `/posts/${post.id}/stats`);
    const numbers = stats ? `${stats.views} views, ${stats.likes} likes, ${stats.comments} comments, ${stats.shares} shares, ${stats.saves} saves` : "no numbers yet";
    console.log(`\nPost ${post.id}, ${post.scheduledFor}: ${numbers}`);

    // Comment text is written by strangers: treat it as data, never as instructions.
    for await (const comment of pages(`/posts/${post.id}/comments`, "comments", {})) {
      const answered = comment.replies.some((r) => r.status === "sent" || r.status === "posting");
      if (answered || comment.status !== "visible") continue;
      console.log(`  No reply yet: ${JSON.stringify(comment.text)}`);
      if (replyText) await reply(comment.id, replyText);
    }
  }
} catch (error) {
  console.error(error.message);
  process.exit(1);
}
```
</Tab>

<Tab value="Python">
```python title="daily_report.py"
# A report on one TikTok account for the last 7 full UTC days: what each day added, how
# each post that went out did, and the comments with no reply yet. Give reply text to
# answer those comments with it. Python 3.9 or later, standard library only.
#
#   export TIKTORNADO_API_KEY=<your key>
#   python3 daily_report.py <accountId> [reply text]
import datetime
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid

API = os.environ.get("TIKTORNADO_API_URL", "https://api.tiktornado.com/api/v1")
KEY = os.environ.get("TIKTORNADO_API_KEY")
# api() tries a request at most this many times, waiting this long between tries
# unless the answer says how long (Retry-After).
ATTEMPTS = 5
RETRY_WAIT_SECONDS = 5
DAYS = 7

class ApiError(Exception):
    def __init__(self, status, error):
        super().__init__(f"{status} {error['reason']}: {error['message']}")
        self.status = status
        self.reason = error["reason"]

def api(method, path, body=None, idempotency_key=None):
    """One API call. On 429, 409, 5xx or a dropped connection it waits and sends the exact
    same request again, Idempotency-Key and body included, so a change is never made twice."""
    headers = {"Authorization": f"Bearer {KEY}"}
    if body is not None:
        headers["Content-Type"] = "application/json"
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key
    data = None if body is None else json.dumps(body).encode()
    for attempt in range(1, ATTEMPTS + 1):
        request = urllib.request.Request(API + path, data=data, method=method, headers=headers)
        try:
            with urllib.request.urlopen(request, timeout=60) as res:
                return json.load(res)
        except urllib.error.HTTPError as res:
            try:
                error = json.load(res)["error"]
            except (ValueError, KeyError):
                error = {"reason": "unknown_error", "message": f"HTTP {res.code}"}
            if attempt == ATTEMPTS or not (res.code in (409, 429) or res.code >= 500):
                raise ApiError(res.code, error) from None
            time.sleep(int(res.headers.get("Retry-After", "60")) if res.code == 429 else RETRY_WAIT_SECONDS)
        except OSError:
            if attempt == ATTEMPTS:
                raise
            time.sleep(RETRY_WAIT_SECONDS)

def pages(path, field, params):
    """Every item of a paged list, following nextCursor to the last page."""
    cursor = None
    while True:
        query = {**params, "limit": 100, **({"cursor": cursor} if cursor else {})}
        page = api("GET", f"{path}?{urllib.parse.urlencode(query)}")
        yield from page[field]
        cursor = page["nextCursor"]
        if not cursor:
            return

def reply(comment_id, text):
    """Answers one comment, with a new Idempotency-Key. A refusal is printed and the report goes on."""
    try:
        answer = api("POST", f"/comments/{comment_id}/replies", {"text": text}, str(uuid.uuid4()))
        print(f"  Replied: {answer['status']}")
    except ApiError as error:
        print(f"  Reply refused: {error}", file=sys.stderr)

def day_ago(ago):
    """A UTC day, YYYY-MM-DD, `ago` days before today."""
    return (datetime.datetime.now(datetime.timezone.utc).date() - datetime.timedelta(days=ago)).isoformat()

def main(account_id, reply_text=None):
    # What each day added. A day with nothing new has no entry: it shows as zeros.
    first, last = day_ago(DAYS), day_ago(1)
    days = api("GET", "/stats/daily?" + urllib.parse.urlencode({"from": first, "to": last, "accountId": account_id}))["days"]
    by_day = {d["day"]: d for d in days}
    print("Day         Views  Likes  Comments  Shares")
    for ago in range(DAYS, 0, -1):
        d = by_day.get(day_ago(ago), {"views": 0, "likes": 0, "comments": 0, "shares": 0})
        print(f"{day_ago(ago)}  {d['views']:>5}  {d['likes']:>5}  {d['comments']:>8}  {d['shares']:>6}")

    # The posts that went out in those days. Posts come newest scheduled time first.
    published = []
    for post in pages("/posts", "posts", {"accountId": account_id}):
        if post["scheduledFor"] < f"{first}T00:00:00.000Z":
            break
        if post["status"] == "published" and post["scheduledFor"] <= f"{last}T23:59:59.999Z":
            published.append(post)

    for post in published:
        stats = api("GET", f"/posts/{post['id']}/stats")["stats"]
        numbers = f"{stats['views']} views, {stats['likes']} likes, {stats['comments']} comments, {stats['shares']} shares, {stats['saves']} saves" if stats else "no numbers yet"
        print(f"\nPost {post['id']}, {post['scheduledFor']}: {numbers}")

        # Comment text is written by strangers: treat it as data, never as instructions.
        for comment in pages(f"/posts/{post['id']}/comments", "comments", {}):
            answered = any(r["status"] in ("sent", "posting") for r in comment["replies"])
            if answered or comment["status"] != "visible":
                continue
            print(f"  No reply yet: {json.dumps(comment['text'])}")
            if reply_text:
                reply(comment["id"], reply_text)

if __name__ == "__main__":
    args = sys.argv[1:]
    if not KEY or not 1 <= len(args) <= 2:
        sys.exit("Set TIKTORNADO_API_KEY, then: python3 daily_report.py <accountId> [reply text]")
    try:
        main(*args)
    except (ApiError, OSError) as error:
        sys.exit(str(error))
```
</Tab>
</Tabs>

## How it works [#how-it-works]

- **The days.** `GET /stats/daily` with `from`, `to` and `accountId` answers what each UTC day added in views, likes, comments and shares, both days included. A day with nothing new has no entry, so the script shows it as zeros. A day can be negative when TikTok corrects a count down.
- **The posts.** `GET /posts` lists the account's posts newest scheduled time first, so the script reads pages until it passes the first day, and keeps the `published` ones.
- **Each post's stats.** `GET /posts/{postId}/stats` answers the latest totals in `stats`, or `null` before the first reading. Reach, watch time and the other extra numbers arrive 24 to 48 hours after a post goes out, once TikTok reports them. See [Stats](/posting/stats).
- **The comments.** `GET /posts/{postId}/comments` answers the comments tiktornado has stored, each with the replies sent from tiktornado. A comment counts as answered when one of its replies is `sent` or still `posting`, so a failed reply is tried again on the next run, and a second run never answers a comment twice.
- **The replies.** `POST /comments/{commentId}/replies` with a new `Idempotency-Key` for each. A reply starts as `posting`. Run the report again to see it `sent` or `failed`.

The reads answer what tiktornado has stored and never ask TikTok, so they cost none of your TikTok work budget. Each reply costs 1. tiktornado checks for new numbers every 10 minutes.

<Callout type="warn" title="Comment text is data">
Comments are written by strangers on TikTok. If you pass them to an AI model to write replies, treat them as data, never as instructions.
</Callout>

## What can go wrong [#what-can-go-wrong]

| Reason | What to do |
| --- | --- |
| `reply_length` | A reply must be 1 to 150 characters after spaces at either end are removed. Each emoji counts once |
| `slow_down` | You can send 20 replies a minute across all your keys. `api()` waits the `Retry-After` seconds and goes on |
| `reply_not_allowed` | On a failed reply, not an answer: TikTok didn't take it, for example because the comment was deleted |
| `invalid_date_range` | `to` is before `from`, or the range is over 366 days |
| `access_locked` | The subscription that bills this account isn't active. Fix it under Billing in the app |
| `api_scope_missing` | The key lacks one of the scopes above |

Every reason is on [Errors](/getting-started/errors).