# Socket Mode

> Your app opens a WebSocket to Slaiky and gets its events, commands and clicks there. No public URL, nothing to host.

Source: https://slaiky.xyz/docs/socket-mode

In Socket Mode your code calls Slaiky, not the other way round. It opens a WebSocket, Slaiky sends each event, command and click down it as an envelope, and your app says "got it" for each one. Nothing has to be reachable from the internet: it runs on a laptop, behind a firewall, or on a server with no public address.

## When to use it

Use Socket Mode when your app runs as a process that stays up: a bot on your computer, a service inside your company network, a script you start by hand. Use [Events over HTTP](/docs/events) when you already have a public server that answers requests, or code that only wakes up when called.

It is one or the other. With Socket Mode on, Slaiky sends nothing to your request URLs.

Turn it on in the app’s page: **Events → Socket Mode**. In a [manifest](/docs/manifests), it is `"socket_mode_enabled": true`. The app’s page says **Connected** while a socket is open.

## Connect

Ask for an address with `apps.connections.open`, then open a WebSocket to it. The address works once, within 30 seconds: ask for a new one every time you connect. With Socket Mode off, the call answers `socket_mode_off`.

*your app → Slaiky · `apps.connections.open`*

```sh
curl -s https://app.slaiky.xyz/api/methods/apps.connections.open \
  -H "authorization: Bearer $SLAIKY_BOT_TOKEN" \
  -H 'content-type: application/json' -d '{}'
```

*Slaiky → your app*

```json
{ "ok": true, "url": "wss://app.slaiky.xyz/ws?ticket=docs-ticket" }
```

A client that can send headers on the handshake may skip the ticket: open the same `/ws` address with `Authorization: Bearer slk-bot-…`. The samples here use the ticket.

Every frame is JSON, `{ "t": type, "d": data }`. Besides envelopes you will see `ready` once, when the socket is set up, and `error` when Slaiky refused a frame you sent. Ignore any other frame.

## What arrives

Each envelope carries one thing that happened. Its `type` says which kind, and `payload` is the same body an app over HTTP would get.

| `type` | What it carries | `payload` |
| --- | --- | --- |
| `events_api` | An event the app asked for | The event wrapper, [Events](/docs/reference/events) |
| `slash_commands` | One of the app’s slash commands | The command, [payloads](/docs/reference/payloads#a-slash-command-slash-command) |
| `interactive` | A click, a pick, a shortcut, a modal submitted or closed | The interaction, [payloads](/docs/reference/payloads) |

*Slaiky → your app · `app.envelope`*

```json
{
  "t": "app.envelope",
  "d": {
    "envelopeId": "7f3c0006-5a1e-4c2b-9d6f-1a2b3c4d5e05",
    "type": "events_api",
    "payload": {
      "type": "event_callback",
      "eventId": "7f3c0006-5a1e-4c2b-9d6f-1a2b3c4d5e05",
      "event": { "type": "app_mention", "channelId": "…", "channelType": "channel", "message": { "id": "…", "body": "@docsrecorder is the deploy green?" } }
    },
    "acceptsResponsePayload": false,
    "retryAttempt": 0
  }
}
```

Every field is on [Socket Mode frames](/docs/reference/socket-mode#app-envelope).

## Acknowledge every envelope

Send `app.ack` with the envelope’s id as soon as it arrives, before any slow work. An event without an ack comes again after 30 seconds.

For a command or a click, `acceptsResponsePayload` is `true` and the ack can carry the answer in `payload`. The person is waiting: the ack must arrive within 3 seconds. What the answer may say is on [Commands, shortcuts and buttons](/docs/interactivity#answer-at-once).

*Slaiky → your app · `app.envelope`*

```json
{
  "t": "app.envelope",
  "d": {
    "envelopeId": "7f3c0020-5a1e-4c2b-9d6f-1a2b3c4d5e13",
    "type": "slash_commands",
    "payload": { "type": "command", "command": "/docsdemo", "text": "shipped the export", "userId": "…", "channelId": "…", "triggerId": "…", "responseUrl": "…" },
    "acceptsResponsePayload": true,
    "retryAttempt": 0
  }
}
```

*your app → Slaiky · `app.ack`*

```json
{ "t": "app.ack", "d": { "envelopeId": "7f3c0020-5a1e-4c2b-9d6f-1a2b3c4d5e13", "payload": { "text": "Noted: shipped the export", "responseType": "in_channel" } } }
```

An ack that doesn’t fit (a bad `payload`, an id that isn’t one) is refused with an `error` frame, `"code": "invalid"` and `"for": "app.ack"`, and the envelope stays unacknowledged. A socket may send up to 40 frames a second: acks over that are refused with `"code": "rate_limited"` and their envelopes come again.

## Resends and `retryAttempt`

An event you didn’t acknowledge is sent again after 30 seconds, up to 3 times while you are connected. Each resend has the same `envelopeId` and a higher `retryAttempt`. After the last one it is marked failed.

*Slaiky → your app · `app.envelope`*

```json
{ "t": "app.envelope", "d": { "envelopeId": "7f3c0006-5a1e-4c2b-9d6f-1a2b3c4d5e05", "type": "events_api", "payload": { "type": "event_callback", "eventId": "7f3c0006-5a1e-4c2b-9d6f-1a2b3c4d5e05", "event": { "type": "app_mention", "message": { "id": "…" } } }, "acceptsResponsePayload": false, "retryAttempt": 1 } }
```

*your app → Slaiky · `app.ack`*

```json
{ "t": "app.ack", "d": { "envelopeId": "7f3c0006-5a1e-4c2b-9d6f-1a2b3c4d5e05" } }
```

So keep the ids you handled and skip one that comes back. Acknowledge it again anyway: a second ack changes nothing.

Commands and clicks are sent once. They are answered now or not at all.

## What you missed while away

When your app connects, Slaiky sends the events it couldn’t deliver while you were away, oldest first, up to 1 hour old. Older ones are dropped. They arrive as normal envelopes: acknowledge them the same way.

Commands and clicks are not kept for later. While your app is away, a person who runs its command is told it isn’t connected.

Each delivery and how it went is on the app’s page, under **Deliveries**: see [the delivery log](/docs/events#the-delivery-log).

## Reconnect

A socket closes for a few reasons. Connect again for all of them but two.

| Close code | Why | What to do |
| --- | --- | --- |
| `1012` | The app’s settings changed (Socket Mode turned on or off, its permissions), or Slaiky is restarting for a release | Connect again now, with a new `apps.connections.open` |
| `4401` | The token that opened the socket stopped working: someone made a new one | Stop. Start again with the new token |
| `4403` | The app was removed, the bot was turned off, or its workspace deleted | Stop |
| anything else | The network | Connect again, waiting a little longer each time |

This bot does all of it: it acknowledges first, answers a command in the ack, skips what it already handled and reconnects.

*your app → Slaiky · `socket-mode-bot.mjs`*

```js
// A Socket Mode bot that keeps going: it acknowledges first, skips envelopes it already handled,
// answers a slash command in its ack, and connects again when the socket closes. Node 22+, no packages.
// SLAIKY_BOT_TOKEN=slk-bot-… node socket-mode-bot.mjs
const API = process.env.SLAIKY_API ?? 'https://app.slaiky.xyz/api/methods';
const TOKEN = process.env.SLAIKY_BOT_TOKEN;

async function call(method, body = {}) {
  const res = await fetch(`${API}/${method}`, {
    method: 'POST',
    headers: { authorization: `Bearer ${TOKEN}`, 'content-type': 'application/json' },
    body: JSON.stringify(body),
  });
  const data = await res.json();
  if (!data.ok) throw Object.assign(new Error(`${method}: ${data.error.code} ${data.error.message}`), { code: data.error.code });
  return data;
}

// What the ack says back: the answer to a command or a click, said at once (or nothing).
function answerNow(d) {
  if (d.type === 'slash_commands') return { text: `Got it: ${d.payload.text || '(nothing)'}` };
  return undefined;
}

// The slow work, after the ack.
async function work(d) {
  const event = d.payload.event;
  if (d.type === 'events_api' && event?.type === 'app_mention') {
    await call('chat.postMessage', { channel: event.channelId, threadId: event.message.parentId ?? event.message.id, text: 'On it.' });
  }
}

const seen = new Set(); // envelope ids already handled: a resend brings the same id again
let wait = 1000;

async function connect() {
  let url;
  try {
    ({ url } = await call('apps.connections.open')); // a one-time URL: ask for a new one every time
  } catch (err) {
    if (err.code === 'unauthorized' || err.code === 'socket_mode_off') return console.error(err.message);
    setTimeout(connect, wait);
    wait = Math.min(wait * 2, 60_000);
    return;
  }

  const socket = new WebSocket(url);
  socket.onopen = () => {
    wait = 1000;
    console.log('Connected.');
  };

  socket.onmessage = ({ data }) => {
    const frame = JSON.parse(data);
    if (frame.t === 'error') return console.error('Slaiky refused a frame:', frame.d.code, frame.d.message);
    if (frame.t !== 'app.envelope') return;
    const d = frame.d;
    const again = seen.has(d.envelopeId);
    const payload = d.acceptsResponsePayload && !again ? answerNow(d) : undefined;
    // 1. Say "got it" first (again for a resend: a second ack changes nothing).
    socket.send(JSON.stringify({ t: 'app.ack', d: { envelopeId: d.envelopeId, ...(payload ? { payload } : {}) } }));
    if (again) return;
    seen.add(d.envelopeId);
    if (seen.size > 5000) seen.delete(seen.values().next().value);
    // 2. Then do the work.
    work(d).catch((err) => console.error('envelope failed:', err.message));
  };

  socket.onclose = ({ code }) => {
    // 4401: the token behind this socket was replaced. 4403: the app was removed or the bot turned off.
    if (code === 4401 || code === 4403) return console.error(`Closed (${code}). Check the app and its token.`);
    // 1012: the app's settings changed or Slaiky is restarting: connect again now. Anything else: wait a little longer each time.
    setTimeout(connect, code === 1012 ? Math.random() * 1000 : wait);
    if (code !== 1012) wait = Math.min(wait * 2, 60_000);
  };
}

connect();
```

## One connection or several

Slaiky sends every envelope to every socket your app has open. The first ack counts; for a command, the first ack’s `payload` is the answer and later ones are ignored. So two processes on one app both see each event.

Run one connection per app. While you switch to a new version, two can overlap for a moment: keep the handled ids where both can see them, so only one of them acts. A bot may hold up to 100 sockets open at once; more are refused with `429`.

> **Tip:** Testing on your computer while the real bot runs elsewhere? Make a second app for it. Two sockets on one app split nothing: both get everything.

## Without Socket Mode: the older frames

Apps written before Socket Mode open a socket with their bot token (the `Authorization` header) while Socket Mode is off. They still work. Such a socket gets `app.command` and `app.interaction`. When the app holds `app_mentions:read` and every `:history` permission, it also gets `app.mention` (the bot was mentioned where it is a member) and the workspace’s live frames such as `message.created`.

Nothing on that socket is acknowledged, resent or replayed. A command there carries a `responseToken`: answer it with [`commands.respond`](/docs/reference/methods/commands.respond). New apps should use Socket Mode.
