tuita

Bots & API

Build bots, scripts and integrations for ⁨tuita⁩

Build for ⁨tuita⁩

Everything the tuita apps do goes through a small JSON API, and bots and scripts can use it too. You need an account on ⁨tuita⁩ and a personal API token. There’s no app registration and no OAuth dance.

  1. Create an account for your bot, or use your own.
  2. In Settings, Bots & API, turn on “This is an automated account” so people see an “Automated” label, and say who runs it.
  3. Create a token with the scopes you need and keep it secret.

Authentication

Send the token in the Authorization header. Every request and response is JSON (UTF-8), except uploads, which are multipart.

curl https://tuita.chiko.dev/api/v1/me \
  -H "Authorization: Bearer tuita_your_token"

A token is tuita_ followed by 43 letters, digits, dashes and underscores. Only a hash is stored, so a lost token can’t be shown again: make a new one. A token has one or more of these scopes:

  • read: Timelines, notifications, profiles, search and the realtime stream
  • write: Posting, deleting, likes, reposts, bookmarks, follows and uploads
  • messages: Reading and sending direct messages

A token can’t change passwords, sessions, tokens or passkeys, can’t export or delete the account, and can’t use the admin API. Those need a real sign-in on the website and answer 403.

Errors come back as JSON with an error message and a 4xx status. 401 means the token is wrong or revoked, 403 a missing scope or a refused route, and 429 comes with a Retry-After header.

Your first post

curl https://tuita.chiko.dev/api/v1/posts \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"text": "Hello from my bot", "cw": "", "sensitive": false, "mediaIds": []}'

Upload images and video first with POST /api/v1/media (multipart), then attach them by id in mediaIds. A reply sets replyTo, a quote sets quoteOf.

Endpoints

Paths in curly braces are placeholders. Lists page with ?before= set to the next value of the previous page; limit is 1 to 40. The scope column is the scope a token needs.

MethodPathScopeWhat it does
GET/api/v1/mereadThe account the token belongs to
PATCH/api/v1/mewriteChange the profile and settings of that account
PATCH/api/v1/me/botwriteTurn the “Automated” label on or off and name the person who runs the bot
GET/api/v1/timelines/followingreadThe home timeline of the people you follow
GET/api/v1/timelines/foryoureadThe For you timeline; page with ?cursor=
GET/api/v1/notificationsreadNotifications (?filter=mentions for replies, mentions and quotes)
GET/api/v1/posts/{id}readA post with its thread and replies
GET/api/v1/users/{handle}readA profile (handle@domain for accounts on other servers)
GET/api/v1/users/{handle}/postsreadSomeone’s posts (?tab=replies, media or likes; with media, ?kind=photo or video)
GET/api/v1/searchreadSearch posts, people or media, with operators like from: and has:media
GET/api/v1/trendsreadThe tags used most in the last week
GET/api/v1/streamreadRealtime events (Server-Sent Events)
POST/api/v1/postswriteWrite a post
POST/api/v1/posts/threadwriteWrite 2 to 25 posts as a thread
DELETE/api/v1/posts/{id}writeDelete one of your posts
POST/api/v1/posts/{id}/likewriteLike a post (DELETE to undo). Also /repost and /bookmark
POST/api/v1/users/{handle}/followwriteFollow someone (DELETE to unfollow)
POST/api/v1/mediawriteUpload an image or video as multipart; the answer holds the id to attach
POST/api/v1/scheduledwriteSchedule a post for later
POST/api/v1/reportswriteReport a post or an account to the moderators
GET/api/v1/conversationsmessagesYour direct message conversations
POST/api/v1/conversations/{handle}messagesSend a direct message; the body is JSON with a text field

Realtime events

GET /api/v1/stream is a Server-Sent Events stream. It sends a notification event for every like, repost, follow, reply, mention or quote, a message event for direct messages and badges with unread counts. It sends a comment line every 25 seconds and asks clients to retry after 5 seconds; reconnect if the connection drops.

event: notification
data: {"type":"notification","data":{"kind":"mention","actor":{"handle":"ana"},"post":{"id":"0193…","text":"@mybot hi!"}}}

Example: a bot that answers mentions

Node 22 or newer, no packages:

// Run with: INSTANCE=https://tuita.chiko.dev TOKEN=tuita_… node echo-bot.mjs
const { INSTANCE, TOKEN } = process.env;
const headers = { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' };

async function reply(post, handle) {
  const text = `@${handle} you said: ${post.text.replace(/@\w+/g, '').trim()}`;
  await fetch(`${INSTANCE}/api/v1/posts`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ text, cw: '', sensitive: false, replyTo: post.id, mediaIds: [] })
  });
}

for (;;) {
  const res = await fetch(`${INSTANCE}/api/v1/stream`, { headers });
  let buffer = '';
  for await (const chunk of res.body.pipeThrough(new TextDecoderStream())) {
    buffer += chunk;
    let end;
    while ((end = buffer.indexOf('\n\n')) >= 0) {
      const block = buffer.slice(0, end);
      buffer = buffer.slice(end + 2);
      const event = /^event: (.*)$/m.exec(block)?.[1];
      const data = /^data: (.*)$/m.exec(block)?.[1];
      if (event !== 'notification' || !data) continue;
      const { data: n } = JSON.parse(data);
      if (n.kind === 'mention' && n.post) await reply(n.post, n.actor.handle);
    }
  }
  await new Promise((r) => setTimeout(r, 5000)); // reconnect
}

The same in Python, using only requests:

import json, os, requests
base, token = os.environ["INSTANCE"], os.environ["TOKEN"]
h = {"Authorization": f"Bearer {token}"}
with requests.get(f"{base}/api/v1/stream", headers=h, stream=True) as r:
    event = None
    for line in r.iter_lines(decode_unicode=True):
        if line.startswith("event: "):
            event = line[7:]
        elif line.startswith("data: ") and event == "notification":
            n = json.loads(line[6:])["data"]
            if n["kind"] == "mention" and n.get("post"):
                requests.post(f"{base}/api/v1/posts", headers=h, json={
                    "text": f"@{n['actor']['handle']} hello!", "cw": "",
                    "sensitive": False, "replyTo": n["post"]["id"], "mediaIds": []})

Limits

  • Each token may make 600 requests per 10 minutes. Over the limit the server answers 429 with a Retry-After header.
  • An account can have up to 20 tokens and create up to 20 tokens per hour.
  • Posting, following, reporting and the other actions keep their own limits per account.

Rules for bots