The ecosystem · packages/slack
A Slack bot, answered by a handler of your own
A mention or a direct message reaches your handler with a client that has packages/chat's methods, so the same handler answers on every chat platform. Plain Roc on the server's HTTP client and WebSocket: no SDK.
Installing it#
Name the package in the app's header with the four it uses (chat, crypto, tools, websocket), and list its plugin with your handler. The example's main.roc:
## Acme's helpdesk on Slack (packages/slack): a bot that answers a mention in a channel, in a thread
## of its own, and a direct message, with a handler written for packages/chat (`Helpdesk.answer!`,
## which knows nothing of Slack). Events come to `routes/slack/events` (Slack's Events API, checked
## against SLACK_SIGNING_SECRET); with SLACK_APP_TOKEN set, over Socket Mode instead.
app [program] { chat: "../../chat/main.roc", crypto: "../../crypto/main.roc", pf: platform "../../../server/platform/main.roc", slack: "../main.roc", tools: "../../tools/main.roc", websocket: "../../websocket/main.roc" }
import slack.Slack
import Helpdesk
import Generated/App
program = App.program({
init!: |_started| Ok({}),
plugins: [Slack.plugin({ on_message!: Helpdesk.answer! })],
})Then set SLACK_BOT_TOKEN, and SLACK_APP_TOKEN for Socket Mode or SLACK_SIGNING_SECRET for the Events API, in the environment or the .env that rocx dev reads. Without a bot token the server doesn't start, except under --dev, where it logs Slack off; an app whose bot is optional says required: Bool.False, and starts with the bot off. Once started it says who the bot is:
Slack bot @helpdesk (U0123ABC), hearing events over Socket ModeA Slack app#
At api.slack.com/apps, create an app from a manifest:
display_information:
name: Acme Helpdesk
features:
bot_user:
display_name: helpdesk
always_online: true
app_home:
messages_tab_enabled: true
messages_tab_read_only_enabled: false
oauth_config:
scopes:
bot: [app_mentions:read, chat:write, channels:history, groups:history, im:history, reactions:write, users:read, files:read]
settings:
event_subscriptions:
bot_events: [app_mention, message.im]
socket_mode_enabled: trueInstall it (the bot token, xoxb-…), make an app-level token with connections:write under Basic Information (xapp-…), and invite the bot into a channel. It answers whoever writes to it where it is invited, so where it is invited decides who may reach it.
How events arrive#
- Socket Mode (
SLACK_APP_TOKEN): the plugin keeps a WebSocket open to Slack, acknowledges each envelope at once, and connects again when Slack asks or the connection breaks. No public URL: it works on a laptop. - The Events API (
SLACK_SIGNING_SECRET): Slack POSTs each event to a route of yours, which checks its signature and its age (five minutes at most), answers the URL's challenge, and acknowledges at once:
import slack.Slack
## POST /slack/events: where Slack's Events API sends the bot's events (the URL in the Slack app's
## Event Subscriptions), checked against SLACK_SIGNING_SECRET.
respond! = |{ request, .. }| Slack.events_route!(request)Either way the event waits in a queue in the server's memory, and the plugin's worker hands messages to your handler one at a time, in order, so a long answer never keeps Slack waiting past its three seconds. An event Slack sends again is handled once.
What reaches the handler#
A mention in a channel, answered in its own thread, and a direct message, answered where it was written. The bot's own messages, other bots', edits and joins don't reach it. The text comes as Markdown, the mention taken out; the writer's name is looked up and kept a day. The example's handler, which knows nothing of Slack:
import chat.Chat
## Acme's helpdesk bot, for any chat platform: it shows it's working, answers, and is done. `help`
## says what it does, `history` counts the thread's messages, `long` writes more than one message
## holds (sent in pieces), and anything else is said back. It names no platform: Slack's client,
## or any other with packages/chat's methods, answers it.
Helpdesk := [].{
## A message, answered.
answer! : Chat.Message, c => Try({}, Str)
where [
c.working! : c, Chat.Message, Bool => Try({}, Str),
c.reply! : c, Chat.Message, Str => Try(Chat.Sent, Str),
c.history! : c, Chat.Message, U64 => Try(List(Chat.Message), Str),
c.max_length : c -> U64,
]
answer! = |message, client| {
client.working!(message, Bool.True)?
said = message.text.trim()
answer =
if said == "help" {
"**Acme helpdesk.** Ask me anything, or say `history` to count this thread's messages."
} else if said == "history" {
earlier = client.history!(message, 50)?
mine = earlier.count_if(|each| each.bot)
"This thread has ${earlier.len().to_str()} messages, ${mine.to_str()} of them mine."
} else if said == "long" {
var $lines = []
var $n = 1.U64
while $n <= 400 {
$lines = $lines.append("Line ${$n.to_str()} of a long answer.")
$n = $n + 1
}
Str.join_with($lines, "\n")
} else {
"Hi ${message.user.name}, you said: _${said}_"
}
_ = Chat.reply_long!(client, message, answer)?
client.working!(message, Bool.False)
}
}A handler's Err is logged, and the next message goes on.
The client#
| Method | What it calls |
|---|---|
reply! | chat.postMessage in the thread, the Markdown written as Slack's mrkdwn, links not unfurled |
edit!, react! | chat.update; reactions.add ("👀" or Slack's name) |
working! | 👀 on the message while the bot works, taken off after |
history! | conversations.replies, or a direct conversation's conversations.history |
download! | a file's private URL, with the bot's token |
call!(method, fields) | any Web API method; a rate limit is waited out as retry-after says |
Slack.client!({}) is the client for a message the app sends on its own, a reminder or a report.
The example app#
packages/slack/example is Acme's helpdesk: help, history (the thread's messages, counted), long (an answer in pieces), and anything else said back. Its tests run it against a stand-in for Slack and check what it asked of Slack; they never call Slack. The package's README.md is the reference, and its PROPOSALS.md what is next: buttons, slash commands, a thread's replies without a mention, a workspace installing the app.