# Post to many accounts

Upload a video once and schedule it on several TikTok accounts, with safe retries through the Idempotency-Key header and a wait on every 429.

One upload can go out on as many of your accounts as you like: a `mediaRef` works on any account you own, not only the one you named when you asked for the link. This script uploads a video once, then schedules one post per account at the same time, and retries each one safely when it is told to slow down.

## Run it [#run-it]

You need an API key with the `posts:write` scope and the `id` of each account (from `GET /accounts`).

```bash
export TIKTORNADO_API_KEY=<your key>
node post-to-many-accounts.mjs leg-day.mp4 2026-12-02T15:00:00Z "Leg day, no excuses #fitness" \
  j971x2c4ajrq0w8sd5e8fxz3a57v2k8m j975bq1hkz8d3w0xn6c2tfr4p87v9m5a
```

It prints one line per account, and exits with an error if any account's post was refused:

```text
j971x2c4ajrq0w8sd5e8fxz3a57v2k8m: saved post k174wq9nrm6t2f0bd3xh8pz5a87v1c2e for 2026-12-02T15:00:00.000Z
j975bq1hkz8d3w0xn6c2tfr4p87v9m5a: 400 daily_limit_reached: This account has hit TikTok's daily posting limit. Pick a later time.
```

The Python script takes the same arguments: `python3 post_to_many_accounts.py`. It uses only the standard library.

## The code [#the-code]

<Tabs items={["Node.js","Python"]}>
<Tab value="Node.js">
```js title="post-to-many-accounts.mjs"
// Upload one video once and schedule it on several TikTok accounts at the same time.
// Node.js 22 or later, nothing to install.
//
//   export TIKTORNADO_API_KEY=<your key>
//   node post-to-many-accounts.mjs <video> <time> <caption> <accountId> [accountId ...]
//
// <time> is ISO 8601 with a time zone, more than 10 minutes ahead: 2026-12-02T15:00:00Z
import { randomUUID } from "node:crypto";
import { openAsBlob } from "node:fs";
import { basename, extname } from "node:path";
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 VIDEO_TYPES = { ".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm" };

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);
  }
}

const [file, scheduledFor, caption, ...accountIds] = process.argv.slice(2);
const contentType = VIDEO_TYPES[extname(file ?? "").toLowerCase()];
if (!KEY || !file || !scheduledFor || caption === undefined || accountIds.length === 0 || !contentType) {
  console.error("Set TIKTORNADO_API_KEY, then: node post-to-many-accounts.mjs <video.mp4|.mov|.webm> <time> <caption> <accountId> [accountId ...]");
  process.exit(1);
}

try {
  // One upload for every account: a mediaRef works on any of your accounts.
  const video = await openAsBlob(file);
  const link = await api("POST", "/uploads", { accountId: accountIds[0], filename: basename(file), contentType, size: video.size });
  const upload = await fetch(link.uploadUrl, { method: link.method, headers: link.headers, body: video });
  if (!upload.ok) throw new Error(`The upload failed with HTTP ${upload.status}. Ask for a new link and try again.`);

  // One post per account, one after another, each with its own Idempotency-Key.
  let refused = 0;
  for (const accountId of accountIds) {
    const body = { accountId, kind: "video", caption, mediaRefs: [link.mediaRef], scheduledFor };
    try {
      const post = await api("POST", "/posts", body, randomUUID());
      console.log(`${accountId}: saved post ${post.id} for ${post.scheduledFor}`);
    } catch (error) {
      if (!(error instanceof ApiError)) throw error;
      // A refusal is about this account's post: report it and go on with the others.
      console.error(`${accountId}: ${error.message}`);
      refused++;
    }
  }
  if (refused > 0) process.exit(1);
} catch (error) {
  console.error(error.message);
  process.exit(1);
}
```
</Tab>

<Tab value="Python">
```python title="post_to_many_accounts.py"
# Upload one video once and schedule it on several TikTok accounts at the same time.
# Python 3.9 or later, standard library only.
#
#   export TIKTORNADO_API_KEY=<your key>
#   python3 post_to_many_accounts.py <video> <time> <caption> <accountId> [accountId ...]
#
# <time> is ISO 8601 with a time zone, more than 10 minutes ahead: 2026-12-02T15:00:00Z
import json
import os
import sys
import time
import urllib.error
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
VIDEO_TYPES = {".mp4": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm"}

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 main(path, scheduled_for, caption, account_ids):
    content_type = VIDEO_TYPES[os.path.splitext(path)[1].lower()]
    size = os.path.getsize(path)

    # One upload for every account: a mediaRef works on any of your accounts.
    link = api("POST", "/uploads", {"accountId": account_ids[0], "filename": os.path.basename(path), "contentType": content_type, "size": size})
    with open(path, "rb") as video:
        headers = {**link["headers"], "Content-Length": str(size)}
        urllib.request.urlopen(urllib.request.Request(link["uploadUrl"], data=video, method=link["method"], headers=headers), timeout=600).close()

    # One post per account, one after another, each with its own Idempotency-Key.
    refused = 0
    for account_id in account_ids:
        body = {"accountId": account_id, "kind": "video", "caption": caption, "mediaRefs": [link["mediaRef"]], "scheduledFor": scheduled_for}
        try:
            post = api("POST", "/posts", body, str(uuid.uuid4()))
            print(f"{account_id}: saved post {post['id']} for {post['scheduledFor']}")
        except ApiError as error:
            # A refusal is about this account's post: report it and go on with the others.
            print(f"{account_id}: {error}", file=sys.stderr)
            refused += 1
    return 1 if refused else 0

if __name__ == "__main__":
    args = sys.argv[1:]
    if not KEY or len(args) < 4 or os.path.splitext(args[0])[1].lower() not in VIDEO_TYPES:
        sys.exit("Set TIKTORNADO_API_KEY, then: python3 post_to_many_accounts.py <video.mp4|.mov|.webm> <time> <caption> <accountId> [accountId ...]")
    try:
        sys.exit(main(args[0], args[1], args[2], args[3:]))
    except (ApiError, OSError) as error:
        sys.exit(str(error))
```
</Tab>
</Tabs>

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

- **One upload.** The upload link is asked for with the first account, and its `mediaRef` goes into every post.
- **One post per account.** Each account gets its own `POST /posts` with its own `Idempotency-Key`. A refusal for one account is printed and the others still go out.
- **One after another.** Posts for different accounts may also be sent in parallel. Posts for the same account are best sent one at a time. See [Several requests at once](/getting-started/rate-limits#several-requests-at-once).

## Safe retries [#safe-retries]

`api()` builds each request's body once and keeps its `Idempotency-Key`, then resends exactly that on:

| Answer | Why it is safe to resend |
| --- | --- |
| `429` `slow_down` | It waits the seconds in `Retry-After`. A `429` is never stored under the key, so the retry runs for real |
| `409` `idempotency_in_progress` | The first request is still running. The retry gets its answer once it is done |
| `500` `unknown_error`, `503` `service_unavailable` | Not stored either. The same key makes sure the post is saved at most once |
| A dropped connection or a timeout | If the first request was saved, the retry gets its answer back with `Idempotent-Replayed: true`. If not, it is saved now |

Resend the same bytes, not the same object rebuilt: the same fields in another order count as a different body, and the key then answers `422` `idempotency_key_reused`. A `400` or `404` is stored under its key: fix the request and send it with a new key. See [Safe retries](/getting-started/idempotency).

## How fast it goes [#how-fast-it-goes]

Each post with one video costs 4 of the 60 units of TikTok work you have a minute, so about 15 posts a minute go through before `slow_down`. The upload link costs 1 more. `Retry-After` is always `60`, and every limit refills within a minute, so the script carries on after a pause. See [Rate limits](/getting-started/rate-limits).

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

| Reason | What to do |
| --- | --- |
| `daily_limit_reached` | That account already has 15 videos in some 24 hours around the time. Pick another time for it |
| `access_locked` | The subscription that bills that account isn't active. Fix it under Billing in the app. Your other accounts keep working |
| `account_not_ready`, `invalid_state` | That account can't take posts right now. Check its status with `GET /accounts` |
| `not_found` | The account id is wrong, or the account isn't yours |
| `schedule_too_soon` | The time is 10 minutes or less away. Every post is refused, since they all share it |
| `idempotency_key_reused` | The body changed between two sends with one key. Keep the text you built the first time |

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