Slack
- Introduction
- Setting up a Slack app
- Routing notifications
- Writing messages
- Buttons and menus
- Testing
Introduction
Many teams already monitor Slack for deploys, payments, and operational alerts, making it a natural place to deliver notifications. dust-framework can send notifications to Slack as Block Kit messages with sections, fields, images, and interactive buttons that trigger application code directly, such as refunding an invoice from a payment alert.
For example, suppose your application has a Team model. This notification alerts a team when their site is deployed:
use dust::notification;use dust::slack::{self, Button, Message, Section};pub struct Deployed { pub site: String, pub commit: String, pub url: String,}#[notification]impl Deployed { fn slack(&self, _team: &Team) -> Message { Message::new(format!("{} was deployed", self.site)) .header("Deployment finished") .section(Section::new(slack::markdown!( "Deployed `{}` to *{}*.", self.commit, self.site, ))) .actions([Button::link("View deployment", &self.url).primary()]) }}Send it through notification::to(&team).send(deployed) once you've set up a Slack app and given the team a Slack route.
Setting up a Slack app
Before you send Slack messages, create a Slack app. The app is the bot that posts your messages, and its token goes in SLACK_BOT_TOKEN. To post to your own workspace, such as alerts for your team:
- Open Your Apps, select Create New App, then From scratch. Name the app and pick your workspace.
- Open OAuth & Permissions. Under Bot Token Scopes, add
chat:write. - Select Install to Workspace, then Allow.
- Copy the Bot User OAuth Token, which starts with
xoxb-, intoSLACK_BOT_TOKEN. - Invite the app to each channel it posts to, by typing
/invite @YourAppin the channel.
To post to any public channel without an invitation, add the chat:write.public scope too. Private channels always need the invitation.
| Scope | Needed for |
|---|---|
chat:write |
Posting messages and updating them |
chat:write.public |
Posting to public channels without inviting the app |
chat:write.customize |
Overriding the username or icon |
incoming-webhook |
Letting an OAuth install choose a channel for a webhook |
users:read.email |
Looking up a user's slack_id by email |
When your messages include buttons or menus, also configure SLACK_SIGNING_SECRET for receiving interactions. Applications that post exclusively to customers' workspaces store per-workspace tokens and leave SLACK_BOT_TOKEN unset; configure those under posting to your users' workspaces.
Routing notifications
Notifiables implement ReceivesSlack to specify where their Slack messages are delivered.
Posting to your own workspace
Suppose your teams table has a nullable slack_channel_id column:
use dust::notification::ReceivesSlack;use dust::slack::Route;impl ReceivesSlack for Team { fn slack_route(&self) -> Option<Route> { self.slack_channel_id.as_deref().map(Route::channel) }}When slack_route returns None, as it does here for a team that hasn't picked a channel, the notifiable doesn't receive Slack messages.
Route::channel takes a channel ID, such as C0123ABCDEF, or a name, such as #ops. Prefer IDs, because they still work after someone renames the channel. You'll find a channel's ID at the bottom of its details in Slack. Passing a user ID, such as U0123ABCDEF, posts to that user's direct messages with your app once you enable the Messages Tab under App Home in your Slack app's settings.
If you don't need to pick channels dynamically or manage a bot token, you can route notifications to a Slack incoming webhook instead using Route::webhook. This is useful for letting customers paste a webhook URL into their notification settings, or for posting internal alerts without configuring SLACK_BOT_TOKEN:
use dust::notification::ReceivesSlack;use dust::slack::Route;impl ReceivesSlack for Team { fn slack_route(&self) -> Option<Route> { self.slack_webhook_url.as_deref().map(Route::webhook) }}Each incoming webhook is tied to the specific channel chosen when it was created in Slack, so dust-framework posts every message directly to that channel. Unlike bot tokens, incoming webhooks cannot post to arbitrary channels or customize the sender's username and icon.
Posting to your users' workspaces
A platform that notifies its customers, such as with deployment messages in each team's channel, needs its app in each customer's workspace. Each customer adds your app through Slack's OAuth flow, which gives your application a bot token for their workspace.
Distributing your app
- In your app's settings, open OAuth & Permissions. Under Redirect URLs, add your callback URL, such as
https://example.com/slack/callback. It must use HTTPS. - Add the bot token scopes your app needs, such as
chat:writeandincoming-webhook. Withincoming-webhook, the person who adds the app picks a channel on Slack's consent screen. - Open Manage Distribution and activate public distribution. Other workspaces can then add your app without a listing in the Slack Marketplace.
- Copy the Client ID and Client Secret from Basic Information, and add them to your
.envfile:
SLACK_CLIENT_ID=1234567890.1234567890
SLACK_CLIENT_SECRET=your-client-secretdust-framework reads both values into your slack configuration so slack::authorize_url and slack::install use them automatically.
Adding the app to a workspace
Two handlers add the app: one that sends the customer to Slack, and one that Slack sends them back to. The first stores a random state in the session, and the second checks it, so another site can't connect its own workspace to your customer's team.
Suppose each user has a team_id column and your Team model defines a nullable slack_channel_id column along with an encrypted slack_bot_token: Option<Encrypted<String>> column. slack::authorize_url builds Slack's consent screen URL with your client ID, the requested scopes, and the state. After the customer approves your app, slack::install exchanges the code Slack sends back for the workspace's bot token and the channel the customer picked, and the callback stores both on the team:
use dust::auth::Authenticated;use dust::model::update;use dust::prelude::*;use dust::slack;pub async fn connect(session: Session) -> dust::Result<Redirect> { let state = dust::str::random(40); session.put("slack_state", &state); Ok(Redirect::to(slack::authorize_url( &state, ["chat:write", "incoming-webhook"], )?))}#[dust::query]pub struct Callback { code: String, state: String,}pub async fn callback( user: Authenticated<User>, session: Session, Query(Callback { code, state: sent }): Query<Callback>,) -> dust::Result<Redirect> { let state = session.pull::<String>("slack_state"); dust::abort_unless(state.as_deref() == Some(sent.as_str()), 403)?; let installation = slack::install(&code).await?; let mut team = Team::find_or_fail(user.team_id).await?; update!(team { slack_channel_id: installation.webhook.map(|webhook| webhook.channel_id), slack_bot_token: installation.bot_token, }) .await?; Ok(Redirect::to("/settings/notifications"))}When the customer cancels, Slack sends them back with an error query parameter instead of a code, so the callback responds with a 400.
Register both handlers in routes::web for authenticated users so the session middleware is active. Assuming the handlers live in http::handlers::slack_app:
use dust::auth::Authenticate;pub fn routes(route: &mut Router) { route.middleware(Authenticate).group(|route| { route.get("/slack/connect", slack_app::connect); route.get("/slack/callback", slack_app::callback); });}Then link to the first route with an Add to Slack button on your team's settings page:
<a href="/slack/connect">Add to Slack</a>Routing to an installation
Once a team has connected their workspace, update your ReceivesSlack implementation to authenticate each notification with that team's own bot token rather than the global SLACK_BOT_TOKEN. Because slack_bot_token is an Encrypted<String> column, dust-framework decrypts it automatically when the model loads, so you can pass it straight to .token(...):
use dust::notification::ReceivesSlack;use dust::slack::Route;impl ReceivesSlack for Team { fn slack_route(&self) -> Option<Route> { Some( Route::channel(self.slack_channel_id.as_deref()?) .token(self.slack_bot_token.as_ref()?.as_str()), ) }}Teams often want their messages in another channel later, such as one they pick on your settings page. Store that channel's ID in slack_channel_id instead, and ask the team to invite your app to the channel with /invite @YourApp. A public channel needs no invitation when the app has the chat:write.public scope.
Writing messages
A notification's slack method returns a slack::Message initialized with fallback text. Slack displays this text in desktop and mobile notifications and exposes it to screen readers instead of blocks, so keep it aligned with your block content:
use dust::slack::Message;let message = Message::new("Invoice #42 was paid by Taylor");Text and escaping
Slack reads &, <, and > as markup. For example, <!channel> notifies a whole channel, and <https://example.com|click> is a link. dust-framework escapes these characters in every string you give a message, so a customer who names themselves <!channel> can't notify your whole channel. Slack's other formatting still works in strings, such as *bold*, _italic_, and `code`.
To send mentions, links, and dates, build slack::Markdown, which dust-framework sends as it is:
| Function | Returns |
|---|---|
slack::markdown!("*{}* paid", name) |
Markdown formatted like format! that escapes interpolated arguments unless they are Markdown |
slack::mention(user_id) |
A mention that notifies the user, as in <@U0123ABCDEF> |
slack::link(url, label) |
A link with an escaped label |
slack::date(timestamp) |
A date and time that each reader sees in their own time zone |
Markdown::raw(markup) |
Markup you write yourself, such as <!here> |
Combine them with markdown!:
use dust::slack;let text = slack::markdown!( "{} deployed {} at {}", slack::mention("U0123ABCDEF"), slack::link("https://forge.test", "forge.test"), slack::date(dust::now()),);Never pass text that users wrote to Markdown::raw.
Blocks

Chain block methods on Message to stack Block Kit elements in order from top to bottom:
use dust::slack::{Button, Image, Message, Section};let message = Message::new("Invoice #42 was paid") .header("Invoice paid") .section( Section::new("Taylor paid invoice *#42*.") .field("Amount", "$1,200") .field("Plan", "Pro") .accessory(Image::new("https://example.com/avatars/taylor.png", "Taylor")), ) .divider() .image("https://example.com/charts/revenue.png", "Revenue this month") .actions([ Button::link("View invoice", "https://example.com/invoices/42").primary(), Button::link("Billing", "https://example.com/billing"), ]) .context(["Sent by Example"]);| Method | Adds |
|---|---|
header(text) |
Large, bold, plain text |
section(section) |
A Section, or text for one |
divider() |
A line between blocks |
image(url, alt_text) |
An image |
actions(elements) |
Buttons and menus side by side |
context(elements) |
Small text and images |
block(block) |
Any block, including a serde_json::Value for blocks without a builder, such as rich_text |
A Section can contain markdown text, up to ten two-column fields, and a single accessory element (a button, menu, or image). actions and context accept an array of homogeneous elements, or a tuple when mixing element types (such as .context((Image::new(avatar_url, "Taylor"), "Deployed by Taylor"))).
Use Button::link(label, url) to open a URL and Button::action(label, action) to trigger an interactive action. Chain .primary() for a green button, .danger() for a red button, and .confirm("Refund $1,200?") to require confirmation before firing the action.
[!NOTE] To inspect a message's layout while designing it, print
message.builder_url(), which opens Slack's Block Kit Builder preloaded with your blocks.
Message options
Beyond blocks, Message supports options for threading and link previews: call thread(ts) to reply inside an existing thread, reply_broadcast() to also echo the reply to the channel, and unfurl_links(false) or unfurl_media(false) to disable automatic previews.
To post under another name or icon, such as a "Deploy bot" with a rocket, call username(name), icon_emoji(":rocket:"), or icon_url(url). These need the chat:write.customize scope, and webhooks ignore them:
use dust::slack::Message;Message::new("Deploy finished.") .thread(&self.thread_ts) .unfurl_links(false) .username("Deploy bot") .icon_emoji(":rocket:")Slack's limits
Slack refuses messages over its Block Kit limits, such as 50 blocks a message, 3,000 characters of section text, and 75 characters in a button's label. dust-framework checks each message against these limits before it sends anything, so a message over a limit fails in your tests rather than only in production.
When Slack refuses a message for another reason, the send fails with Slack's error, such as channel_not_found or not_in_channel.
| Error | Meaning | Fix |
|---|---|---|
channel_not_found |
The channel ID is wrong, or the app cannot see it | Correct the ID or invite the app |
not_in_channel |
The bot is not a member of a private channel | Run /invite @YourApp in that channel |
invalid_auth, token_revoked |
The token is missing, wrong, or was revoked | Set SLACK_BOT_TOKEN or reinstall the app |
ratelimited |
Too many messages reached Slack in a short window | Queue the message and let its retry wait |
msg_too_long |
The message exceeds a Block Kit limit | Split it into smaller messages |
When a notification is queued, a rejected Slack message lands in failed_jobs so you can inspect Slack's message and retry it after fixing the cause.
Buttons and menus
Some messages ask for a response, such as a payment alert with a Refund button or an incident with a menu to set its priority. When someone clicks a button or picks from a menu, Slack sends a request to your application. dust-framework checks that Slack signed the request, then runs the button's action, which may update the message or reply to the person who clicked.
Receiving interactions
You only need to configure an interaction endpoint if your Slack messages include interactive action buttons (Button::action) or menus. If you only send one-way notifications or link buttons (Button::link), you can skip this setup.
Add a route for
slack::interactionstoroutes::api, whose routes skip CSRF protection:rustuse dust::slack;pub fn routes(route: &mut Router) { route.post("/slack/interactions", slack::interactions);}In your app's settings, open Interactivity & Shortcuts and turn on Interactivity. Set the Request URL to the route's URL, such as
https://example.com/api/slack/interactions. If Socket Mode is enabled, turn it off under Settings first, becauseslack::interactionsreceives requests over HTTP.Copy the Signing Secret from Basic Information into
SLACK_SIGNING_SECRET.
Slack expects a response within three seconds, so slack::interactions queues each action and responds immediately. Run a queue worker, or set QUEUE_CONNECTION=sync in development to execute actions synchronously during the request.
Writing actions
An action is a serializable struct with #[slack::action] on the impl defining its async handle method. Actions are discovered automatically by dust-framework as long as their module is declared in src/lib.rs, so you can define an action right alongside the notification that renders its button (for example, in src/notifications/), or group them into a dedicated src/slack/ module as your application grows.
For example, suppose your users table has nullable slack_id and is_admin columns, and your invoices table has a nullable refunded_at column. This action refunds an invoice when an admin clicks its button:
use dust::model::update;use dust::slack::{self, Interaction};use serde::{Deserialize, Serialize};#[derive(Serialize, Deserialize)]pub struct Refund { pub invoice_id: i64,}#[slack::action]impl Refund { async fn handle(self, interaction: &Interaction) -> dust::Result<()> { let user = User::first_where(User::slack_id.eq(interaction.user_id())).await?; let Some(user) = user else { return interaction.reply("Connect your Slack account to refund invoices.").await; }; if !user.is_admin { return interaction.reply("Only admins can refund invoices.").await; } let mut invoice = Invoice::find_or_fail(self.invoice_id).await?; update!(invoice { refunded_at: dust::now() }).await?; let message = slack::markdown!( "Invoice #{} refunded by {}", self.invoice_id, slack::mention(interaction.user_id()), ); interaction.update(message).await }}Put the action in a button, and Slack sends it back with each click:
use dust::slack::Button;Button::action("Refund", Refund { invoice_id: 42 }).danger().confirm("Refund $1,200?")handle takes self, and optionally an &Interaction, Inject<T> services, and Section<T> config sections. It returns () or dust::Result<()>.
The message stores the action's fields, so keep them to IDs and load the rest in handle. Nobody can change the fields, because Slack signs each request, but anyone who can see the message can click the button. Always check in handle that the person who clicked may do what the action does, as Refund does above.
Because actions run as queued jobs, #[slack::action] accepts the same options as #[job], such as queue, tries, and a stable name:
#[slack::action(name = "refund", queue = "slack", tries = 3)]impl Refund { async fn handle(self, interaction: &Interaction) -> dust::Result<()> { // ... }}[!NOTE] To populate a user's
slack_id, most apps either look it up by email using Slack'susers.lookupByEmailWeb API method (which requires theusers:read.emailbot scope) and cache the ID on the user, or store it when a user connects their Slack account via OAuth.
Menus
You can add interactive menus inside an actions block or attach one beside a section's text with Section::accessory.
A Select displays a dropdown of up to 100 custom options bound to actions of the same type, dispatching the chosen option's action when selected. For example, suppose your application defines a SetPriority action with an incident_id and a Level enum:
use dust::slack::{Message, Select};let priority = Select::new("Set priority") .option("Low", SetPriority { incident_id: 7, level: Level::Low }) .option("High", SetPriority { incident_id: 7, level: Level::High });Message::new("Incident #7 opened").actions([priority])When you want a compact "⋯" button instead of a full dropdown, use Overflow with up to five options. It pairs naturally with Section::accessory for secondary actions:
use dust::slack::{Overflow, Section};let menu = Overflow::new() .option( "Acknowledge", ManageIncident { incident_id: 7, action: IncidentAction::Acknowledge }, ) .option("Close", ManageIncident { incident_id: 7, action: IncidentAction::Close });Section::new("Incident *#7*: API latency spike").accessory(menu)To let someone pick from the workspace's users, use UsersSelect with the action to dispatch:
use dust::slack::{Message, UsersSelect};Message::new("Incident #7 opened").actions([ UsersSelect::new("Assign to...", AssignIncident { incident_id: 7 }),])Inside your action's handle method, call interaction.selected_user() to read the chosen user's Slack ID:
if let Some(slack_user_id) = interaction.selected_user() { // Assign the incident...}Similarly, ConversationsSelect lets someone pick a Slack channel or conversation from the workspace, and interaction.selected_conversation() returns the chosen conversation ID inside handle:
use dust::slack::{ConversationsSelect, Message};Message::new("Incident #7 opened").actions([ ConversationsSelect::new("Forward to channel...", ForwardIncident { incident_id: 7 }),])Replying to the user
Interaction responds through the response URL Slack includes with each interaction payload, so it does not require a bot token.
To send an ephemeral message visible only to the user who clicked the button or menu, call reply:
interaction.reply("Only admins can refund invoices.").await?;To replace the original message containing the button or menu, call update. Both reply and update accept plain text, slack::Markdown, or a full slack::Message with blocks:
use dust::slack::{Message, Section};interaction .update( Message::new("Invoice #42 refunded") .section(Section::new("Invoice *#42* has been refunded.")), ) .await?;To remove the original message altogether, call delete:
interaction.delete().await?;Slack permits up to five replies per interaction within 30 minutes; after that window, send a regular notification instead.
Testing
In tests, you can verify that Slack notifications are sent with the expected content without posting to a real workspace. The notification fake records Slack messages alongside other channels, and message::<Slack>() returns the built message:
use dust::model::create;use dust::notification::{self, Slack};use dust::testing::prelude::*;#[dust::test]async fn deploying_notifies_the_team(app: Application) -> dust::Result<()> { let team = create!(Team { name: "Forge", slack_channel_id: "C0123ABCDEF" }).await?; let notifications = notification::fake(); app.post(format!("/teams/{}/deployments", team.id)).await.assert_ok(); notifications.assert_sent_to_where::<Deployed>(&team, |sent| { sent.message::<Slack>().is_some_and(|message| message.text().contains("was deployed")) }); Ok(())}A message over Slack's limits fails the test, as it would fail a real send. To check the JSON that Slack receives, fake the HTTP client instead, and read the body of the request to slack.com/api/chat.postMessage.