Slack
- Introduction
- Setting up a Slack app
- Routing notifications
- Writing messages
- Buttons and menus
- Testing
Introduction
Many teams already watch Slack for deploys, payments, and operational alerts, which makes it a natural place to deliver notifications. Laravel can send notifications to Slack as Block Kit messages with sections, fields, images, and interactive buttons that run your application's code when someone clicks them, 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:
1// notifications/deployed.go2package notifications34import (5 "go.laravel.com/notification"6 "go.laravel.com/slack"78 "app/models"9)1011type Deployed struct {12 Site string13 Commit string14 URL string15}1617func (n Deployed) Messages(team *models.Team) (notification.Messages, error) {18 return notification.Messages{19 Channels: []any{slack.Message{20 Text: slack.Markdownf("%s was deployed", n.Site),21 Blocks: []slack.Block{22 slack.Header{Text: "Deployment finished"},23 slack.Section{Text: slack.Markdownf("Deployed `%s` to *%s*.", n.Commit, n.Site)},24 slack.Actions{Elements: []slack.Element{25 slack.Button{Label: "View deployment", URL: n.URL, Style: slack.Primary},26 }},27 },28 }},29 }, nil30}1// notifications/deployed.go2package notifications34import (5 "go.laravel.com/notification"6 "go.laravel.com/slack"78 "app/models"9)1011type Deployed struct {12 Site string13 Commit string14 URL string15}1617func (n Deployed) Messages(team *models.Team) (notification.Messages, error) {18 return notification.Messages{19 Channels: []any{slack.Message{20 Text: slack.Markdownf("%s was deployed", n.Site),21 Blocks: []slack.Block{22 slack.Header{Text: "Deployment finished"},23 slack.Section{Text: slack.Markdownf("Deployed `%s` to *%s*.", n.Commit, n.Site)},24 slack.Actions{Elements: []slack.Element{25 slack.Button{Label: "View deployment", URL: n.URL, Style: slack.Primary},26 }},27 },28 }},29 }, nil30}
Send it with notification.Send(r, deployed, team) 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.
When your messages include buttons or menus, also set SLACK_SIGNING_SECRET for receiving interactions. Applications that post only to their customers' workspaces store a token for each workspace and leave SLACK_BOT_TOKEN unset, as posting to your users' workspaces describes.
Routing notifications
A notifiable has a SlackRoute method that returns a slack.Route, which says where its Slack messages are delivered.
Posting to your own workspace
Suppose your teams table has a slack_channel_id column, which is empty for a team that hasn't picked a channel:
1// models/team.go2func (t Team) SlackRoute() slack.Route {3 return slack.Route{Channel: t.SlackChannelID}4}1// models/team.go2func (t Team) SlackRoute() slack.Route {3 return slack.Route{Channel: t.SlackChannelID}4}
When SlackRoute returns a route without a channel or a webhook, as it does here for a team that hasn't picked a channel, the notifiable doesn't receive Slack messages.
A route's 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. A user ID, such as U0123ABCDEF, posts to that user's direct messages with your app once you turn on the Messages Tab under App Home in your Slack app's settings.
If you don't need to pick channels as your application runs or manage a bot token, you may route notifications to a Slack incoming webhook instead by setting the route's Webhook. This is useful for letting customers paste a webhook URL into their notification settings, or for posting internal alerts without setting SLACK_BOT_TOKEN:
1// models/team.go2func (t Team) SlackRoute() slack.Route {3 return slack.Route{Webhook: t.SlackWebhookURL}4}1// models/team.go2func (t Team) SlackRoute() slack.Route {3 return slack.Route{Webhook: t.SlackWebhookURL}4}
Each incoming webhook is tied to the channel chosen when it was created in Slack, so Laravel posts every message to that channel. Unlike a bot token, an incoming webhook can't post to other channels or change the sender's name 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:
1SLACK_CLIENT_ID=1234567890.12345678902SLACK_CLIENT_SECRET=your-client-secret1SLACK_CLIENT_ID=1234567890.12345678902SLACK_CLIENT_SECRET=your-client-secret
Laravel reads both values for you, and the slack functions in the next section use them, so your application doesn't pass them around itself.
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 teams table has a slack_channel_id column and a nullable text column named slack_bot_token. Anyone who holds the bot token can post as your app in the customer's workspace, so encrypt the column:
1// models/team.go2type Team struct {3 ID int64 `json:"id"`4 Name string `json:"name"`5 SlackChannelID string `json:"slack_channel_id"`6 SlackBotToken *crypt.Encrypted[string] `json:"-"`7 CreatedAt time.Time `json:"created_at"`8 UpdatedAt time.Time `json:"updated_at"`9}1// models/team.go2type Team struct {3 ID int64 `json:"id"`4 Name string `json:"name"`5 SlackChannelID string `json:"slack_channel_id"`6 SlackBotToken *crypt.Encrypted[string] `json:"-"`7 CreatedAt time.Time `json:"created_at"`8 UpdatedAt time.Time `json:"updated_at"`9}
slack.AuthorizeURL returns the address of Slack's consent screen, with your client ID, the scopes, and the state. After the customer allows the app, slack.Install trades the code that Slack sends back for the workspace's bot token and the channel the customer picked. The callback stores both on the team:
1// handlers/slackapp/slackapp.go2package slackapp34import (5 "crypto/rand"6 "net/http"78 "go.laravel.com/db"9 "go.laravel.com/model"10 "go.laravel.com/slack"11 "go.laravel.com/web"1213 "app/models"14)1516func Connect(r *web.Request) *web.Response {17 state := rand.Text()1819 r.Session().Put("slack.state", state)2021 return web.Redirect(slack.AuthorizeURL(r, state, "chat:write", "incoming-webhook"))22}2324func Callback(r *web.Request) *web.Response {25 var params struct {26 State string `json:"state"`27 Code string `json:"code"`28 }29 if err := r.QueryInto(¶ms); err != nil {30 return web.Fail(err)31 }3233 state, _ := r.Session().Pull[string]("slack.state")34 if state == "" || state != params.State {35 return web.Abort(http.StatusForbidden)36 }3738 if params.Code == "" {39 return web.Abort(http.StatusBadRequest)40 }4142 installation, err := slack.Install(r, params.Code)43 if err != nil {44 return web.Fail(err)45 }4647 team, err := model.Find[models.Team](r, r.User[models.User]().TeamID)48 if err != nil {49 return web.Fail(err)50 }5152 err = model.Update(r, &team, db.Values{53 "slack_channel_id": installation.Webhook.ChannelID,54 "slack_bot_token": installation.BotToken,55 })56 if err != nil {57 return web.Fail(err)58 }5960 return web.Redirect("/settings/notifications")61}1// handlers/slackapp/slackapp.go2package slackapp34import (5 "crypto/rand"6 "net/http"78 "go.laravel.com/db"9 "go.laravel.com/model"10 "go.laravel.com/slack"11 "go.laravel.com/web"1213 "app/models"14)1516func Connect(r *web.Request) *web.Response {17 state := rand.Text()1819 r.Session().Put("slack.state", state)2021 return web.Redirect(slack.AuthorizeURL(r, state, "chat:write", "incoming-webhook"))22}2324func Callback(r *web.Request) *web.Response {25 var params struct {26 State string `json:"state"`27 Code string `json:"code"`28 }29 if err := r.QueryInto(¶ms); err != nil {30 return web.Fail(err)31 }3233 state, _ := r.Session().Pull[string]("slack.state")34 if state == "" || state != params.State {35 return web.Abort(http.StatusForbidden)36 }3738 if params.Code == "" {39 return web.Abort(http.StatusBadRequest)40 }4142 installation, err := slack.Install(r, params.Code)43 if err != nil {44 return web.Fail(err)45 }4647 team, err := model.Find[models.Team](r, r.User[models.User]().TeamID)48 if err != nil {49 return web.Fail(err)50 }5152 err = model.Update(r, &team, db.Values{53 "slack_channel_id": installation.Webhook.ChannelID,54 "slack_bot_token": installation.BotToken,55 })56 if err != nil {57 return web.Fail(err)58 }5960 return web.Redirect("/settings/notifications")61}
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.go for authenticated users, so the session middleware is active:
1// routes/web.go2route.Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {3 route.Get("/slack/connect", slackapp.Connect)4 route.Get("/slack/callback", slackapp.Callback)5})1// routes/web.go2route.Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {3 route.Get("/slack/connect", slackapp.Connect)4 route.Get("/slack/callback", slackapp.Callback)5})
Then link to the first route with an Add to Slack button on your team's settings page:
1<a href="/slack/connect">Add to Slack</a>1<a href="/slack/connect">Add to Slack</a>
Routing to an installation
Once a team has connected their workspace, update the team's SlackRoute method to post each notification with that team's own bot token rather than SLACK_BOT_TOKEN. Because SlackBotToken is a crypt.Encrypted[string], Laravel decrypts it when the model loads, so you may pass its Value as the route's Token:
1// models/team.go2func (t Team) SlackRoute() slack.Route {3 if t.SlackBotToken == nil || t.SlackChannelID == "" {4 return slack.Route{}5 }67 return slack.Route{Channel: t.SlackChannelID, Token: t.SlackBotToken.Value}8}1// models/team.go2func (t Team) SlackRoute() slack.Route {3 if t.SlackBotToken == nil || t.SlackChannelID == "" {4 return slack.Route{}5 }67 return slack.Route{Channel: t.SlackChannelID, Token: t.SlackBotToken.Value}8}
A team that hasn't added your app gets an empty route, so the team doesn't receive Slack messages.
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 posts to Slack by adding a slack.Message to its Channels. A message starts with its fallback text. Slack displays this text in desktop and mobile notifications and gives it to screen readers in place of the blocks, so keep it in step with your blocks:
1message := slack.Message{Text: "Invoice #42 was paid by Taylor"}1message := slack.Message{Text: "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. A message's text, a section's text, and a section's fields are slack.Markdown, which Laravel sends as it is, so text you write in your code may use Slack's formatting, such as *bold*, _italic_, and `code`.
Text from anywhere else, such as a customer's name, must be escaped, so a customer who names themselves <!channel> can't notify your whole channel. Go won't put a string variable in a slack.Markdown field, so build the markdown with these functions:
| Function | Returns |
|---|---|
slack.Markdownf("*%s* paid", |
Markdown formatted like fmt.Sprintf, which escapes each argument unless it's slack.Markdown |
slack.Escape(text) |
The text with &, <, and > escaped |
slack.Mention(userID) |
A mention that notifies the user, as in <@U0123ABCDEF> |
slack.Link(url, |
A link with an escaped label |
slack.Date(t) |
A date and time that each reader sees in their own time zone |
Combine them with Markdownf, which leaves each one as it is because it's already slack.Markdown:
1text := slack.Markdownf(2 "%s deployed %s at %s",3 slack.Mention("U0123ABCDEF"),4 slack.Link("https://forge.test", "forge.test"),5 slack.Date(date.Now(ctx)),6)1text := slack.Markdownf(2 "%s deployed %s at %s",3 slack.Mention("U0123ABCDEF"),4 slack.Link("https://forge.test", "forge.test"),5 slack.Date(date.Now(ctx)),6)
To send markup of your own, such as <!here>, convert a constant, as in slack.Markdown("<!here> The deploy failed."). Never convert text that users wrote.
Blocks

List Block Kit elements in the message's Blocks, in order from top to bottom:
1message := slack.Message{2 Text: "Invoice #42 was paid",3 Blocks: []slack.Block{4 slack.Header{Text: "Invoice paid"},5 slack.Section{6 Text: "Taylor paid invoice *#42*.",7 Fields: []slack.Field{8 {Label: "Amount", Value: "$1,200"},9 {Label: "Plan", Value: "Pro"},10 },11 Accessory: slack.Image{URL: "https://example.com/avatars/taylor.png", AltText: "Taylor"},12 },13 slack.Divider{},14 slack.Image{URL: "https://example.com/charts/revenue.png", AltText: "Revenue this month"},15 slack.Actions{Elements: []slack.Element{16 slack.Button{17 Label: "View invoice",18 URL: "https://example.com/invoices/42",19 Style: slack.Primary,20 },21 slack.Button{Label: "Billing", URL: "https://example.com/billing"},22 }},23 slack.Context{Elements: []slack.ContextElement{slack.Markdown("Sent by Example")}},24 },25}1message := slack.Message{2 Text: "Invoice #42 was paid",3 Blocks: []slack.Block{4 slack.Header{Text: "Invoice paid"},5 slack.Section{6 Text: "Taylor paid invoice *#42*.",7 Fields: []slack.Field{8 {Label: "Amount", Value: "$1,200"},9 {Label: "Plan", Value: "Pro"},10 },11 Accessory: slack.Image{URL: "https://example.com/avatars/taylor.png", AltText: "Taylor"},12 },13 slack.Divider{},14 slack.Image{URL: "https://example.com/charts/revenue.png", AltText: "Revenue this month"},15 slack.Actions{Elements: []slack.Element{16 slack.Button{17 Label: "View invoice",18 URL: "https://example.com/invoices/42",19 Style: slack.Primary,20 },21 slack.Button{Label: "Billing", URL: "https://example.com/billing"},22 }},23 slack.Context{Elements: []slack.ContextElement{slack.Markdown("Sent by Example")}},24 },25}
| Block | Adds |
|---|---|
slack.Header |
Large, bold, plain text |
slack.Section |
Markdown text, up to ten two-column fields, and a single accessory (a button, menu, or image) |
slack.Divider |
A line between blocks |
slack.Image |
An image |
slack.Actions |
Buttons and menus side by side |
slack.Context |
Small text and images, such as a slack.Image beside slack.Markdown("Deployed by Taylor") |
slack.JSONBlock |
Any block, written as Slack's JSON, for blocks without a type here, such as rich_text |
A slack.Button with a URL opens the URL, and one with an Action runs an interactive action. Set Style: slack.Primary for a green button or slack.Danger for a red button, and Confirm: &slack.Confirm{Text: "Refund $1,200?"} to require confirmation before the action runs.
To inspect a message's layout while designing it, print the link that message.BuilderURL() returns, which opens Slack's Block Kit Builder preloaded with your blocks.
Message options
Beyond blocks, a message has fields for threading and link previews: set Thread to a message's timestamp to reply inside its thread, ReplyBroadcast to also show the reply in the channel, and HideLinkPreviews or HideMediaPreviews to turn off Slack's automatic previews.
To post under another name or icon, such as a "Deploy bot" with a rocket, set Username, and IconEmoji or IconURL. These fields need the chat:write.customize scope, and webhooks ignore them:
1message := slack.Message{2 Text: "Deploy finished.",3 Thread: "1700000000.000100",4 HideLinkPreviews: true,5 Username: "Deploy bot",6 IconEmoji: ":rocket:",7}1message := slack.Message{2 Text: "Deploy finished.",3 Thread: "1700000000.000100",4 HideLinkPreviews: true,5 Username: "Deploy bot",6 IconEmoji: ":rocket:",7}
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. Laravel checks each message against these limits as the notification builds it, 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.
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. Laravel 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 an interaction endpoint if your messages include buttons with an Action or menus. If you only send one-way notifications or buttons with a URL, you may skip this setup.
-
Mount
slack.Interactionsinroutes/api.go, whose routes skip CSRF protection:1// routes/api.go2route.Handle("POST /slack/interactions", slack.Interactions{})1// routes/api.go2route.Handle("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 run actions during the request.
Writing actions
An action is a type whose fields are its data. Its Handle method receives the ctx and a *slack.Interaction. You may define an action beside the notification that renders its button, or group your actions in an actions package as your application grows.
For example, suppose your users table has 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:
1// actions/refund.go2package actions34import (5 "context"6 "database/sql"7 "errors"89 "go.laravel.com/date"10 "go.laravel.com/db"11 "go.laravel.com/model"12 "go.laravel.com/slack"1314 "app/models"15)1617type Refund struct {18 InvoiceID int64 `json:"invoice_id"`19}2021func (a Refund) Handle(ctx context.Context, interaction *slack.Interaction) error {22 user, err := model.Query[models.User]().Where("slack_id", "=", interaction.UserID).First(ctx)23 if errors.Is(err, sql.ErrNoRows) {24 return interaction.Reply(ctx, slack.Message{25 Text: "Connect your Slack account to refund invoices.",26 })27 }28 if err != nil {29 return err30 }3132 if !user.IsAdmin {33 return interaction.Reply(ctx, slack.Message{Text: "Only admins can refund invoices."})34 }3536 _, err = db.Table("invoices").37 Where("id", "=", a.InvoiceID).38 Update(ctx, db.Values{"refunded_at": date.Now(ctx)})39 if err != nil {40 return err41 }4243 text := slack.Markdownf("Invoice #%d refunded by %s", a.InvoiceID, slack.Mention(interaction.UserID))4445 return interaction.Update(ctx, slack.Message{Text: text})46}1// actions/refund.go2package actions34import (5 "context"6 "database/sql"7 "errors"89 "go.laravel.com/date"10 "go.laravel.com/db"11 "go.laravel.com/model"12 "go.laravel.com/slack"1314 "app/models"15)1617type Refund struct {18 InvoiceID int64 `json:"invoice_id"`19}2021func (a Refund) Handle(ctx context.Context, interaction *slack.Interaction) error {22 user, err := model.Query[models.User]().Where("slack_id", "=", interaction.UserID).First(ctx)23 if errors.Is(err, sql.ErrNoRows) {24 return interaction.Reply(ctx, slack.Message{25 Text: "Connect your Slack account to refund invoices.",26 })27 }28 if err != nil {29 return err30 }3132 if !user.IsAdmin {33 return interaction.Reply(ctx, slack.Message{Text: "Only admins can refund invoices."})34 }3536 _, err = db.Table("invoices").37 Where("id", "=", a.InvoiceID).38 Update(ctx, db.Values{"refunded_at": date.Now(ctx)})39 if err != nil {40 return err41 }4243 text := slack.Markdownf("Invoice #%d refunded by %s", a.InvoiceID, slack.Mention(interaction.UserID))4445 return interaction.Update(ctx, slack.Message{Text: text})46}
List a value of each action type in your application's options, in bootstrap/app.go, so the queue worker can find an action when Slack sends it back. A click on an action type that isn't listed does nothing:
1SlackActions: []slack.Action{actions.Refund{}},1SlackActions: []slack.Action{actions.Refund{}},
Put the action in a button, and Slack sends it back with each click:
1slack.Button{2 Label: "Refund",3 Action: actions.Refund{InvoiceID: 42},4 Style: slack.Danger,5 Confirm: &slack.Confirm{Text: "Refund $1,200?"},6}1slack.Button{2 Label: "Refund",3 Action: actions.Refund{InvoiceID: 42},4 Style: slack.Danger,5 Confirm: &slack.Confirm{Text: "Refund $1,200?"},6}
Handle returns an error, which fails the action's job as an error fails any other job.
The message stores the action's fields as JSON, 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, an action may have the same JobOptions method as other jobs, such as to give it its own queue and a few tries:
1func (Refund) JobOptions() queue.Options {2 return queue.Options{Queue: "slack", Tries: 3}3}1func (Refund) JobOptions() queue.Options {2 return queue.Options{Queue: "slack", Tries: 3}3}
Slack also sends the action's name back with each click. By default, the name is the type's package path and name, such as app/actions.Refund, so moving or renaming the type breaks the buttons in messages you've already sent. Before you rename an action, give it an ActionName method that returns its old name. For example, if you rename Refund to IssueRefund:
1func (IssueRefund) ActionName() string { return "app/actions.Refund" }1func (IssueRefund) ActionName() string { return "app/actions.Refund" }
To fill in a user's slack_id, most applications either look it up by email with Slack's users.lookupByEmail Web API method, which needs the users:read.email bot scope, and store the ID on the user, or store it when the user connects their Slack account through OAuth.
Menus
You may add menus inside an Actions block, or attach one beside a section's text as the section's Accessory.
A slack.Select displays a dropdown of up to 100 options, each with an action of the same type, and picking an option runs its action. For example, suppose your application defines a SetPriority action with an IncidentID and a Level:
1priority := slack.Select{Placeholder: "Set priority", Options: []slack.Option{2 {Label: "Low", Action: actions.SetPriority{IncidentID: 7, Level: "low"}},3 {Label: "High", Action: actions.SetPriority{IncidentID: 7, Level: "high"}},4}}56message := slack.Message{7 Text: "Incident #7 opened",8 Blocks: []slack.Block{slack.Actions{Elements: []slack.Element{priority}}},9}1priority := slack.Select{Placeholder: "Set priority", Options: []slack.Option{2 {Label: "Low", Action: actions.SetPriority{IncidentID: 7, Level: "low"}},3 {Label: "High", Action: actions.SetPriority{IncidentID: 7, Level: "high"}},4}}56message := slack.Message{7 Text: "Incident #7 opened",8 Blocks: []slack.Block{slack.Actions{Elements: []slack.Element{priority}}},9}
When you want a compact "⋯" button instead of a full dropdown, use slack.Overflow with up to five options. It pairs well with a section's Accessory for secondary actions:
1menu := slack.Overflow{Options: []slack.Option{2 {Label: "Acknowledge", Action: actions.ManageIncident{IncidentID: 7, Status: "acknowledged"}},3 {Label: "Close", Action: actions.ManageIncident{IncidentID: 7, Status: "closed"}},4}}56section := slack.Section{Text: "Incident *#7*: API latency spike", Accessory: menu}1menu := slack.Overflow{Options: []slack.Option{2 {Label: "Acknowledge", Action: actions.ManageIncident{IncidentID: 7, Status: "acknowledged"}},3 {Label: "Close", Action: actions.ManageIncident{IncidentID: 7, Status: "closed"}},4}}56section := slack.Section{Text: "Incident *#7*: API latency spike", Accessory: menu}
To let someone pick from the workspace's users, use slack.UsersSelect with the action to run:
1assign := slack.UsersSelect{2 Placeholder: "Assign to...",3 Action: actions.AssignIncident{IncidentID: 7},4}1assign := slack.UsersSelect{2 Placeholder: "Assign to...",3 Action: actions.AssignIncident{IncidentID: 7},4}
Inside your action's Handle method, read the chosen user's Slack ID from interaction.SelectedUser:
1if slackUserID := interaction.SelectedUser; slackUserID != "" {2 // Assign the incident...3}1if slackUserID := interaction.SelectedUser; slackUserID != "" {2 // Assign the incident...3}
Similarly, slack.ConversationsSelect lets someone pick a channel or conversation from the workspace, and interaction.SelectedConversation holds the chosen conversation's ID inside Handle:
1forward := slack.ConversationsSelect{2 Placeholder: "Forward to channel...",3 Action: actions.ForwardIncident{IncidentID: 7},4}1forward := slack.ConversationsSelect{2 Placeholder: "Forward to channel...",3 Action: actions.ForwardIncident{IncidentID: 7},4}
Replying to the user
A *slack.Interaction responds through the response URL that Slack sends with each click, so it doesn't need a bot token.
To send a message that only the person who clicked the button or menu can see, call Reply:
1err := interaction.Reply(ctx, slack.Message{Text: "Only admins can refund invoices."})1err := interaction.Reply(ctx, slack.Message{Text: "Only admins can refund invoices."})
To replace the message that holds the button or menu, call Update. Both Reply and Update take a slack.Message, so the response may have blocks too:
1err := interaction.Update(ctx, slack.Message{2 Text: "Invoice #42 refunded",3 Blocks: []slack.Block{slack.Section{Text: "Invoice *#42* has been refunded."}},4})1err := interaction.Update(ctx, slack.Message{2 Text: "Invoice #42 refunded",3 Blocks: []slack.Block{slack.Section{Text: "Invoice *#42* has been refunded."}},4})
To remove the message altogether, call Delete:
1err := interaction.Delete(ctx)1err := interaction.Delete(ctx)
Slack permits up to five responses to a click within 30 minutes. After that, send a notification instead.
Testing
In tests, you may check that Slack notifications are sent with the expected content without posting to a real workspace. The notification fake records Slack messages along with the other channels, and Message[slack.Message]() returns the message that was built:
1package feature_test23import (4 "fmt"5 "strings"6 "testing"78 "go.laravel.com/model"9 "go.laravel.com/notificationtest"10 "go.laravel.com/slack"1112 "app/models"13 "app/notifications"14 "app/tests"15)1617func TestDeployingNotifiesTheTeam(t *testing.T) {18 client := tests.New(t)19 sent := notificationtest.New(client)2021 team := &models.Team{Name: "Forge", SlackChannelID: "C0123ABCDEF"}22 if err := model.Create(client.Context(), team); err != nil {23 t.Fatal(err)24 }2526 client.Post(fmt.Sprintf("/teams/%d/deployments", team.ID), nil).AssertOK()2728 sent.AssertSentTo(team, func(deployed notificationtest.Sent[notifications.Deployed]) bool {29 message, ok := deployed.Message[slack.Message]()3031 return ok && strings.Contains(string(message.Text), "was deployed")32 })33}1package feature_test23import (4 "fmt"5 "strings"6 "testing"78 "go.laravel.com/model"9 "go.laravel.com/notificationtest"10 "go.laravel.com/slack"1112 "app/models"13 "app/notifications"14 "app/tests"15)1617func TestDeployingNotifiesTheTeam(t *testing.T) {18 client := tests.New(t)19 sent := notificationtest.New(client)2021 team := &models.Team{Name: "Forge", SlackChannelID: "C0123ABCDEF"}22 if err := model.Create(client.Context(), team); err != nil {23 t.Fatal(err)24 }2526 client.Post(fmt.Sprintf("/teams/%d/deployments", team.ID), nil).AssertOK()2728 sent.AssertSentTo(team, func(deployed notificationtest.Sent[notifications.Deployed]) bool {29 message, ok := deployed.Message[slack.Message]()3031 return ok && strings.Contains(string(message.Text), "was deployed")32 })33}
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.
To test an action, you may call its Handle method with an Interaction of your own. A slacktest.Fake records the action's response in place of sending it to Slack, and sets the response's Response field to slack.Replied, slack.Updated, or slack.Deleted. For example, this test checks that the Refund action turns away a user who isn't an admin:
1func TestOnlyAdminsCanRefundInvoices(t *testing.T) {2 client := tests.New(t)3 posts := slacktest.New(client)45 // Create a user who isn't an admin, with the Slack ID U0123ABCDEF...67 interaction := &slack.Interaction{UserID: "U0123ABCDEF", ChannelID: "C0123ABCDEF"}89 err := actions.Refund{InvoiceID: 42}.Handle(client.Context(), interaction)10 if err != nil {11 t.Fatal(err)12 }1314 posts.AssertSent(func(post slack.Post) bool {15 return post.Response == slack.Replied && post.Message.Text == "Only admins can refund invoices."16 })17}1func TestOnlyAdminsCanRefundInvoices(t *testing.T) {2 client := tests.New(t)3 posts := slacktest.New(client)45 // Create a user who isn't an admin, with the Slack ID U0123ABCDEF...67 interaction := &slack.Interaction{UserID: "U0123ABCDEF", ChannelID: "C0123ABCDEF"}89 err := actions.Refund{InvoiceID: 42}.Handle(client.Context(), interaction)10 if err != nil {11 t.Fatal(err)12 }1314 posts.AssertSent(func(post slack.Post) bool {15 return post.Response == slack.Replied && post.Message.Text == "Only admins can refund invoices."16 })17}