• This repository has been archived on 10/Oct/2020
  • Stars
    star
    97
  • Rank 348,505 (Top 7 %)
  • Language
    Python
  • Created over 7 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A tutorial for adding Slack message menus to your Python app

Maximizing your Slack app's usefulness

When we think about how bots and humans interact within Slack, we often think of two types of interaction: Notification and Conversation.

The simplest form of Slack integration is to have your app post important information from another service into a slack channel. This works well for a variety of situations, such as package arrival notifications or an alert that one of your servers has caught on fire. Notifications are simple, timely, and informative. When your app is a part of a much more complex workflow, notifications are just a jumping point into another application or process.

As your processes and workflows become more complex, involving several applications across multiple windows, things can get ...complicated.

Message Buttons

Back in June, we released Message Buttons. Using these new interactive elements, developers were able to bring common workflow actions right into the bot's message. Users could not only see the notification message, but take action from inside Slack. This also eased a lot of the complexity with conversational bots. Rather than requiring a user to type a specific confirmation message, you were able to show the user a set of buttons to complete or cancel an action.

Message Buttons demo GIF

While Message Buttons are a great way to increase the usability of your Slack application, there are some limitations. One limitation is the amount of real estate buttons take up. When you have a large set of options, you'll end up with a message that takes up the user's entire chat window or gets truncated.

See our Message Buttons with Node.js tutorial for more information on how to add message buttons to your app.

Message Menus

Today we've released message menus ๐ŸŽ‰

Message menus are the newest interactive feature for Slack apps: clickable dropdown menus that you can add to message attachments. They can have static options, or they can load dynamically. You can build with five types of message menu today, each achieving a different flavor of use case: static menus, user menus, channel menus, conversation menus, and dynamic menus.

Slack message menu example

Read more about how apps are using message menus on our blog.

Adding message menus to your app

In this tutorial, we'll focus on adding dynamic option menus to your app. Here's a summary of how dynamic interactive message menus work:

  1. Post a message containing one or more attachments containing one or more interactive elements
  2. Slack sends a request to your registered Options Load URL containing the context you need to generate relevant menu options. You simply respond to this request with a JSON array of options.
  3. Users click a button or select an option from a menu
  4. A request is sent to your registered Action URL containing all the context you need to understand: who clicked it, which option they clicked, which message callback_id was associated with the message, and the original message inciting the selection
  5. You respond to your Action URL's invocation with a message to replace the original, and/or a new ephemeral message, and/or you utilize the invocation's response_url to update the original message out of band for a limited time.

Let's build it!

๐Ÿ’ก This code is also available as a complete example application on GitHub.

While we're building this example in Python, we haven't forgotten about the Node fans. We've put together a really neat example for Node.js over here ๐ŸŽ‰

For this example, we're going to need Python, the Python Slack client (slackclient) and a webserver (Flask).

First you'll create the basic elements of the app: A Slack client and webserver

from flask import Flask, request, make_response, Response
from slackclient import SlackClient
import json

# Your app's Slack bot user token
SLACK_BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"]

# Slack client for Web API requests
slack_client = SlackClient(SLACK_BOT_TOKEN)

# Flask webserver for incoming traffic from Slack
app = Flask(__name__)

Then we'll add the two endpoints Slack will POST requests to. The first endpoint is where Slack will send a request for items to populate the menu options, we'll call this one message_options.

@app.route("/slack/message_options", methods=["POST"])
def message_options():
    # Parse the request payload
    form_json = json.loads(request.form["payload"])

    menu_options = {
        "options": [
            {
                "text": "Chess",
                "value": "chess"
            },
            {
                "text": "Global Thermonuclear War",
                "value": "war"
            }
        ]
    }

    return Response(json.dumps(menu_options), mimetype='application/json')

The second endpoint you'll need is where Slack will send data when a user makes a selection. We'll call this one message_actions.

@app.route("/slack/message_actions", methods=["POST"])
def message_actions():

    # Parse the request payload
    form_json = json.loads(request.form["payload"])

    # Check to see what the user's selection was and update the message
    selection = form_json["actions"][0]["selected_options"][0]["value"]

    if selection == "war":
        message_text = "The only winning move is not to play.\nHow about a nice game of chess?"
    else:
        message_text = ":horse:"

    response = slack_client.api_call(
      "chat.update",
      channel=form_json["channel"]["id"],
      ts=form_json["message_ts"],
      text=message_text,
      attachments=[]
    )

    return make_response("", 200)

Now that our endpoints are configured, we can build the message containing the menu and send it to a channel.

In order to show the menu, we'll have to build the message attachment which will contain it.

message_attachments = [
    {
        "fallback": "Upgrade your Slack client to use messages like these.",
        "color": "#3AA3E3",
        "attachment_type": "default",
        "callback_id": "menu_options_2319",
        "actions": [
            {
                "name": "games_list",
                "text": "Pick a game...",
                "type": "select",
                "data_source": "external"
            }
        ]
    }
]

Once the attachment JSON is ready, simply post a message to the channel, adding the attachment containing the menu.

slack_client.api_call(
  "chat.postMessage",
  channel="C09EM2073",
  text="Shall we play a game?",
  attachments=message_attachments
)

Take note of the "data_source": "external" attribute in the attachment JSON. This is how Slack knows to pull the menu options from the message_options endpoint we set up above.

slack_client.api_call(
  "chat.postMessage",
  channel="C09EM2073",
  text="Shall we play a game?",
  attachments=attachments_json
)

Support

Need help? Join Bot Developer Hangout and talk to us in #slack-api.

You can also create an Issue right here on GitHub.

More Repositories

1

python-slack-sdk

Slack Developer Kit for Python
Python
3,840
star
2

node-slack-sdk

Slack Developer Kit for Node.js
TypeScript
3,270
star
3

bolt-js

A framework to build Slack apps using JavaScript
TypeScript
2,736
star
4

hubot-slack

Slack Developer Kit for Hubot
CoffeeScript
2,300
star
5

bolt-python

A framework to build Slack apps using Python
Python
1,053
star
6

slack-github-action

Send data into Slack using this GitHub Action!
JavaScript
953
star
7

python-rtmbot

A framework for receiving and interacting with events from Slack's RTM API
Python
680
star
8

java-slack-sdk

Slack Developer Kit (including Bolt for Java) for any JVM language
Java
573
star
9

python-slack-events-api

Slack Events API adapter for Python (Flask required)
Python
342
star
10

Slack-Python-Onboarding-Tutorial

a simple python onboarding bot and tutorial for Slack
Python
251
star
11

slack-api-specs

Open API specifications for platform products by Slack
220
star
12

steno

๐Ÿ“ผ Slack app testing companion - Record and Replay your HTTP requests, both incoming and outgoing
TypeScript
184
star
13

deno-slack-sdk

SDK for building Run on Slack apps using Deno
TypeScript
160
star
14

template-slash-command-and-dialogs

Sample Slack app that uses a Slash Command and interactive message to create helpdesk tickets
JavaScript
141
star
15

node-slack-interactive-messages

Slack Buttons, Menus, and Dialogs made simpler for Node
JavaScript
133
star
16

build-this-bot-workshop

Learn how to build a bot on Slack using Python
127
star
17

reacjilator

A translation bot that translates a message when a user reacted with an emoji ๐Ÿ‡จ๐Ÿ‡ณ ๐Ÿ‡ฎ๐Ÿ‡น ๐Ÿ‡น๐Ÿ‡ญ ๐Ÿ‡ซ๐Ÿ‡ท ๐Ÿ‡ฏ๐Ÿ‡ต ๐Ÿ‡ฎ๐Ÿ‡ณ ๐Ÿ‡บ๐Ÿ‡ธ ๐Ÿ‡ง๐Ÿ‡ฌ ๐Ÿ‡น๐Ÿ‡ผ ๐Ÿ‡ฆ๐Ÿ‡ช ๐Ÿ‡ฐ๐Ÿ‡ท
JavaScript
110
star
18

onboarding-example

A demonstration of how to build an onboarding app using Slack's Events API
JavaScript
99
star
19

node-tasks-app

Tasks App is a sample Task Management app built on the Slack Platform.
JavaScript
98
star
20

slack-platform-assets

Images, templates, and Sketch files to aid designing and presenting your Slack apps
94
star
21

node-slack-events-api

Slack Events API for Node
JavaScript
93
star
22

sample-message-menus-node

An example Slack app that demonstrates use of message menus
JavaScript
91
star
23

python-dialog-example

An example app to demonstrate Slack dialogs
Python
77
star
24

template-announcement-approvals

Sample Slack app that uses the Events API and interactive message to implement an approvals workflow
JavaScript
74
star
25

Slack-Ruby-Onboarding-Tutorial

An example Slack bot written in Ruby
Ruby
64
star
26

bolt-js-getting-started-app

Getting Started Slack app using โšก๏ธ Bolt for JavaScript
JavaScript
54
star
27

sample-app-unfurls

An example Slack app that demonstrates use of App Unfurls
JavaScript
45
star
28

app-interaction-patterns

A collection of common workflows and interaction patterns for Slack apps.
41
star
29

oauth-tutorial

Slack OAuth setup tutorial using a simple slash command bot
JavaScript
39
star
30

template-triage-bot

Triage Channel Stats w/ Bolt for JS & Shortcuts โšก๏ธ
JavaScript
39
star
31

template-actionable-notifications

Sample Slack app to illustrate how incoming webhooks and interactive messages can be used to build a helpdesk integration
JavaScript
35
star
32

deno-slack-api

Slack API Client for Deno Run on Slack projects
TypeScript
35
star
33

template-terms-of-service

Sample Slack app that uses the Events API and interactive messages to send new users a Terms of Service or welcome message
JavaScript
35
star
34

app-directory-assets

A collection of design assets to help build an app directory submission
34
star
35

template-incident-management

A sample of managing incidents via Slack
TypeScript
34
star
36

template-channel-webhooks

Sample Slack app that uses a Bot to create per-channel webhooks
JavaScript
31
star
37

TalkBot

Building a Twilio-powered Slack bot with Node.js
JavaScript
30
star
38

python-slack-discovery-sdk

This project aims to make using Slack's Discovery APIs easier.
Python
28
star
39

template-channel-naming

Sample Slack app that uses the Events API and interactive message to help enforce channel naming conventions
JavaScript
28
star
40

workflow-powerups

TypeScript
27
star
41

template-action-and-dialog

A sample Slack app "ClipIt", which allows user to clip a message using a message action
JavaScript
27
star
42

sample-message-menus-ruby

An example Slack app in Ruby that demonstrates use of message menus
Ruby
23
star
43

definition-app

A Slack app for storing and accessing company specific phrases
TypeScript
23
star
44

template-account-binding

A sample Slack app that shows you how to bind a Slack user to a user on another system
JavaScript
22
star
45

admin_app_management

Sample application to manage your applications within a Slack organization
TypeScript
20
star
46

pycon-2018

Sample app for Pycon 2018 Slack app workshop
Python
15
star
47

slack-reporting-tool

A Slack app to help administer workspaces by letting team members report offensive messages
TypeScript
15
star
48

deno-slack-runtime

Helper library for running a Run on Slack Deno function
TypeScript
13
star
49

pycon-2019

Pycon 2019 Workshop
Python
12
star
50

deno-slack-hooks

Helper library implementing the contract between the Slack CLI and Slack application SDKs
TypeScript
11
star
51

python-link-button-example

An example app using Slack link buttons and deep links
Python
10
star
52

deno-slack-hub

Connectors used to build coded workflows for Run on Slack apps using Deno
TypeScript
9
star
53

deno-slack-builder

Library for building a Run on Slack Deno project.
TypeScript
9
star
54

bolt-examples-aws-re-invent-2020

A collection of examples to get started with deploying modern โšก๏ธ Slack apps to AWS Lambda and Amazon Lightsail containers
Java
8
star
55

WeAreDevs

WeAreDevelopers Slack Workshop
Python
7
star
56

manifest-schema

Provide JSON schemas that define Slack's manifest.json file
Python
6
star
57

python-slack-hooks

Helper library implementing the contract between the Slack CLI and Bolt for Python
Python
5
star
58

template-message-linking

Sample Slack APP that uses the Events API to link to a conversation happening in one channel to another
JavaScript
5
star
59

bolt-python-getting-started-app

Getting Started Slack app using โšก๏ธ Bolt for Python
Python
4
star
60

easy-peasy-bot-custom-integration

DEPRECATED use https://github.com/slackapi/easy-peasy-bot instead
JavaScript
3
star
61

sample-incident-management

JavaScript
3
star
62

sample-code-index

An index of the most up-to-date sample code created by the Slack team
3
star
63

slack-health-score

A GitHub Action to report software project health score
JavaScript
3
star
64

deno-simple

TypeScript
2
star
65

deno-reverse-string

TypeScript
2
star
66

slack-app-time-off

Time-Off Request sample app for Slack's Next Generation Platform
TypeScript
1
star
67

deno-metadata-event

TypeScript
1
star
68

sunny-picnics

๐ŸŒค๐ŸŒณ๐ŸŒป๐Ÿงบ๐Ÿœ๐Ÿ‘’
1
star
69

deno-budget-calculator

TypeScript
1
star
70

deno-environment-variables

TypeScript
1
star
71

deno-testing-functions

TypeScript
1
star
72

template-ts-clip-message

TypeScript
1
star
73

slack-connect-sample

A sample app which shows off the functionality of the Slack Connect APIs.
JavaScript
1
star
74

deno-slack-protocols

Implements the rules for communication between Slack CLI and any Slack app development SDKs
TypeScript
1
star