# Slack

A Slack app's back end: messages and threads, reactions, files, people and
channels read page by page, modals and the home tab, over Slack's Web API;
and what Slack sends the app (events, slash commands, buttons, modals
submitted) as routes that check Slack's signature, answer within its three
seconds, and do the work in a [job](back-end.md#later-job-fn). An
[extension](../extensions/README.md): `extensions/slack/`. A line to a
channel through an incoming webhook alone is [alert](alert.md). Back to the
[map](README.md).

```mote
use "pkg:slack/events.mote"

// "/ticket printer on fire": said at once, then opened in a job and posted to the channel.
fn slackCommandNow(c: SlackCommand): string = `Opening "${c.text}"…`

fn slackCommand(c: SlackCommand): SlackReply
  let t = Ticket.add({title: c.text, by: c.user})?
  return {text: `Ticket ${t.id}: ${c.text}`, everyone: true, blocks: [slackSection(`*${c.text}*\nopened by <@${c.user}>`), slackActions("ticket", [slackButton("Close", "close", t.id, "danger")])]}

// The button, pressed: the ticket closed, and the message changed in its place.
fn slackAction(a: SlackAction): SlackReply
  if a.action != "close" return {text: ""}
  Ticket.set(a.value, {open: false})?
  return {text: `Closed by <@${a.user}>`, replace: true}

// @-mentioned: an answer in the thread.
fn slackEvent(e: SlackEventIn): bool
  if e.type == "app_mention"
    slackReply(e.channel, e.ts, {text: "On it."}, "")?
  return true
```

```sh
SLACK_BOT_TOKEN=xoxb-… SLACK_SIGNING_SECRET=… bun dist/server/main.js
```

**Not met Slack.** Written from Slack's API reference as of 2026 and run
against a stand-in (`tests/svc_standin.mjs chat`); the signature is checked
against the example in Slack's own "Verifying requests from Slack" page
(the slash command's body, timestamp `1531420618`, its secret and its
`v0=a2114d…b503`), which `slackVerify` takes. The steps to check it with a
real workspace are [below](#checking-it-against-slack).

## The settings

| | |
|---|---|
| `SLACK_BOT_TOKEN` | The bot's token (`xoxb-…`, OAuth & Permissions), a [secret](back-end.md#secrets). Every call takes a `token`: `""` for this one, or another: a person's `xoxp-…` token to act as them, or an install's own bot token for an app on several workspaces (both got by OAuth, which is not this extension's); or `"team:T0123"`, the bot token the program keeps for that workspace, given by its `fn slackTeamToken(team: string): string` (each event, command and action says its `team`: answer with `"team:" + e.team`). An app only on several workspaces declares `fn slackBotToken(): string` as well, and needs no `SLACK_BOT_TOKEN`. |
| `SLACK_SIGNING_SECRET` | Basic Information → Signing Secret, a secret. |
| `SLACK_WAIT` | The longest `Retry-After` waited out, in seconds: 30 unsaid. |
| `SLACK_TOLERANCE` | How far a request's timestamp may be from now, in seconds: 300 unsaid. |
| `SLACK_API` | Another address for the Web API (a stand-in). |

The app's settings at api.slack.com/apps: Event Subscriptions → Request URL
`<site>/slack/events` (and the bot events to hear: `app_mention`,
`message.channels`, `reaction_added`, `app_home_opened`, …); Slash Commands
→ each command's Request URL `<site>/slack/commands`; Interactivity &
Shortcuts → `<site>/slack/interactivity`. The scopes are the calls':
`chat:write`, `reactions:write`, `files:write`, `users:read` (and
`users:read.email`), `channels:read`, `channels:history`, `im:write`,
`commands`.

## The calls

`use "pkg:slack/slack.mote"` (`events.mote` takes it). Each is the back
end's, can fail, and takes the `token` last.

| | |
|---|---|
| `slackPost(channel, m, token)` | A message: a `SlackPosted` (`channel`, `ts`, `text`). `m` is a `SlackOut`: `text` (the notification's words), `blocks`, `thread` (the ts it replies under), `broadcast`, `unfurl`, `username`, `icon`, `metadata`. |
| `slackSay(channel, text, token)` · `slackReply(channel, ts, m, token)` | A line; a reply in a thread. |
| `slackWhisper(channel, user, m, token)` | Seen only by `user` (chat.postEphemeral). |
| `slackUpdate(channel, ts, m, token)` · `slackDelete(channel, ts, token)` | |
| `slackDm(user, m, token)` | To a person, in their DM with the bot. |
| `slackLink(channel, ts, token)` | A message's permanent link. |
| `slackReact(channel, ts, "eyes", token)` · `slackUnreact(…)` | Already there, or already gone, is not a failure. |
| `slackUser(id, token)` · `slackUserByEmail(email, token)` · `slackUsers(most, token)` | `SlackUser`: `id`, `name` (the one shown), `realName`, `handle`, `email`, `bot`, `deleted`, `admin`, `tz`, `image`. |
| `slackChannel(id, token)` · `slackChannels(types, most, token)` · `slackMembers(channel, most, token)` · `slackJoin(channel, token)` | `SlackChannel`: `id`, `name`, `private`, `im`, `archived`, `member`, `members`, `topic`, `purpose`. |
| `slackHistory(channel, oldest, latest, cursor, token)` · `slackThread(channel, ts, cursor, token)` | One page: `SlackHistory` (`messages`, `next`: the cursor of the next page, `""` at the end). |
| `slackPage(method, args, key, cursor, token)` · `slackAll(method, args, key, most, token)` | Any list Slack gives a cursor for, a page or every page. |
| `slackUpload({name, data, title?, comment?, channel?, thread?}, token)` | A file, Slack's way since files.upload went: an address asked for, the bytes sent there, then completed and shared. A `SlackFile`. |
| `slackOpen(trigger, view, token)` · `slackPush(…)` · `slackUpdateView(id, view, hash, token)` | A modal (`trigger`: the trigger_id of a command or a button, good for three seconds). A `SlackViewed` (`id`, `hash`). |
| `slackHome(user, view, token)` | A person's home tab. |
| `slackWhoAmI(token)` | The token's team, user and bot. |
| `slackCall(method, args, token)` · `slackRead(method, args, token)` | Any other method: a write as a form (records and lists in it as JSON), a read as a GET. |

**Block Kit** (`blocks.mote`) is shapes with Slack's own field names
(`SlackBlock`, `SlackElement`, `SlackText`, `SlackOption`, `SlackView`), so
a block is sent as written, and fns for the ones a product uses:
`slackSection(md)`, `slackSectionWith(md, accessory)`,
`slackFieldsBlock([md…])`, `slackHeader`, `slackDivider()`,
`slackContext([md…])`, `slackImage(url, alt)`, `slackActions(id,
[elements])`, `slackButton(text, action, value, style)`,
`slackLinkButton(text, url, action)`, `slackSelect(action, placeholder,
[slackOption(text, value)…])`, `slackUserSelect`, `slackDatePicker`,
`slackTextInput(action, multiline)`, `slackConfirm(…)`, `slackInput(block,
label, element)`, `slackModal(title, blocks, submit, callback)`,
`slackHomeView(blocks)`. A block these do not make is a literal: Slack's
Block Kit Builder shows any block's JSON.

**Failures** say Slack's code (`Slack refused chat.postMessage:
channel_not_found`), with a kind: `"auth"` (a bad or revoked token, or a
missing scope: `data.needed` names it), `"missing"`, `"refused"` (not in
the channel, archived), `"invalid"`, `"limited"`, `"slack"` (5xx), `"offline"`.

**Limits.** Slack limits each method by its tier, per workspace, and says
when to come back in `Retry-After` on a 429. A read is asked again by
`net.send` after that wait; a write is asked again here, twice at most (a
429 means it was not done). While a method is waited on, every other call
of it waits too (the `SlackLimit` model); a wait longer than `SLACK_WAIT`
is a failure of kind `"limited"` with `data.retryAfter`, not a job hung for
minutes. `chat.postMessage` has a limit of its own of about one message a
second in each channel: post a burst from a job, not a loop in a call.

## What Slack sends

`use "pkg:slack/events.mote"`: three routes, each of which checks the
signature first (`X-Slack-Signature`, `v0=` and an HMAC-SHA256 of
`v0:<timestamp>:<body>`, compared in constant time by
[`webhook.check`](back-end.md#webhooks)'s `"slack"`; a timestamp more than
five minutes away is a replay, refused) and answers at once.

| Route | |
|---|---|
| `POST /slack/events` | The url_verification challenge answered; each event kept by its `event_id` (the `SlackEvent` model) and done once in a job, though Slack sends it again when an answer is slow. |
| `POST /slack/commands` | `fn slackCommandNow(c)` in the answer (its words seen only by the person; the place to open a modal with `c.trigger`), then `fn slackCommand(c)` in a job, its `SlackReply` posted to the command's `response_url`. |
| `POST /slack/interactivity` | A button, a select, a shortcut: `fn slackActionNow(a)` in the answer, then `fn slackAction(a)` in a job, its reply to the `response_url`. A modal submitted: `fn slackCheck(v)` in the answer (its errors, `{block_id: "why"}`, shown in the modal), then `fn slackSubmitted(v)` in a job. |

Each hook is optional. Those in a job are tried again when they fail: make
them safe to run twice. Those in the answer share Slack's three seconds
with the check and the answer itself: one call to Slack (a modal opened)
fits; more goes in the job.

A `SlackReply` is `{text, blocks?, everyone?, replace?, remove?}`: seen by
the channel when `everyone`, else by the person alone; `replace` puts it in
the place of the message the button was on, `remove` takes that message
away. `text` empty and no blocks: nothing is posted. `slackRespond(url,
reply)` posts one yourself (five at most, for half an hour).

A modal's values: `slackValue(v.values, block, action)` (a text, a
select's choice, a date, a person, a channel) and `slackValues(…)` (a
multi-select's).

## In a person's name

Every call takes its `token` last, so a person's own token (`xoxp-…`)
works wherever the bot's does: the message is then theirs. The
[oauth](oauth.md) extension's Slack is *Sign in with Slack* (OpenID
Connect, the user scopes `openid email profile`), so the token
`oauthToken(slackProvider(), user)` gives says who they are and may do
nothing else: it cannot post. A token with user scopes for the Web API
(`chat:write`, …) comes from Slack's OAuth v2 install flow
(`oauth.v2.access`, `user_scope`), which neither extension has yet. With
one in hand, kept by the program:

```mote
server fn postAsMe(channel: string, text: string): string requires signedIn
  let token = myUserToken()?   // the program's own: a person's xoxp-… token, kept sealed
  return slackSay(channel, text, token)?.ts
```

## Left out

- **Socket Mode** (events over a WebSocket, for an app with no public
  address): the back end's WebSocket client is there now
  ([`ws.open`](back-end.md#connections-of-its-own)). What remains is a
  `server start` that connects to `apps.connections.open`'s address,
  acknowledges each envelope and hands it to the same hooks.
- OAuth (installing on other workspaces): the token is given to each call;
  getting one is another extension's.
- The legacy `files.upload`, attachments, incoming webhooks (that is
  [alert](alert.md)), Workflow Builder steps, the RTM API, Enterprise Grid's
  admin methods, the `options` load URL of external selects.

## Checking it against Slack

1. Make an app at api.slack.com/apps (From scratch), add the bot scopes
   above, install it to a workspace of your own; `SLACK_BOT_TOKEN` is the
   Bot User OAuth Token, `SLACK_SIGNING_SECRET` the Signing Secret.
2. Run the program where Slack reaches it (a tunnel to `localhost`), and set
   the three Request URLs. Slack sends url_verification when the events'
   address is saved: it says "Verified".
3. `slackSay("<a channel id>", "hello", "")` after `/invite @yourbot` in
   that channel: the message shows; without the invite, `not_in_channel`
   is the failure.
4. Mention the bot: `slackEvent` hears `app_mention` once. A slash command:
   its first words at once, then the reply from the job. A button in that
   reply: the message changes. A modal opened from a command (as `/form` does in
   `tests/svc_chat/app.mote`): an empty field shows the error from
   `slackCheck`.
5. `slackUpload` of a small file to the channel: it shows with its comment.
   `slackUsers(500, "")` gives everyone, page after page.

Recorded in `tests/expect/real_svc_chat.txt` (`tests/all.sh real_svc_chat`):
the signature refused unsigned, wrongly signed and old; the challenge; an
event sent twice and done once; a command, a modal opened from a command, a
button, a modal's errors and its submission; a file in three steps; people
in two pages; a 429 waited out; a refusal's words; and the extension's own
`mote test`.
