Command Bot API
A Telegram-style Bot API. Your bot receives everything the user types, taps or submits in the portal through getUpdates, and replies with sendMessage, including rich HTML, inline buttons and input forms. Any language that can make HTTP requests can run a bot.
http://localhost:4003/botTOKEN/method
HTTPS/HTTP · GET query string, JSON body or form body
Long polling via getUpdates, with a private queue per session_id. No webhook setup needed.
Each bot has a unique numeric id, @username and a secret token.
Overview
The platform has two sides:
- The portal (this web app) where a person creates bots and chats with them. Every bot has exactly one chat; its
chat_idis shown in the bot's details panel. - The Bot API that your code talks to. Everything the user does in the chat becomes an update your bot can fetch; everything your bot sends appears in the chat instantly.
┌────────────┐ getUpdates (long-poll) ┌──────────────────┐ live ┌──────────────┐
│ your bot │ ◀──────────────────────── │ Command Bot API │ ────────▶ │ portal UI │
│ (any lang) │ ────────────────────────▶ │ Express + MySQL │ ◀──────── │ chat, taps, │
└────────────┘ sendMessage / edit / … └──────────────────┘ actions │ form submits │
└──────────────┘
Three kinds of updates reach your bot:
| Update | When | Key payload |
|---|---|---|
message | The user typed a text message | message.text, message.chat.id |
callback_query | The user pressed an inline button | callback_query.data, callback_query.id |
input_result | The user submitted an input form | input_result.values (all fields), field/value for single-field forms |
Quick start
- In the portal press +, name the bot and copy its token.
- No
chat_idis needed: every bot has exactly one chat and the token identifies it. (The id is still shown in the details panel (⚙) and bygetChats.) - Send a message, then poll for what the user does next:
# send a message with a button and an input field
curl -s $BASE/bot$TOKEN/sendMessage \
-H 'Content-Type: application/json' \
-d '{"parse_mode": "HTML",
"text": "Hello <b>there</b>! What is your name?",
"reply_markup": {
"inline_keyboard": [[{"text": "Skip", "callback_data": "skip"}]],
"input_field": {"name": "name", "placeholder": "Your name"}
}}'
# wait up to 30 s for the user's reply, button press or form submit
curl -s "$BASE/bot$TOKEN/getUpdates?timeout=30&offset=0"
The demo bot in examples/echo-bot.js shows a complete loop; see Complete bot examples for Node.js and Python versions.
Authentication
The token is part of the URL, exactly like Telegram: /bot<TOKEN>/<method>. Tokens look like 12:Kx9… (bot id, colon, random secret). A wrong or revoked token returns 401 Unauthorized.
Keep the token secret. Anyone holding it can read the chat and send messages as the bot. If it leaks, open the bot's details panel and press Rotate token; the old one stops working immediately.
Every authenticated call also updates the bot's last seen time, which the portal uses to show the green "online" presence dot (within the last 45 seconds).
Requests & responses
All methods accept GET with query parameters, or POST with a JSON body (Content-Type: application/json) or a URL-encoded form body. Nested objects such as reply_markup may be passed as a JSON string in form/query requests.
// success
{ "ok": true, "result": … }
// failure
{ "ok": false, "error_code": 400, "description": "Bad Request: message text is empty" }
Responses are JSON with a Telegram-compatible envelope. Timestamps named date are Unix seconds; created_at values are Unix milliseconds. Cross-origin requests are allowed (Access-Control-Allow-Origin: *) so a bot can even run in a browser page.
GET/POSTgetUpdates
Returns the updates waiting for your bot, oldest first. This is the only way to receive user activity: text messages, button presses and form submits all arrive here.
| Parameter | Type | Description |
|---|---|---|
session_id | string | Return only the updates that belong to this client session (messages sent with the same session_id). Strongly recommended when several browsers share one bot; see Sessions. session is accepted as an alias. |
offset | integer | Return updates with update_id ≥ offset. Send last_update_id + 1 to acknowledge what you have handled. Exactly as on Telegram, a confirmed update is deleted and never returned again. With a session_id only that session's updates below the offset are deleted; without one, every update of the bot below the offset is. Unconfirmed updates expire after 24 hours. Default 0. |
consume | boolean | true deletes every update in the response the moment it is returned, so each one is delivered exactly once with no offset bookkeeping. Meant for session pollers; never use it on a session-less poll while other clients poll the same bot. |
timeout | 0–50 seconds | Long polling: the request stays open until an update for this bot (and session) exists or the timeout passes, then answers at once. Default 0 returns immediately. |
limit | 1–100 | Maximum number of updates to return. Default 100. |
{ "ok": true, "result": [
{ "update_id": 41, "session_id": "tab-7f3a", "callback_query": { "id": "2:3:11:mvh5", "data": "/correct", "button_text": "✅ Correct",
"session_id": "tab-7f3a", "from": { … }, "chat_instance": "3",
"message": { "message_id": 11, "chat": { "id": 3, … }, "date": 1792529990, "text": "Report #42" } } },
{ "update_id": 42, "message": { "message_id": 12, "from": { "id": 1, "first_name": "Portal", "username": "portal_user", "is_bot": false },
"chat": { "id": 3, "type": "private", "title": "General" }, "date": 1792530000, "text": "/start" } }
] }
When an update appears and when it disappears
An update is created the moment the user acts in the portal and is immediately visible to the next getUpdates call that matches it. How long it keeps appearing depends on how the client polls:
| Client polls with | Update disappears | Use when |
|---|---|---|
session_id + consume=true | As soon as it has been returned once. The very next poll is empty. | Browsers polling on a fixed interval (every second). Simplest; nothing to store on the client. |
session_id + offset=last+1 | When the client acknowledges it. It keeps appearing until then, so a crash before handling is safe to retry. | Clients that need at-least-once handling with retries. |
no session_id + offset=last+1 | When confirmed, like a Telegram bot: every update of the bot below the offset is deleted. Unconfirmed ones expire after 24 hours (UPDATE_RETENTION_HOURS). | A single bot program that owns the whole token. |
Pick one method per client. A poller that sends neither consume nor an advancing offset receives the same update on every poll for up to 24 hours, which is exactly the double-processing you want to avoid. This matches Telegram, where an update only disappears once you call getUpdates with an offset above its id.
Update types
Every update object has an integer update_id (strictly increasing per bot) plus exactly one of the following keys.
message
The user sent a text message from the composer.
| Field | Type | Description |
|---|---|---|
message_id | integer | Unique id of the message in the chat |
from | User | The portal user: { id, first_name, username, is_bot: false } |
chat | Chat | { id, type: "private", title }. Use chat.id for replies. |
date | integer | Unix seconds |
text | string | The message text (≤ 4096 characters) |
reply_to_message | Message | Present when the operator used Reply on a bot message: { message_id, text, date, session_id } of that message |
session_id | string | The session this reply is routed to: the replied-to message's session, or otherwise the session of the chat's most recent tagged bot message |
callback_query
The user pressed an inline keyboard button that has callback_data. URL buttons open the link directly and do not produce an update.
| Field | Type | Description |
|---|---|---|
id | string | Query id. Pass it to answerCallbackQuery to show feedback. |
data | string | The button's callback_data |
button_text | string | The label that was pressed (handy for logging) |
message | Message | The bot message that carried the button, including message_id and chat |
from | User | The portal user |
chat_instance | string | Chat id as a string (Telegram compatibility) |
session_id | string | Present when the pressed message was sent with a session_id |
Buttons stay on the message and can be pressed repeatedly; use editMessageReplyMarkup to remove or change them once handled. The portal highlights the last button pressed on each message (solid colour with a ✓) and remembers it across reloads; the portal's message objects carry it as pressed: { data, text, at }. Editing the message's text or markup clears the highlight.
input_result
The user filled in and submitted an input form. Each form can be submitted once; the portal then locks it and shows the submitted values.
| Field | Type | Description |
|---|---|---|
id | string | Submission id |
values | object | All field values keyed by field name. Numbers are numbers for type: "number"; everything else is a string. Optional fields that were left empty are "". |
field, value | string | Present only when the form had a single field, as a shortcut |
message | Message | The bot message that carried the form |
from | User | The portal user |
session_id | string | Present when the form's message was sent with a session_id |
{ "update_id": 43, "input_result": {
"id": "2:3:13:mvh6", "from": { … },
"message": { "message_id": 13, "chat": { "id": 3, … }, "text": "Create your account" },
"values": { "name": "Ada Lovelace", "email": "[email protected]", "plan": "pro", "notes": "" } } }
Values are validated server-side before the update is created: required fields must be filled, number fields must parse, email fields must look like an address and select values must be one of the options. Invalid submissions are rejected in the portal and never reach the bot.
Long polling
The recommended loop is a single request at a time with timeout=30. The server holds the connection open and answers the moment an update appears, so latency is near zero without hammering the API.
let offset = 0;
for (;;) {
const { result } = await call('getUpdates', { offset, timeout: 30 });
for (const u of result) {
offset = u.update_id + 1; // acknowledge
await handle(u);
}
}
- Use one polling loop per bot. Two concurrent pollers would compete for the same queue.
- Wrap the call in a retry with a short sleep; a network blip simply means you poll again with the same
offset. - The badge in the portal sidebar and the Pending updates panel show what your bot has not yet fetched, which is useful while debugging.
Sessions: many browsers, one bot
A bot token is normally used by one program. A common setup, though, is a website where every visitor's browser talks to the same bot: each browser sends its own report and waits for the operator to press a button on that report. Two things must hold: the press must reach only the browser that sent the report, and a browser that polls every second must never process the same press twice. Sessions give every browser its own queue, which guarantees both.
The pattern
- One id per browser tab. Generate it once (for example
crypto.randomUUID()kept insessionStorage) and use the same value for everything that tab does. - Send with the id. Every
sendMessagecarriessession_id. The message is tagged on the server and the portal shows the tag under the bubble, so the operator can tell visitors apart. Putting the id insidecallback_dataas well ("/correct tab-7f3a") is fine and useful as a second check, but it is not what routes the update. - Poll with the id.
getUpdates?session_id=…&consume=true(or&offset=last+1). The browser receives only presses and submits on its own messages, plus operator replies typed while its message was the latest in the chat.
// in the visitor's browser — see examples/browser-session-client.js for a complete drop-in version
const sessionId = sessionStorage.cbSession ??= crypto.randomUUID();
await call('sendMessage', {
session_id: sessionId, // ties every reply to this tab
parse_mode: 'HTML', text: '<b>Report</b> from visitor 7f3a',
reply_markup: { inline_keyboard: [[{ text: 'Correct', callback_data: `/correct ${sessionId}` }],
[{ text: 'Wrong', callback_data: `/wrong ${sessionId}` }]] },
});
// poll every second: only this tab's updates, each delivered exactly once
setInterval(async () => {
const { result } = await call('getUpdates', { session_id: sessionId, consume: true });
for (const u of result) {
if (u.callback_query) handle(u.callback_query.data); // "/correct tab-7f3a" — always for this tab
if (u.message) showOperatorReply(u.message.text);
}
}, 1000);
Add timeout: 25 to the poll and the request waits on the server until a press happens, so the browser reacts in milliseconds instead of up to a second later and makes one request every 25 seconds instead of 25.
What happens, second by second
| Time | Event | Tab A polls (session_id=A&consume=true) | Tab B polls (session_id=B&consume=true) |
|---|---|---|---|
| 10:00:00 | A and B each send a report | [] | [] |
| 10:00:05 | Operator presses Correct on A's report | update 41 is written to session A's queue only | |
| 10:00:06 | [ update 41 ] → deleted on delivery | [] | |
| 10:00:07 | [] | [] | |
| 10:00:09 | Operator types "checking now" | [] | [ update 42 (message) ] — B's report was the latest tagged message |
Rules
- Routing.
callback_queryandinput_resultupdates inherit thesession_idof the message that carried the button or form. An operator's typed message goes to the session of the bot message they pressed ↩ Reply on (the update carriesreply_to_message). Without Reply it goes to the session of the latest tagged bot message, which is only reliable when one visitor is active: in a 100-visitor test, 541 of 543 untargeted replies reached the wrong visitor, and 543 of 543 targeted ones the right one. Messages sent without a session produce unrouted updates. - Isolation. A poll with a
session_idnever returns another session's updates, nor unrouted ones. A message sent withoutsession_idis therefore invisible to session pollers: use the id on both calls, consistently. - Exactly once. With
consume=truean update is deleted when returned. Withoffset, acknowledged updates of that session are deleted, so a page reload that restarts atoffset=0cannot replay them. Use one of the two, not both. - Long polling is per session. A request with
timeoutis woken only by updates for its own session. - Session-less pollers. A poll without
session_idis a plain Telegram bot: it returns every update of the bot, routed or not, and itsoffsetdeletes everything it confirms, including browsers' updates. Use it only when one program owns the token; never run it alongside session browsers.
POSTsendMessage
Sends a message from the bot into the chat. Returns the created message.
| Parameter | Type | Description |
|---|---|---|
chat_id | integer | Optional. Every bot has exactly one chat and the token already identifies it, so this can be omitted. If given, it must be this bot's chat. |
textrequired | string | 1–8192 characters. Newlines are preserved. |
parse_mode | HTML | Markdown | Enables formatting; see Text formatting. Omit for plain text (links are still auto-detected). |
reply_markup | object | Inline keyboard and/or input fields; see Buttons & input fields. |
// response
{ "ok": true, "result": { "message_id": 14, "chat_id": 3, "bot_id": 2, "from": "bot",
"text": "Hello <b>there</b>", "parse_mode": "HTML", "reply_markup": { … },
"answered": false, "date": 1792530100, "created_at": 1792530100123 } }
Keep the returned message_id if you plan to edit or delete the message later.
Text formatting
HTML parse_mode: "HTML"
A Telegram-like subset. Anything not in the list is stripped (the inner text is kept), attributes are removed except a safe href, and only http(s):, mailto: and tel: links are allowed, so bot output can never inject scripts into the portal.
| Tag | Renders as |
|---|---|
<b>, <strong> | bold |
<i>, <em> | italic |
<u>, <ins> | underline |
<s>, <strike>, <del> | |
<code> | inline code |
<pre> | code block (whitespace preserved) |
<a href="…"> | link, opens in a new tab |
<blockquote> | quoted block |
<span class="tg-spoiler">, <tg-spoiler> | spoiler, revealed on click |
<br> or a newline | line break |
Escape literal <, > and & in user-supplied text as <, >, & before embedding it in HTML.
Markdown parse_mode: "Markdown"
*bold* _italic_ ~strikethrough~ `inline code` [link text](https://example.com)
```
code block
```
Plain text
Without parse_mode the text is shown verbatim; URLs become clickable automatically.
Buttons & input fields
reply_markup is an object that may contain an inline keyboard, input fields, or both. Buttons render under the message text; the form renders under the buttons.
"reply_markup": {
"inline_keyboard": [
[ { "text": "✅ Approve", "callback_data": "approve", "style": "success" },
{ "text": "❌ Reject", "callback_data": "reject", "style": "danger" } ],
[ { "text": "📖 Documentation", "url": "https://example.com/docs" } ]
],
"input_fields": [
{ "name": "email", "label": "Email", "type": "email", "placeholder": "[email protected]" },
{ "name": "plan", "label": "Plan", "type": "select", "options": ["Free", "Pro", "Team"] },
{ "name": "notes", "label": "Notes", "type": "textarea", "required": false }
],
"submit_text": "Create account"
}
inline_keyboard
An array of rows; each row is an array of 1–8 buttons; up to 20 rows.
| Field | Type | Description |
|---|---|---|
textrequired | string | Label, ≤ 64 characters. Emoji welcome. |
callback_data | string | ≤ 256 characters, sent back in a callback_query. Required unless url is set. |
url | string | Opens the link in a new tab instead of producing an update. http(s):, mailto:, tel:. |
style | default | primary | success | danger | Visual accent of the button. |
input_fields
An array of 1–12 fields rendered as a form with a submit button. For a single field you can use the shorthand "input_field": { … }. The form submits once and produces one input_result update containing every value.
| Field | Type | Description |
|---|---|---|
name | string | Key used in values. [A-Za-z0-9_.-], ≤ 64 chars, unique within the form. Defaults to field_1, field_2… |
label | string | Shown above the input. Defaults to name. |
type | string | text (default), textarea, number, email, password, url, date, time, select |
placeholder | string | Hint text inside the input |
value | string | Pre-filled value |
required | boolean | Default true |
options | array | select only: ["Free", "Pro"] or [{ "value": "pro", "label": "Pro – $9/mo" }]. Up to 50. |
min, max | number | number fields |
| Form option | Type | Description |
|---|---|---|
submit_text | string | Label of the submit button, ≤ 32 chars. Default Submit. |
Editing a message with editMessageText or editMessageReplyMarkup re-opens its form, which lets a bot ask the same question again or correct a field.
POSTeditMessageText
Replaces the text (and optionally the markup) of a message the bot sent earlier. The portal updates in place and marks the message as edited.
| Parameter | Type | Description |
|---|---|---|
message_idrequired | integer | A message sent by this bot |
textrequired | string | New text |
parse_mode | string | As in sendMessage |
reply_markup | object | New markup. Omit to keep the current buttons/fields; pass null or {} to remove them. |
POSTeditMessageReplyMarkup
Changes only the buttons and input fields of a bot message, keeping its text. Typical use: remove buttons after one has been handled, or swap "Approve/Reject" for a "Done ✓" button.
| Parameter | Type | Description |
|---|---|---|
message_idrequired | integer | A message sent by this bot |
reply_markup | object | New markup; omit or pass {} to remove all buttons and fields |
POSTdeleteMessage
Deletes a message from the chat (bot or user message). Returns true.
| Parameter | Type | Description |
|---|---|---|
message_idrequired | integer | Message in one of this bot's chats |
POSTanswerCallbackQuery
Gives the user immediate feedback after a button press: a small toast at the bottom of the portal, or a blocking alert. Optional, but it makes button presses feel responsive even when the bot takes a moment to reply.
| Parameter | Type | Description |
|---|---|---|
callback_query_idrequired | string | The id from the callback_query update |
text | string | Up to 200 characters. Omit to acknowledge silently. |
show_alert | boolean | true shows a modal alert instead of a toast |
POSTsendChatAction
Shows the typing indicator in the chat for up to 5 seconds, or until the bot's next message arrives. Call it before slow work.
| Parameter | Type | Description |
|---|---|---|
chat_id | integer | Optional; defaults to the bot's chat |
action | string | typing (default) |
GETgetMe
Returns the bot's identity. A quick way to validate a token at startup.
{ "ok": true, "result": { "id": 2, "is_bot": true, "first_name": "Echo Bot", "username": "echo_bot", "description": "" } }
GETgetChats
Returns the bot's chat and its id, so a bot can send a first message before the user has written anything.
{ "ok": true, "result": [ { "id": 3, "type": "private", "title": "General", "last_message_at": 1792530100123 } ] }
Errors
| HTTP | description | Meaning |
|---|---|---|
| 401 | Unauthorized | Unknown or rotated token |
| 400 | Bad Request: chat not found: … | A chat_id was given that belongs to another bot; the message names the right id. Omit chat_id to use the bot's own chat. |
| 400 | Bad Request: message text is empty | text missing or blank |
| 400 | Bad Request: message is too long (max 8192 chars) | Shorten the text |
| 400 | Bad Request: parse_mode must be 'HTML' or 'Markdown' | Unsupported mode |
| 400 | Bad Request: button [r][c] needs callback_data or url | Malformed keyboard; the message names the row and column |
| 400 | Bad Request: input_fields[i].… | Malformed field definition |
| 400 | Bad Request: message to edit not found | Wrong message_id, or the message was sent by the user |
| 400 | Bad Request: invalid JSON body | Body could not be parsed |
| 404 | Not Found: method not found | Typo in the method name (names are case-sensitive) |
| 500 | Internal Server Error | Check the server log |
Limits
| Item | Limit |
|---|---|
| Message text | 8192 characters (bot), 4096 (user) |
| Inline keyboard | 20 rows × 8 buttons; label ≤ 64 chars; callback_data ≤ 256 chars |
| Input fields | 12 per form; 50 options per select; value ≤ 4096 chars |
getUpdates | limit ≤ 100, timeout ≤ 50 s |
| Request body | 1 MB |
Complete bot examples
Each example answers text, handles a button and reads a form. Replace TOKEN with your bot token.
const API = `${process.env.API_BASE || '__BASE__'}/bot${process.env.BOT_TOKEN}`;
const call = async (method, body) => {
const r = await fetch(`${API}/${method}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
const d = await r.json(); if (!d.ok) throw new Error(`${method}: ${d.description}`); return d.result;
};
const menu = { inline_keyboard: [[{ text: '👋 Say hi', callback_data: 'hi', style: 'primary' }, { text: '📝 Form', callback_data: 'form' }]] };
let offset = 0;
for (;;) {
const updates = await call('getUpdates', { offset, timeout: 30 });
for (const u of updates) {
offset = u.update_id + 1;
if (u.message) {
await call('sendMessage', { chat_id: u.message.chat.id, parse_mode: 'HTML', reply_markup: menu,
text: `You said: <code>${u.message.text}</code>` });
} else if (u.callback_query) {
const q = u.callback_query;
await call('answerCallbackQuery', { callback_query_id: q.id, text: `Got "${q.button_text}"` });
if (q.data === 'form') await call('sendMessage', { chat_id: q.message.chat.id, text: 'Tell me about you',
reply_markup: { input_fields: [{ name: 'name', label: 'Name' }, { name: 'age', label: 'Age', type: 'number', min: 0 }], submit_text: 'Send' } });
} else if (u.input_result) {
const v = u.input_result.values;
await call('sendMessage', { chat_id: u.input_result.message.chat.id, text: `Thanks ${v.name}, age ${v.age} noted ✅` });
}
}
}import os, requests
API = f"{os.environ.get('API_BASE', '__BASE__')}/bot{os.environ['BOT_TOKEN']}"
def call(method, **params):
data = requests.post(f"{API}/{method}", json=params, timeout=60).json()
if not data["ok"]:
raise RuntimeError(f"{method}: {data['description']}")
return data["result"]
menu = {"inline_keyboard": [[{"text": "👋 Say hi", "callback_data": "hi", "style": "primary"},
{"text": "📝 Form", "callback_data": "form"}]]}
offset = 0
while True:
for u in call("getUpdates", offset=offset, timeout=30):
offset = u["update_id"] + 1
if "message" in u:
m = u["message"]
call("sendMessage", chat_id=m["chat"]["id"], parse_mode="HTML", reply_markup=menu,
text=f"You said: <code>{m['text']}</code>")
elif "callback_query" in u:
q = u["callback_query"]
call("answerCallbackQuery", callback_query_id=q["id"], text=f"Got {q['button_text']}")
if q["data"] == "form":
call("sendMessage", chat_id=q["message"]["chat"]["id"], text="Tell me about you",
reply_markup={"input_fields": [{"name": "name", "label": "Name"},
{"name": "age", "label": "Age", "type": "number", "min": 0}],
"submit_text": "Send"})
elif "input_result" in u:
v = u["input_result"]["values"]
call("sendMessage", chat_id=u["input_result"]["message"]["chat"]["id"],
text=f"Thanks {v['name']}, age {v['age']} noted ✅")BASE=__BASE__
TOKEN=12:your_token_here
# who am I, and which chat do I have?
curl -s $BASE/bot$TOKEN/getMe
curl -s $BASE/bot$TOKEN/getChats
# plain text (form-encoded)
curl -s $BASE/bot$TOKEN/sendMessage -d "text=Hello from curl"
# HTML + buttons + form (JSON)
curl -s $BASE/bot$TOKEN/sendMessage -H 'Content-Type: application/json' -d '{
"parse_mode": "HTML", "text": "<b>Order #42</b> is ready. Ship it?",
"reply_markup": {
"inline_keyboard": [[{"text": "Ship", "callback_data": "ship:42", "style": "success"},
{"text": "Hold", "callback_data": "hold:42", "style": "danger"}]],
"input_field": {"name": "note", "label": "Note for the courier", "required": false}
}}'
# long-poll (blocks up to 30 s), then acknowledge with offset = last update_id + 1
curl -s "$BASE/bot$TOKEN/getUpdates?timeout=30"
curl -s "$BASE/bot$TOKEN/getUpdates?offset=44"
# react to a button press
curl -s $BASE/bot$TOKEN/answerCallbackQuery -d "callback_query_id=2:1:14:mvh7&text=Shipping…"
curl -s $BASE/bot$TOKEN/editMessageReplyMarkup -H 'Content-Type: application/json' \
-d '{"message_id": 14, "reply_markup": {"inline_keyboard": [[{"text": "Shipped ✓", "callback_data": "noop"}]]}}'Portal API (internal)
The web portal talks to its own JSON API under /api. It requires a portal login: POST /api/auth/login with { "email", "password" } sets a 30-day session cookie (accounts are created from the terminal with npm run user -- add <email>), POST /api/auth/logout ends it and GET /api/auth/me returns the signed-in account. Without a session every other /api route answers 401. The Bot API above is separate and keeps using bot tokens.
| Route | Purpose |
|---|---|
GET /api/bots | List bots with presence, unread count and pending updates |
POST /api/bots | Create a bot { name, username?, description?, color? }; returns the token once |
GET /api/bots/:id | Bot details including its token |
PATCH /api/bots/:id | Rename / recolour |
POST /api/bots/:id/rotate-token | Issue a new token |
DELETE /api/bots/:id | Delete the bot and everything in it |
GET /api/bots/:id/chats | The bot's chat (created if missing) |
GET /api/bots/:id/updates | Updates the bot has not fetched yet |
GET /api/chats/:chatId/messages | Message history with rendered html: the most recent 500 by default; ?limit= (≤ 2000) and ?before=<message_id> page further back |
POST /api/chats/:chatId/messages | Send as the user { text, reply_to_message_id? } → message update, routed to the replied-to message's session |
POST /api/chats/:chatId/read | Mark the chat as read |
DELETE /api/messages/:id | Delete one message from the chat (either side) |
DELETE /api/chats/:chatId/messages | Clear the whole chat; the bot, its token and queued updates stay |
POST /api/messages/:id/callback | Press a button { callback_data } → callback_query update |
POST /api/messages/:id/input | Submit a form { values } → input_result update |
GET /api/events | Server-Sent Events stream of everything that happens, used by the UI |