# Fill a posting queue

Give a TikTok account weekly posting times, preview its next free time, and add videos to its queue, with a Node.js and a Python script.

A queue saves you picking a time for every post. Give an account weekly posting times once, then send each post with `queue: true`: it takes the next free time. This script sets Monday, Wednesday and Friday at 9:00, shows the next free time, and queues each video you give it.

## Run it [#run-it]

You need an API key with the `posts:write` and `accounts:read` scopes. Each video is a `mediaRef` from an upload (see [Upload a video and schedule it](/guides/upload-and-schedule)) or a public `https` link straight to the file.

```bash
export TIKTORNADO_API_KEY=<your key>
node fill-queue.mjs j971x2c4ajrq0w8sd5e8fxz3a57v2k8m America/New_York \
  https://media.example.com/uploads/5ac3e8/tips.mp4 \
  https://media.example.com/uploads/5ac3e8/tips-2.mp4
```

```text
Posting times set in America/New_York
Next free time for a video: 2026-12-02T14:00:00.000Z
https://media.example.com/uploads/5ac3e8/tips.mp4: post k174wq9nrm6t2f0bd3xh8pz5a87v1c2e at 2026-12-02T14:00:00.000Z
```

Change `SLOTS` at the top of the script to your own times. The Python script, `python3 fill_queue.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="fill-queue.mjs"
// Give a TikTok account weekly posting times, then add videos to its queue: each one
// takes the next free time. Node.js 22 or later, nothing to install.
//
//   export TIKTORNADO_API_KEY=<your key>
//   node fill-queue.mjs <accountId> <time zone> <video> [video ...]
//
// <time zone> is an IANA name such as America/New_York. Each <video> is a mediaRef from
// an upload, or a public https link straight to the file.
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;
// Monday, Wednesday and Friday at 9:00. day: 0 is Monday, 6 is Sunday. minute: after midnight.
const SLOTS = [
  { day: 0, minute: 9 * 60 },
  { day: 2, minute: 9 * 60 },
  { day: 4, minute: 9 * 60 },
];

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 [accountId, timeZone, ...videos] = process.argv.slice(2);
if (!KEY || !accountId || !timeZone || videos.length === 0) {
  console.error("Set TIKTORNADO_API_KEY, then: node fill-queue.mjs <accountId> <time zone> <video> [video ...]");
  process.exit(1);
}

try {
  // Replaces all of the account's posting times. Posts already scheduled keep theirs.
  const times = await api("PUT", `/accounts/${accountId}/queue`, { timeZone, slots: SLOTS }, randomUUID());
  console.log(`Posting times set in ${times.timeZone}`);

  // Only a preview: nothing is held, the time is picked again when each post is saved.
  const next = await api("GET", `/accounts/${accountId}/queue/next?kind=video`);
  console.log(`Next free time for a video: ${next.scheduledFor}`);

  // One after another: queued posts to one account are best sent one at a time.
  for (const video of videos) {
    const post = await api("POST", "/posts", { accountId, kind: "video", mediaRefs: [video], queue: true }, randomUUID());
    console.log(`${video}: post ${post.id} at ${post.scheduledFor}`);
  }
} catch (error) {
  // queue_full: no free time in the next 4 weeks. Add times, or schedule the rest by hand.
  console.error(error.message);
  process.exit(1);
}
```
</Tab>

<Tab value="Python">
```python title="fill_queue.py"
# Give a TikTok account weekly posting times, then add videos to its queue: each one
# takes the next free time. Python 3.9 or later, standard library only.
#
#   export TIKTORNADO_API_KEY=<your key>
#   python3 fill_queue.py <accountId> <time zone> <video> [video ...]
#
# <time zone> is an IANA name such as America/New_York. Each <video> is a mediaRef from
# an upload, or a public https link straight to the file.
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
# Monday, Wednesday and Friday at 9:00. day: 0 is Monday, 6 is Sunday. minute: after midnight.
SLOTS = [
    {"day": 0, "minute": 9 * 60},
    {"day": 2, "minute": 9 * 60},
    {"day": 4, "minute": 9 * 60},
]

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(account_id, time_zone, videos):
    # Replaces all of the account's posting times. Posts already scheduled keep theirs.
    times = api("PUT", f"/accounts/{account_id}/queue", {"timeZone": time_zone, "slots": SLOTS}, str(uuid.uuid4()))
    print(f"Posting times set in {times['timeZone']}")

    # Only a preview: nothing is held, the time is picked again when each post is saved.
    upcoming = api("GET", f"/accounts/{account_id}/queue/next?kind=video")
    print(f"Next free time for a video: {upcoming['scheduledFor']}")

    # One after another: queued posts to one account are best sent one at a time.
    for video in videos:
        post = api("POST", "/posts", {"accountId": account_id, "kind": "video", "mediaRefs": [video], "queue": True}, str(uuid.uuid4()))
        print(f"{video}: post {post['id']} at {post['scheduledFor']}")

if __name__ == "__main__":
    args = sys.argv[1:]
    if not KEY or len(args) < 3:
        sys.exit("Set TIKTORNADO_API_KEY, then: python3 fill_queue.py <accountId> <time zone> <video> [video ...]")
    try:
        main(args[0], args[1], args[2:])
    except (ApiError, OSError) as error:
        # queue_full: no free time in the next 4 weeks. Add times, or schedule the rest by hand.
        sys.exit(str(error))
```
</Tab>
</Tabs>

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

- **The times.** `PUT /accounts/{accountId}/queue` replaces all of the account's times with `SLOTS`. Each is a weekday (`day`, 0 for Monday through 6 for Sunday) and a time of day (`minute` after midnight, 540 for 9:00) in the time zone you name, so 9:00 stays 9:00 when the clocks change. Posts already scheduled keep their times.
- **The preview.** `GET /accounts/{accountId}/queue/next?kind=video` answers the time a video would get right now. Nothing is held: each post's time is picked again when it is saved.
- **The posts.** `POST /posts` with `queue: true` and no `scheduledFor`. The answer's `scheduledFor` is the time the post got. From then on it is an ordinary scheduled post: edit, move or cancel it like any other.
- **One at a time.** Queued posts to one account are sent one after another. Two sent at once still get different times, but they slow each other down.

A time is free when no other live post of the account is in that minute, it is more than 10 minutes away, it is before the account ends, and that kind's daily limit has room. The full rules, daylight saving included, are on [Posting queues](/posting/posting-queues).

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

| Reason | What to do |
| --- | --- |
| `invalid_queue` | A time zone that isn't an IANA name such as `America/New_York` (offsets such as `+05:00` aren't taken), a `day` or `minute` out of range, the same time twice, or more than 15 times on one day |
| `queue_full` | No time is free in the next 4 weeks. Add more times, or give the rest a `scheduledFor`. The script stops at the first refusal |
| `queue_empty` | The account has no posting times. Set them first |
| `account_not_ready`, `invalid_state` | The account can't take posts right now, so its times can't be set either |
| `api_scope_missing` | The key needs `posts:write` to set times and post, and `accounts:read` for the next free time |

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