---
name: otag-app
description: Build an app (a bot or integration) for Otag servers - slash commands, cards with buttons, forms, replies only one person sees, follow-ups, the gateway and webhooks. Use when asked to create, extend or debug an Otag app, bot or integration, or to post into Otag from another system.
---

# Building an Otag app

Otag is a voice and text chat platform. An **app** is a program that joins Otag servers as a member with a role of its own. People run its slash commands, press buttons and pick from menus on the cards it posts, and fill in the forms it opens; each of these reaches the app as an **interaction**, which it answers within 3 seconds. The app also calls Otag's REST API as itself.

The Otag server this skill came from is `https://api.otag.chat`. Its human guide is `https://api.otag.chat/developers`, and a working TypeScript example is `https://api.otag.chat/developers/example.zip`.

## Ground rules (get these right)

1. **The token is the app.** `otb_…` acts as the app. Read it from the environment, never write it into code, a page or anything people download, and never log it.
2. **Verify every POST from Otag** before parsing it: `X-Otag-Signature` must equal `sha256=` + hex HMAC-SHA256 of `"<X-Otag-Timestamp>.<raw body>"` under the signing secret, compared in constant time, and the timestamp (Unix seconds) must be within 300 s of now. Otherwise answer 401.
3. **Answer within 3 seconds.** For slower work answer `{"type": "defer"}` at once, then follow up with the interaction's `id` and `token` (valid 15 minutes).
4. **`ping` → `{"type": "pong"}`.** Otag pings the interactions address when it is saved, and a ping carries no `user`, so check the type first.
5. **Interactions come one way only.** With an interactions address set, Otag posts there and sends none over the gateway; with none, they come as `INTERACTION_CREATE` on the gateway and are answered by `POST /interactions/{id}/{token}/callback`.
6. **IDs are strings**, and `member.permissions` is a decimal string.
7. **Answer in the person's language**: `locale` is `en` or `tr`.
8. **Keep nothing between clicks if you can**: put what a button needs in its `id` (`join:b`, `page:2`), at most 100 characters.
9. **Anyone who sees a card can press its buttons.** Otag limits who may run commands, not who may click. For a button that does what a command does, check `member.can_use_commands` and answer `false` with a `reply`.
10. **Say hello**: answer `added` (the app was just added to a server) with a `message` saying what the app does and how to start, with the first step on a button.

## Workflow

1. **Gather**: the Otag server (`https://api.otag.chat` unless the user says otherwise), the app ID, the token, and for HTTPS mode the signing secret, all as environment variables (`OTAG_BASE`, `OTAG_APP_ID`, `OTAG_TOKEN`, `OTAG_SIGNING_SECRET`). The user makes the app in Otag: Settings → Developer → New app (the token is shown once), and on its page turns on the permissions it needs under "It asks to".
2. **Pick the transport**: the gateway for running on a laptop or behind NAT (no public address needed); an HTTPS interactions address for an app on a server. Both use the same answer logic.
3. **Register commands at startup**: `PUT /apps/{app_id}/commands` with the full list (it replaces the old one).
4. **Write one function from interaction to answer**, used by both transports.
5. **Test**: the user adds the app to a server they manage (Server settings → Integrations → Add by link or ID, pasting the app ID) and runs the command in a text channel. Try Otag in Turkish (Settings → App → Language) to check `tr`.
6. **Before calling it done**, check the list at the end.

## REST API

Base `https://api.otag.chat/api/v1`, headers `Authorization: Bot <token>` and `Content-Type: application/json`. Errors are `{code, message}`; `429 rate_limited` carries `retry_after_ms`.

| Purpose | Request |
|---|---|
| Commands | `PUT /apps/{app_id}/commands` `[command…]`; `GET /apps/{app_id}/commands` |
| Snapshot of its servers | `GET /state` (as the gateway READY: guilds with channels, roles, members) |
| Messages | `POST /channels/{id}/messages` `{content?, card?, thread_id?, also_in_channel?, reply_to?, reply_mention?, poll?, title?, tag_ids?}` (content ≤ 4000 chars, markdown, `<@user_id>` mentions; `thread_id` replies in the thread under that message, `also_in_channel: true` shows the reply in the channel too; `reply_to` answers a message the channel shows, with a `quote` of it, `reply_mention: true` mentions its author; not both a thread and a reply; `poll: {options, multi?}` asks a poll, content being the question, ≤ 300 chars, 2-12 options ≤ 100 chars, not editable, votes as `POLL_VOTE` and `PUT /channels/{id}/messages/{mid}/poll/votes` `{option_ids}`; in a channel of kind `forum` a message is a post with a required `title` and optional `tag_ids`, and replies go by `thread_id`, listed by `GET /channels/{id}/posts`; an announcement channel, `announcement: true`, denies @everyone Send Messages, so give the app's role an override; people's messages may be a voice message, no words and one attachment with `voice: true`, `duration_ms` and `waveform`, or a sticker, no words and `sticker_id` with `sticker` while it exists, neither editable); `PATCH /channels/{id}/messages/{mid}` `{content?, card?}`; `DELETE` same; `GET /channels/{id}/messages?before=&limit=` (without replies that stay in their thread); `GET /channels/{id}/messages/{mid}/thread?before=&limit=` → `{root, replies}` |
| Reactions | `PUT`/`DELETE /channels/{id}/messages/{mid}/reactions/{emoji}` |
| Pinned messages | `GET /channels/{id}/pins?thread_id=` (newest pin first); `PUT`/`DELETE /channels/{id}/pins/{mid}` (Manage Messages). A pinned message carries `pin {user_id, pinned_at}`; pinning writes a line with `system {kind: "pin", message_id}` and empty content, by who pinned: ignore it, it takes no reply, reaction or edit. `\|\|words\|\|` is a spoiler the apps hide until clicked |
| Channels | `POST /guilds/{gid}/channels` `{kind: "text"|"forum"|"voice", announcement?, name, topic?, category_id?, position?}`; `PATCH`/`DELETE /channels/{id}`; categories `POST /guilds/{gid}/categories`, `PATCH`/`DELETE /categories/{id}`; overrides `PUT`/`DELETE /channels/{id}/overrides/{role_id}` |
| Members | `GET /guilds/{gid}/members`, `GET /guilds/{gid}/roles`, `PATCH /guilds/{gid}/members/{id}` `{role_ids?, nick?}`, kick `DELETE /guilds/{gid}/members/{id}`, bans `GET /guilds/{gid}/bans`, `PUT`/`DELETE /guilds/{gid}/bans/{id}`, `GET /users/{id}` |
| Voice | `GET /guilds/{gid}/voice` → `[{user_id, channel_id, self_mute, self_deaf, server_mute, streaming, camera}]`; `POST /voice/{user_id}/move` `{channel_id}`; `PUT`/`DELETE /voice/{user_id}/mute`; disconnect `DELETE /voice/{user_id}` |
| Other | `GET /search?q=&channel_id=&author_id=&limit=`; `GET /guilds/{gid}/apps`; `POST /guilds/{gid}/leave` |

Every other route answers `403 app_not_allowed` (no DMs, friends or new servers). Each call also needs the permission in that server (`403 missing_permission`). The app posts ≤ 5 messages/s (burst 20) and joins no voice.

## Commands

```json
[{"name": "match", "description": "Open a match", "description_localizations": {"tr": "Maç aç"}, "menu": true,
  "options": [{"name": "map", "description": "The map", "type": "string", "required": false,
               "choices": [{"name": "Mirage", "value": "de_mirage"}]}]}]
```

≤ 50 commands. `name`: 1–32 of `a-z 0-9 - _`, unique. `description`: 1–100 chars. `menu: true` also lists it in the composer's + menu. ≤ 10 options, `type` ∈ `string`, `integer`, `boolean`, `user`, `channel`; `choices` `[{name, value}]` for string/integer. Bad list → `422 invalid_command`. Otag validates options before the app sees them.

## Interactions

```json
{"id": "…", "token": "…", "type": "command", "app_id": "…", "guild_id": "…", "channel_id": "…",
 "user": {"id": "…", "username": "alice", "display_name": "Alice"},
 "member": {"role_ids": ["…"], "nick": "Ali", "permissions": "3", "can_use_commands": true},
 "locale": "en", "data": {"name": "match", "options": {"map": "de_mirage"}}}
```

`member.can_use_commands`: whether the server's admins let this person use the app's commands there.

| `type` | `data` |
|---|---|
| `command` | `{name, options}` (options by name) |
| `action` | `{action_id, values?, message_id? \| reply_id?}`, plus `message` (the clicked message). `values` is a select's choice list. |
| `form` | `{form_id, values, message_id?}`; `values` by field id: string, number, boolean or list. |
| `configure` | `{}`: a server's manager asked for the app's settings (Server settings → Integrations → the app → Its settings). Answer with a form; check `member.permissions` & 32768 (Manage Server) when saving. |
| `added` | `{}`: someone (`user`) just added the app to the server and picked `channel_id` for its hello. Answer `message` (posted there as the app) or `defer` and `POST /interactions/{id}/{token}/messages` within 15 min; any other answer posts nothing. Sent only when the app may write there, once per adding. |
| `ping` | none: answer `pong`. No `user`, no `token`. |

**Gateway**: WebSocket `https://api.otag.chat/api/v1/gateway` (wss for https). Frames are `{"t": TYPE, "d": {…}}`. Send `{"t":"IDENTIFY","d":{"token":"otb_…"}}` → `READY` (incl. `heartbeat_ms`, 25000) → server events of the app's servers + `INTERACTION_CREATE` (the interaction above). Answer each with `POST /interactions/{id}/{token}/callback` `{type, data?, open?}` within 3 s. Server sends WebSocket pings (clients usually auto-answer); optionally send `{"t":"PING"}` every `heartbeat_ms` and reconnect if no `{"t":"PONG"}` for 15 s. Reconnect = fresh READY, no resume.

## Answers

`{type, data?, open?}`:

| `type` | `data` | Effect |
|---|---|---|
| `reply` | `{content?, card?}` | Only the person sees it, at the channel's foot. |
| `message` | `{content?, card?}` | The app posts it in the channel (needs View channels + Send messages there). |
| `update` | `{content?, card?}` | For an `action`: changes the clicked message/reply; parts change only when given; `"card": null` removes the card. |
| `form` | a form | Opens it for the person (not as the answer to a `form` interaction). |
| `defer` | none | Follow up later. |
| `open` | `{url, window?}` | Opens a link. |
| `pong` | none | Only for `ping`. |

Any answer may add `open: {url, window?}`. Links: `http`, `https`, `steam://connect`, `steam://run`; `window: "popup"` opens an https page in a small window apart from Otag (sign-ins). Failures people see: `503 app_offline` (no address and not on the gateway), `504 app_timeout` (> 3 s), `502 app_error` (an answer that doesn't fit).

**Follow-ups** (no auth header; 15 min; 1/s, burst 20): `PATCH /interactions/{id}/{token}/reply` `{content?, card?, close_window?}` (`close_window: true` closes a popup opened from that reply), `DELETE …/reply`, `POST …/messages` `{content?, card?}` (in the channel), `PATCH …/message` `{content?, card?}` (the clicked message).

## Cards

```json
{"color": "#13877B", "title": "Team A vs Team B", "url": "https://…",
 "status": {"text": "Open · 1 of 10", "tone": "accent"}, "description": "5v5 · **Mirage**",
 "image": "https://…/banner.png", "thumbnail": "https://…/logo.png",
 "fields": [{"name": "Mode", "value": "5v5", "inline": true}],
 "lists": [{"title": "Team A", "people": [{"user_id": "…", "note": "Host"}, {"name": "Guest"}], "slots": 5}],
 "actions": [{"type": "button", "id": "join:a", "label": "Join", "style": "primary"},
             {"type": "button", "id": "start", "label": "Start", "style": "success", "users": ["…"]},
             {"type": "select", "id": "map", "placeholder": "Map", "options": [{"value": "de_mirage", "label": "Mirage"}]},
             {"type": "link", "label": "Open", "url": "https://…"}],
 "footer": "Room 3BUGRA"}
```

Limits: `title` ≤ 120; `url`, `image`, `thumbnail` http/https; `description` markdown ≤ 2000; `status.text` ≤ 100, `tone` ∈ `neutral accent success warning danger live`; `fields` ≤ 12 (name ≤ 64, value ≤ 512 markdown); `lists` ≤ 4, people ≤ 12 each (`user_id` or `name`, `note` ≤ 32), `slots` ≤ 12, `empty` names empty slots; `footer` ≤ 200; `actions` ≤ 10: button `style` ∈ `primary secondary success danger` (default secondary), `disabled?`; select ≤ 25 options `{value, label, description?}`; ids unique ≤ 100 chars; labels ≤ 40; `users`/`except` ≤ 100 each (show to / hide from). The card must show something. Otag fetches and keeps pictures (PNG/JPEG/GIF/WebP, ≤ 4 MB, ≤ 4096 px; never private or local addresses). Bad card → `422 invalid_card` naming the field.

## Forms

```json
{"id": "match", "title": "Open a match", "submit": "Open",
 "sections": [{"fields": [
   {"type": "choice", "id": "mode", "label": "Mode", "style": "segmented", "value": "5v5",
    "options": [{"value": "5v5", "label": "5v5"}, {"value": "1v1", "label": "1v1"}]},
   {"type": "multi", "id": "maps", "label": "Maps", "min": 1, "max": 3, "show_when": {"field": "mode", "is": ["5v5"]},
    "options": [{"value": "de_mirage", "label": "Mirage", "image": "https://…"}]}]},
  {"title": "More options", "collapsed": true, "fields": [
   {"type": "toggle", "id": "knife", "label": "Knife round", "value": true},
   {"type": "text", "id": "name", "label": "Team name", "max_length": 32, "required": true}]}]}
```

≤ 5 sections, ≤ 25 fields. Field `{type, id, label, description?, placeholder?, required?, value?, show_when?}`; types: `text` (`max_length` ≤ 4000, default 200; `multiline?`), `number` (`min? max? step?`), `toggle`, `choice` (`style` tiles|list|segmented), `multi` (`min`, `max`; tiles|list), `select`, `note` (text only). Options ≤ 50 `{value, label, description?, image?, group?}`. `show_when` names an earlier choice/select/toggle (`"true"`/`"false"`). Sent once; Otag validates (`422 missing_value`/`invalid_value`) and sends the app a `form` interaction with the shown fields' values. Bad form → `422 invalid_form`.

## Webhooks (post-only integrations)

Made in Server settings → Integrations → Webhooks; the address is shown once. `POST https://api.otag.chat/api/v1/webhooks/{id}/{token}` `{content?, card?}`: no auth header, ≤ 2/s (burst 10), link actions only on cards, `?wait=true` returns the message.

## Permissions (sum the values; send as a decimal string)

View channels 1 · Send messages 2 · Attach files 4 · Add reactions 8 · Manage messages 16 · Connect 32 · Speak 64 · Share screen 128 · Mute members 256 · Move members 512 · Manage channels 1024 · Manage roles 2048 · Create invites 4096 · Kick members 8192 · Ban members 16384 · Manage server 32768 · Administrator 65536 · Change nickname 131072 · Manage nicknames 262144 · Add emoji and decorations 524288 · Manage emoji and decorations 1048576 · Time out members 4194304 · View audit log 8388608. Typical card app: 3.

## Templates (TypeScript, Node 22.18+, no packages)

```ts
import { createHmac, timingSafeEqual } from 'node:crypto';
import { createServer } from 'node:http';

const base = process.env.OTAG_BASE!, token = process.env.OTAG_TOKEN!, secret = process.env.OTAG_SIGNING_SECRET!;

async function api(method: string, path: string, body?: unknown) {
  const res = await fetch(`${base}/api/v1${path}`, { method, headers: { Authorization: `Bot ${token}`, 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
  if (!res.ok) throw new Error(`${method} ${path}: ${res.status} ${await res.text()}`);
  return res.status === 204 ? null : res.json();
}

function verify(ts: string | undefined, sig: string | undefined, body: Buffer): boolean {
  if (!ts || !sig?.startsWith('sha256=') || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const want = createHmac('sha256', secret).update(`${ts}.`).update(body).digest();
  const got = Buffer.from(sig.slice(7), 'hex');
  return got.length === want.length && timingSafeEqual(got, want);
}

function answer(i: any) {
  if (i.type === 'ping') return { type: 'pong' };
  // just added to a server: say what the app does there, with the first step on a button
  if (i.type === 'added')
    return { type: 'message', data: { card: { title: 'Hi! I say hello.', description: 'Type /hello in a text channel, or press the button.',
      actions: [{ type: 'button', id: 'hello', label: 'Say hello', style: 'primary' }] } } };
  if ((i.type === 'command' && i.data.name === 'hello') || (i.type === 'action' && i.data.action_id === 'hello')) {
    // anyone who sees the card may press its button; the command is for those the server lets use it
    if (!i.member?.can_use_commands) return { type: 'reply', data: { content: 'This server lets only some roles use me.' } };
    return { type: 'reply', data: { card: { title: `Hello, ${i.user.display_name}!`, actions: [{ type: 'button', id: 'wave', label: 'Wave' }] } } };
  }
  if (i.type === 'action' && i.data.action_id === 'wave') return { type: 'update', data: { content: '👋' } };
  return { type: 'reply', data: { content: 'Unknown.' } };
}

// HTTPS mode: Otag posts here (set the app's interactions address to https://<host>/interactions)
createServer(async (req, res) => {
  const chunks: Buffer[] = []; for await (const c of req) chunks.push(c as Buffer);
  const body = Buffer.concat(chunks);
  if (!verify(req.headers['x-otag-timestamp'] as string, req.headers['x-otag-signature'] as string, body)) return void res.writeHead(401).end();
  try { res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(answer(JSON.parse(body.toString())))); }
  catch { res.writeHead(500).end(); }
}).listen(Number(process.env.PORT));

// Gateway mode instead (no interactions address set):
// const ws = new WebSocket(base.replace(/^http/, 'ws') + '/api/v1/gateway');
// ws.onopen = () => ws.send(JSON.stringify({ t: 'IDENTIFY', d: { token } }));
// ws.onmessage = (e) => { const { t, d } = JSON.parse(String(e.data));
//   if (t === 'INTERACTION_CREATE') api('POST', `/interactions/${d.id}/${d.token}/callback`, answer(d)).catch(console.error); };
```

The full example (both modes, heartbeats, reconnects, forms, EN/TR): `https://api.otag.chat/developers/example.zip`.

## Before you call it done

- [ ] Token and signing secret come from the environment; nothing secret is logged or committed.
- [ ] HTTPS mode refuses unsigned, wrongly signed and stale requests (401), and answers `ping` with `pong`.
- [ ] Every interaction is answered within 3 s (`defer` + follow-up for slow work), and errors don't crash the process.
- [ ] Commands are registered at startup; names fit `a-z0-9-_`, descriptions ≤ 100.
- [ ] Cards and forms stay within the limits above (ids unique, labels ≤ 40, ≤ 10 actions, ≤ 25 select options).
- [ ] Replies meant for one person use `reply`; actions only some may press use `users`/`except`; buttons that do what a command does check `member.can_use_commands`.
- [ ] `added` is answered with a hello `message` (what the app does, how to start, a button for the first step).
- [ ] Answers follow `locale` (`en`, `tr`).
- [ ] The app asks only for the permissions it uses.
- [ ] Tested in a real server: the command, each button, each form, in both languages.

To be listed in Otag's app list (Server settings → Integrations): make the app public with a description and an icon, then "Ask to be listed" on its page in Settings → Developer; Otag's admins review it.
