Skip to content
SONOEDocs
EspañolESConsole

Sonoe chat bots

A guide for anyone building a bot for Sonoe chat (the agent protocol, version 1). With it you can build a bot in an afternoon: it receives what people tell it, replies (live too, word by word), shows what it's doing while it works, asks the person for things (their location, to pick an option, to confirm, some text) and can set statuses. Lados (/lados) is built with exactly this protocol.

Base: https://sonoeai.com (locally, http://localhost:8100). Everything is UTF-8 JSON. Field names are in Spanish, like the rest of Sonoe's API.

Concepts

  • People are written @user (their SONOE ID). Bots are written /name (lowercase, unique; a separate namespace: @lados and /lados can both exist).
  • Chats: 1:1 with a person, 1:1 with a bot, or groups with people and bots. A bot joins a group like any other member.
  • What a bot sees:
    • in a 1:1 with it: everything;
    • in a group: only what's addressed to it — a message that names it (/lados …), a reply to one of its messages, or someone tapping one of its buttons or options — unless the group's admin grants it "read the whole group" (and the bot has to ask for it in its manifest). Every member can see that permission.
    • It never receives its own messages or those of other bots (so bots can't loop each other).
  • Event: something that happens to the bot (a message, a button tap, an answer…). It arrives over a connection (the bot opens a stream) or a webhook (Sonoe POSTs to it).
  • Action: what the bot does, with its token: write, stream a reply, set its activity, ask for something…
  • Medium: where a message is delivered. Today sonoe (the app). Later web, sms, whatsapp, email, voz (voice). That's why every message carries required plain text and, optionally, structured blocks (Media and fallback text).

Create the bot

Any account can create one (up to 20 bots), from the console (session) or with an app key:

POST /api/chat/my-bots          (sonoeai.com session, header X-Sonoe: 1)
POST /v1/chat/my-bots           (Authorization: Bearer sk_sonoe_…)

{
  "nombre": "clima",
  "nombre_visible": "Clima",
  "descripcion": "El tiempo en cualquier pueblo de Puerto Rico",
  "avatar": "https://…/clima.png",
  "color": "#445ED9",
  "visibilidad": "publico",          // privado (default): only you can add it · publico: anyone can find and add it
  "modo": "conexion",                // conexion (default) · webhook (then "webhook_url": "https://…")
  "comandos": [{"nombre": "hoy", "descripcion": {"es": "El tiempo de hoy", "en": "Today's weather"},
                "params": [{"nombre": "pueblo", "descripcion": "Dónde", "requerido": false}]}],
  "recibe": ["texto", "ubicacion"],
  "necesita": ["ubicacion"],
  "idiomas": ["es", "en"]
}

201 response:

{"bot": {"nombre": "clima", "…": "…"}, "token": "sb_bot_Xb1…", "webhook_secreto": "whsec_9f…"}

Also: GET /api/chat/my-bots (yours, with en_linea, eventos_pendientes, eventos_fallidos), GET|PATCH|DELETE /api/chat/my-bots/{nombre} (the same routes exist under /v1/chat/… with a key).

Reserved names (Sonoe's team only): sonoe, lados, ayuda, help, admin, bot, bots, sistema…

Authentication

Every protocol call carries the bot's token:

Authorization: Bearer sb_bot_Xb1…

GET /v1/bots/me tells you who you are (your profile and your manifest). An invalid token: 401. Errors come as {"detail": "…", "error": {"type": "bot_token_invalido", "message": "…"}}, in the language of Accept-Language (English if you don't send it).

Receive events

Connection mode (SSE)

Recommended to start with. The bot opens a long-lived stream from anywhere (a server, a laptop behind a router, no open ports needed):

GET /v1/bots/events
Accept: text/event-stream
event: hola
data: {"tipo": "hola", "bot": "clima", "version": "1", "pendientes": 2}

id: 41
event: mensaje
data: {"id": 41, "tipo": "mensaje", …}

: sigue
  • Pending events (the ones you haven't acknowledged) come first, then new ones, in order.
  • Every 15 s a : sigue comment arrives (it keeps the connection alive). The stream closes itself every hour: reconnect (with growing backoff if it fails: 1 s, 2 s, 4 s… up to 60 s).
  • Acknowledge each event once you've handled it; otherwise it arrives again when you reconnect (at-least-once delivery: use the id so you don't handle the same thing twice):
POST /v1/bots/events/ack
{"ids": [41, 42]}
  • Without a stream (for example, in a cron job or a serverless function): GET /v1/bots/events?stream=0 → {"eventos": [ … ]} (up to 100 pending), then ack.
  • An event nobody picks up within 24 h is discarded.

Webhook mode

Sonoe makes a POST to your webhook_url (HTTPS) with the event as the body and these headers:

HeaderValue
X-Sonoe-Eventothe type (mensaje, accion…)
X-Sonoe-Entregathe event's id
X-Sonoe-TimestampUnix seconds when it was sent
X-Sonoe-Firmav1= + hex HMAC-SHA256 of "{timestamp}.{body}" with your webhook_secreto

Reply 2xx in under 10 s (do the long work afterwards, with the API's actions). Otherwise Sonoe retries after 5 s, 30 s, 2 min, 10 min and 30 min; after that, the event is marked failed and its content is deleted. The address must be public (no private or local IPs).

Verifying the signature (Python):

import hashlib, hmac, time

def firma_valida(secreto: str, cabeceras, cuerpo: bytes) -> bool:
    marca = cabeceras["X-Sonoe-Timestamp"]
    if abs(time.time() - int(marca)) > 300:          # older than 5 minutes: a replay
        return False
    esperada = "v1=" + hmac.new(secreto.encode(), marca.encode() + b"." + cuerpo, hashlib.sha256).hexdigest()
    return hmac.compare_digest(esperada, cabeceras["X-Sonoe-Firma"])

Events

The envelope

Common to every event:

{
  "id": 41,
  "tipo": "mensaje",
  "version": "1",
  "creado": "2026-11-22T19:17:27Z",
  "bot": {"nombre": "clima"},
  "medio": "sonoe",
  "chat": {"id": 12, "tipo": "grupo", "nombre": "Playa el sábado", "personas": 4},
  "permisos": {"leer_grupo": false, "ubicacion": true, "estado": false},
  "de": {"tipo": "persona", "usuario": "ana", "nombre": "Ana Rivera", "avatar": "forma-3"},
  "locale": "es-PR",
  "contexto": [
    {"id": 300, "autor": {"tipo": "persona", "usuario": "beto", "…": "…"}, "texto": "/clima ¿llueve hoy?", "bloques": [],
     "responde_a": null, "menciones": [], "medio": "sonoe", "creado": "…", "editado": null}
  ]
}
localestringrequired
The person's language (es, es-PR, en, pt, fr). Reply in that language.
permisosobjectrequired
What the bot may do in that chat. leer_grupo (always true in a 1:1), ubicacion (it asked for it in its manifest: it can request it; the person decides each time), estado (that person let it change their status).
contextoarray<Mensaje>required
The last 10 messages the bot can see, before this one (in a group without "read the whole group", only those addressed to it and its own).

mensaje

{"…sobre…": "…", "tipo": "mensaje",
 "mensaje": {"id": 301, "autor": {"tipo": "persona", "usuario": "ana", "nombre": "Ana Rivera", "avatar": "forma-3"},
             "texto": "/clima ¿y mañana?", "bloques": [], "responde_a": null, "menciones": [], "medio": "sonoe",
             "creado": "…", "editado": null},
 "menciona_al_bot": true,
 "responde_al_bot": false,
 "responde_a": {"id": 290, "autor": {"tipo": "bot", "nombre": "clima", "…": "…"}, "fragmento": "Hoy: 31° y sol"}}

menciona_al_bot is false only when the bot reads the whole group and the message wasn't for it (it can stay quiet).

comando

When the message is /bot command … (or, in a 1:1 with the bot, /command …) and command is in its manifest. It carries everything in mensaje, plus:

{"tipo": "comando", "comando": "hoy", "argumentos": "Ponce", "mensaje": {"…": "…"}}

accion

Someone tapped a button or picked an option from a list in one of the bot's messages:

{"tipo": "accion", "accion": "ver_semana", "valor": null, "mensaje": {"id": 290, "…": "…"}}
{"tipo": "accion", "accion": "pueblos", "valor": {"id": "ponce", "titulo": "Ponce"}, "mensaje": {"…": "…"}}

respuesta_de_entrada

The answer to one of the bot's requests (Ask the person for things). Only that bot receives it:

{"tipo": "respuesta_de_entrada", "pedido": {"id": "p_9a1c…", "tipo": "ubicacion", "mensaje_id": 302},
 "respuesta": {"ubicacion": {"lat": 18.3986, "lng": -66.0503, "precision": 12}}}

respuesta depends on the type: {"ubicacion": {…}} · {"valor": "a", "titulo": "Tren"} · {"confirmado": true} · {"texto": "…"} · {"campos": {"nombre": "…"}} · or {"rechazado": true} if the person said no.

agregado and quitado

You were added to a chat (a new 1:1 or a group) — a good moment to say hi with buttons — or removed from one (or the chat ended). In quitado the chat is gone: it comes as "chat": {"id": 12}.

reaccion

Someone reacted to one of your messages:

{"tipo": "reaccion", "mensaje_id": 290, "valor": "❤️", "tipo_reaccion": "emoji", "accion": "puesta"}

tipo_reaccion: emoji or sticker (Sonoe's sticker ids: sonoe-hola, sonoe-gracias, sonoe-jaja, sonoe-wow, sonoe-corazon, sonoe-fuego, sonoe-pensando, sonoe-listo, sonoe-voy, sonoe-guagua, sonoe-tren, sonoe-bot). accion: puesta (added) or quitada (removed).

Act

Write

POST /v1/bots/chats/{chat}/messages
{
  "texto": "Hoy en San Juan: 31° y sol. **Lleva agua.**",
  "bloques": [
    {"tipo": "tarjeta", "titulo": "San Juan", "subtitulo": "Hoy", "texto": "31° · sol · 10 % lluvia", "color": "#445ED9",
     "campos": [{"nombre": "Máxima", "valor": "31°"}, {"nombre": "Mínima", "valor": "24°"}]},
    {"tipo": "botones", "botones": [{"id": "ver_semana", "texto": "La semana", "estilo": "principal"},
                                    {"id": "radar", "texto": "Radar", "url": "https://…"}]}
  ],
  "responde_a": 301,
  "cerrar_actividad": true
}

→ 201 with the message.

textostringrequired
What's shown in any medium (Media and fallback text). Light Markdown: **bold**, _italic_, `code`, [link](https://…). Up to 4000 characters. @user in the text mentions that person (they get the notification as a mention).
bloquesarray<Bloque>optional
Up to 10 blocks. See Blocks.
responde_aintegeroptional
The message it replies to.
cerrar_actividadbooleanoptional
Defaults to true: your live activity ends with this message and its steps are saved in it as traza (Live activity).

Blocks

tipoFieldsFor
textotextoa separate paragraph
tarjetatitulo, subtitulo, texto, imagen (https), url (https), color (#RRGGBB), campos [{nombre, valor}] (≤10)a card
botonesbotones [{id, texto (≤40), estilo: normal·principal·peligro, url}] (1–6)actions → accion event (those with url only open it)
listaid, titulo, opciones [{id, titulo, detalle}] (1–20)a list to pick from (one option per row) → accion with valor
rutatitulo, destino, minutos, sale, llega, transbordos, minutos_a_pie, url, color, pasos [{tipo: pie·viaje·espera, texto, linea, color, minutos}]directions
lugarid, nombre, detalle, direccion, lat, lng, minutos, abierto, urla place
pedido(written by Sonoe: Ask the person for things)asking the person for something

Ids (the id of buttons, lists and options) are [A-Za-z0-9_.:-], up to 64. A malformed block: 422 naming the field (bloques[1].botones[0].texto).

Stream a reply live

POST /v1/bots/chats/{chat}/messages   {"flujo": true}          → 201 {"id": 305, "estado": "escribiendo", …}
POST /v1/bots/messages/305/delta      {"texto": "Hoy en "}
POST /v1/bots/messages/305/delta      {"texto": "San Juan: 31°…"}
POST /v1/bots/messages/305/end        {"bloques": […]}         → the finished message

People watch the text grow live. In end you can send the full texto (it replaces what was streamed) and the bloques; "cortado": true marks it as cut off (your model failed midway: it keeps what was streamed). The phone notification goes out when it finishes, not on every chunk. After 60 s without chunks, Sonoe closes it with what it had (marked cortado). A delta to a message that's already closed: 409.

Edit, delete, react

PATCH  /v1/bots/messages/{id}                    {"texto": "…", "bloques": […]}   (only yours; marked "edited")
DELETE /v1/bots/messages/{id}                    (the content is really deleted; "message deleted" remains)
POST   /v1/bots/messages/{id}/reactions          {"emoji": "👍"}  or  {"sticker": "sonoe-listo"}
DELETE /v1/bots/messages/{id}/reactions/{valor}

Read

GET /v1/bots/chats                          the chats you're in (with members, bots and your permissions)
GET /v1/bots/chats/{chat}                   one of them
GET /v1/bots/chats/{chat}/messages?before=&limit=50    the history you can see, oldest to newest, and "hay_mas"
GET /v1/bots/users/{usuario}                public profile and status of someone who shares a chat with you, their "locale" and "permite_estado"

Live activity

What the bot is doing. While it works, the bot publishes its state; the app draws it live in the chat (like a "typing…", but with what's really happening, and with steps that can be expanded):

PUT /v1/bots/chats/{chat}/activity
{
  "estado": "usando_herramienta",
  "texto": "Buscando rutas…",
  "herramienta": {"nombre": "lados.viaje", "etiqueta": "Calculando rutas"},
  "pasos": [
    {"titulo": "Buscando «Plaza Las Américas»", "estado": "hecho", "detalle": "Plaza Las Américas"},
    {"titulo": "Calculando rutas", "estado": "en_curso"},
    {"titulo": "Midiendo las caminatas", "estado": "pendiente"}
  ],
  "ttl": 45
}
estadoExtraReads as
pensando—Thinking…
buscandoconsultaSearching "…"
leyendofuente {titulo, url}Reading …
usando_herramientaherramienta {nombre, etiqueta}the label
escribiendo—Typing…
esperando_respuesta—Waiting for your answer…
listo—(removed)
  • texto: what people read, in their language (use the event's locale). Optional: if it's missing, the app uses the state's name.
  • pasos (≤12): titulo, estado (pendiente·en_curso·hecho·error), detalle. Send all of them on every update (they replace the previous ones). That's how you get "Searching routes… ✓ 3 options · Calculating walk…".
  • TTL: if the bot doesn't update within ttl seconds (30 by default, 120 at most), the activity disappears on its own (the bot went quiet or went down). Update before then to keep it.
  • End it with DELETE /v1/bots/chats/{chat}/activity (or estado: listo), or by sending a message with cerrar_actividad: true: that message keeps the steps as its traza (the app can show them below it).

Ask the person for things

POST /v1/bots/chats/{chat}/ask
{
  "tipo": "ubicacion",                      // ubicacion · eleccion · confirmacion · texto
  "pregunta": "¿Desde dónde sales?",
  "motivo": "Para buscar rutas desde donde estás. Solo lo ve este bot.",
  "para": "ana",                            // who answers; in a 1:1, the person (default)
  "minutos": 15                             // expires (30 by default, up to 1440)
}
→ 201 {"pedido": "p_9a1c…", "mensaje": {…}}
  • It shows up in the chat as a message with a pedido block. The person answers in the app and the answer reaches you as respuesta_de_entrada. It can be answered once.
  • Location: the bot must declare "necesita": ["ubicacion"] in its manifest (otherwise 403); the app asks for it with consent every time, and the location goes only to that bot, only for that request: it isn't stored in the chat (the message says "answered", never where). In a group you have to say who it's para (for).
  • Choice: "opciones": [{"id": "a", "titulo": "Tren", "detalle": "34 min"}, …] (2–12). The chat shows what was picked.
  • Confirmation: yes/no → {"confirmado": true|false}.
  • Text / form: without campos, free text; with "campos": [{"id": "nombre", "etiqueta": "Nombre", "tipo": "texto"|"numero", "requerido": true}] (≤5), a form → {"campos": {…}}.
  • The person can always say no → {"rechazado": true}.

Statuses

Every person (and every bot) can have a status: trabajando (working), escuchando (listening, with cancion and artista), en_camino (on the way, with destino), ocupado (busy), estudiando (studying), durmiendo (sleeping), jugando (playing) or personalizado (custom); with an emoji, a short texto (≤80) and, optionally, minutos so it clears itself. It shows in chats and profiles and arrives live.

PUT    /v1/bots/status                    {"tipo": "trabajando", "emoji": "🛠️", "texto": "Actualizando horarios"}   (the bot's own)
DELETE /v1/bots/status
PUT    /v1/bots/users/{usuario}/status    {"tipo": "escuchando", "emoji": "🎧", "cancion": "DtMF", "artista": "Bad Bunny", "minutos": 4}
DELETE /v1/bots/users/{usuario}/status    (only if the current status was set by this bot)

For a person's status, the bot declares "necesita": ["estado"] and the person allows it in the app (POST /v1/chat/status/grants {"bot": "musica"}; revoked with DELETE …/grants/musica). Without that: 403. The status shows its source: {"tipo": "bot", "nombre": "musica"}.

Manifest and permissions

What the bot declares (when it's created, when it's changed, or by itself on startup):

PUT /v1/bots/manifest
{
  "comandos": [{"nombre": "ir", "descripcion": {"es": "Cómo llegar", "en": "Directions"},
                "params": [{"nombre": "destino", "requerido": true}]}],
  "recibe": ["texto", "ubicacion"],          // texto · ubicacion · imagen (later)
  "necesita": ["ubicacion"],                 // leer_grupo · ubicacion · estado
  "idiomas": ["es", "es-PR", "en", "pt", "fr"]
}
  • comandos (≤30; name [a-z0-9_]): the app suggests them when you type /. The descripcion can be per language.
  • necesita grants nothing by itself: it's what can be granted. leer_grupo is granted by each group's admin (and everyone sees it); ubicacion is given by the person on each request; estado, by each person.
  • idiomas: the languages the bot speaks (the app can warn if the person uses another one).

Media and fallback text

What the protocol carries doesn't depend on the medium: a message is plain text (required) + blocks (optional). Sonoe's app draws the blocks; a bridge to another medium will do its own thing without the bot changing:

MediumHow it will look
sonoe (today)the blocks, native
webthe same blocks in HTML
whatsappcards → a formatted message; botones → reply buttons (≤3) or a list; lista → a list
smsthe texto; buttons as "Reply 1, 2…"
emailHTML with the blocks; buttons as links
vozthe texto read aloud; the options spoken

So: write a texto that makes sense on its own (without relying on the blocks), and use blocks for what gets tapped or looked at. Every message and event carries medio (always sonoe today); once there are bridges, an event will say where the person wrote from and Sonoe will take care of delivering your reply there.

Limits

WhatHow much
A bot's actions (not GET)240 per minute
Chunks in a stream1200 per minute
Message4000 characters, 10 blocks; body ≤ 64 KB
A person's messages60 per minute
ActivityTTL 1–120 s (30 by default), 12 steps
Stream without chunksclosed after 60 s
Request (ask)expires in 1–1440 min (30)
Unacknowledged events24 h
Webhookreply within 10 s; 5 retries (5 s → 30 min)
Bots per account20
Members per group100 (people and bots)
Someone's reactions to one message5

Going over: 429.

Hello bot

A minimal bot in Python, in connection mode:

import json, os
import httpx  # pip install httpx

API = os.environ.get("SONOE_API", "https://sonoeai.com")
H = {"Authorization": f"Bearer {os.environ['SONOE_BOT_TOKEN']}"}
HOLA = {"es": "¡Hola", "en": "Hi", "pt": "Oi", "fr": "Salut"}


def eventos(c: httpx.Client):
    """The bot's events, one by one (SSE: "data:" lines up to an empty line)."""
    with c.stream("GET", "/v1/bots/events", timeout=httpx.Timeout(10, read=60)) as r:
        datos = []
        for linea in r.iter_lines():
            if linea.startswith("data:"):
                datos.append(linea[5:].strip())
            elif not linea and datos:
                yield json.loads("\n".join(datos))
                datos = []


with httpx.Client(base_url=API, headers=H) as c:
    while True:  # the stream closes every hour: open it again
        for e in eventos(c):
            if e["tipo"] in ("mensaje", "comando"):
                chat = e["chat"]["id"]
                c.put(f"/v1/bots/chats/{chat}/activity", json={"estado": "pensando"})
                saludo = HOLA.get(e["locale"][:2], "¡Hola")
                c.post(f"/v1/bots/chats/{chat}/messages",
                       json={"texto": f"{saludo}, {e['de']['nombre']}! Dijiste: {e['mensaje']['texto']}"})
            if "id" in e:
                c.post("/v1/bots/events/ack", json={"ids": [e["id"]]})
SONOE_BOT_TOKEN=sb_bot_… python hola.py

Open a chat with your bot in the app and write to it. For anything serious: reconnect with growing backoff when it fails, and handle each event in its own task, like Lados's bot does.

Privacy and security

  • In transit: HTTPS. At rest: message text, its data (blocks, traces), the events waiting for a bot and each webhook's secret are stored encrypted (AES-256-GCM, with a server key). A copy of the database can't read them. The server can (end-to-end encryption, with keys only on the phones, will come later; bots will then have to declare it).
  • An acknowledged event (or one delivered by webhook) is deleted. A location only travels inside its event.
  • A bot sees only what's described in Concepts. Its location requests always go through the person's consent.

For what Sonoe's app uses (people, not bots), see The app API.