Building an app with Bolt for Python

Bolt for Python

Bolt is a foundational framework that makes it easier to build Slack apps with the platform's latest features. This guide walks you through building your first app with Bolt for Python.

If you prefer developing in another language, read our Bolt overview.

Along the way, you'll create a Slack app, set up a development environment, and build an app that listens and responds to events from your Slack workspace.


Getting started

The first section of this guide covers creating a basic Slack app tailored to work with Bolt. While we glance over some configuration here, our more general app setup guide goes into greater detail.

Creating a Slack app

To get started, you'll need to create a Slack app:

Create a Slack app

Click From scratch, enter your App Name, and select the workspace where you'll play around and build your app. Don't fuss too much over either field—no matter what workspace you select, you'll still be able to distribute your app to other workspaces if you choose. Click Create app.

Requesting scopes

Scopes give your app permission to perform actions, such as posting messages in your workspace. You can select the scopes to add to your app by navigating to the OAuth & Permissions sidebar or selecting your app below:

Try it out by creating an app
View configuration

Scroll down to the Bot Token Scopes section and click Add an OAuth Scope.

For now, we'll only use one scope. Add the chat:write scope to grant your app the permission to post messages in channels it's a member of.

Installing your app

Install your own app by selecting Install to Workspace at the top of the OAuth & Permissions page, or from the sidebar. Click Allow.

OAuth UI in app installation process

After installation, you'll land back in the OAuth & Permissions page and find a Bot User OAuth Token.

Access tokens represent the permissions delegated to your app by the installing user. Keep it secret. Keep it safe. At a minimum, avoid checking them into public version control. Instead, access them via an environment variable.

Enabling your app's Home tab

This guide uses Home tabs, a feature which offers a persistent space for your app to display dynamic interfaces for users.

To enable your app's Home tab, click the App Home sidebar on the App Management page, or select your app from the dropdown below:

Try it out by creating an app
View configuration

Toggle Home Tab to ON.

Setting up your Bolt app

With the app configured and installed, it’s time to set up a new Bolt for Python project with your app's credentials.

Configuring your local environment

If you don’t have Python 3.6 or later installed, now is the time to do it from the Python downloads page.

Create a virtual environment

It's recommended to use a Python virtual environment to manage your project's dependencies.

Create your virtual environment:

python3 -m venv .venv

Then, activate it.

macOS:

source .venv/bin/activate

Windows:

scripts\activate

Adding your app credentials

Before creating and starting the app, you'll need to copy over the credentials for your app. Copy the Bot User OAuth Token under the OAuth & Permissions sidebar.

You'll just be using a local project in this guide, so you'll save your bot token as an environment variable. In the command line, you'll save your token as SLACK_BOT_TOKEN.

macOS:

export SLACK_BOT_TOKEN=xoxb-your-token

Windows:

$env:SLACK_BOT_TOKEN="xoxb-your-token"

In addition to the access token, you'll need a signing secret. Your app's signing secret verifies that incoming requests are coming from Slack. Navigate to the Basic Information page from your app management page. Under App Credentials, copy the value for Signing Secret.

Like before, save your signing secret, this time as SLACK_SIGNING_SECRET.

macOS:

export SLACK_SIGNING_SECRET=your-signing-secret

Windows:

$env:SLACK_SIGNING_SECRET="your-signing-secret"

Using ngrok as a local proxy

To develop locally we'll be using ngrok, which allows you to expose a public endpoint that Slack can use to send your app events. If you haven't already, install ngrok from their website. You'll also need to sign up for a free ngrok account and install your authtoken first before you can serve any HTML content.

Once you're ready, go ahead and tell ngrok to use port 3000:

ngrok http 3000

Developing your app

With your local environment configured, let's begin coding the app.

Installing the Bolt Python package

Your can install the slack_bolt Python package to your virtual environment using the following command:

pip install slack_bolt

Initializing your app

After you've installed the slack_bolt package and added your credentials, create a new app.py file and paste the following code into it:

import os
# Use the package we installed
from slack_bolt import App

# Initialize your app with your bot token and signing secret
app = App(
    token=os.environ.get("SLACK_BOT_TOKEN"),
    signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)

# Add functionality here later
# @app.event("app_home_opened") etc.

# Ready? Start your app!
if __name__ == "__main__":
    app.start(port=int(os.environ.get("PORT", 3000)))

The above code initializes the app using the App constructor, then starts an HTTP server on port 3000. The HTTP server is using a built-in development adapter, which is responsible for handling and parsing incoming events from Slack. You can run your app now, but it won't do much.

python3 app.py

The HTTP server adapter is not recommended for production. Bolt for Python includes a collection of built-in adapters that can be imported and used with your app. You can explore adapters and sample usage in the repository's examples folder.

Subscribing to events

Your app can listen to all sorts of events happening around your workspace—messages being posted, reactjis being emoted, users joining the team, and more. To listen for events, your app uses the Events API.

Let's subscribe to the app_home_opened event. Select Event Subscriptions from the sidebar and toggle Enable Events to ON.

You'll be presented with an input box to enter a Request URL, which is where Slack sends the events your app is subscribed to. For local development, we'll use your ngrok URL from above with /slack/events appended to the end, as this is where Bolt for Python listens for all incoming requests by default. For example: https://abcd-12-34-56-789.ngrok.io/slack/events

After you've saved your Request URL and the URL is verified, navigate to Subscribe to bot events > Add Bot User Event and search for app_home_opened. Click Save Changes. This allows your app to receive app_home_opened events when users navigate to your app's Home tab from the Slack sidebar or search bar.

Responding to events

To respond to events, you can write a listener. Listeners have access to the event body, the entire request payload, and an additional context object that holds helpful information such as the bot token you used to instantiate your app.

Let's set up a basic listener using the app_home_opened event that publishes a view to your Home tab.

Paste this listener code, which is using a Python decorator, into your existing Bolt app. Make sure that your listeners code comes before the logic that encapsulates app.start(), or you may run into unhandled request errors. Your updated app.py file should look as follows:

import os
# Use the package we installed
from slack_bolt import App

# Initialize your app with your bot token and signing secret
app = App(
    token=os.environ.get("SLACK_BOT_TOKEN"),
    signing_secret=os.environ.get("SLACK_SIGNING_SECRET")
)

# New functionality
@app.event("app_home_opened")
def update_home_tab(client, event, logger):
  try:
    # views.publish is the method that your app uses to push a view to the Home tab
    client.views_publish(
      # the user that opened your app's app home
      user_id=event["user"],
      # the view object that appears in the app home
      view={
        "type": "home",
        "callback_id": "home_view",

        # body of the view
        "blocks": [
          {
            "type": "section",
            "text": {
              "type": "mrkdwn",
              "text": "*Welcome to your _App's Home tab_* :tada:"
            }
          },
          {
            "type": "divider"
          },
          {
            "type": "section",
            "text": {
              "type": "mrkdwn",
              "text": "This button won't do much for now but you can set up a listener for it using the `actions()` method and passing its unique `action_id`. See an example in the `examples` folder within your Bolt app."
            }
          },
          {
            "type": "actions",
            "elements": [
              {
                "type": "button",
                "text": {
                  "type": "plain_text",
                  "text": "Click me!"
                }
              }
            ]
          }
        ]
      }
    )

  except Exception as e:
    logger.error(f"Error publishing home tab: {e}")

# Ready? Start your app!
if __name__ == "__main__":
    app.start(port=int(os.environ.get("PORT", 3000)))

View this example in Block Kit Builder

Now, save your app.py file and restart your Bolt app:

python3 app.py

Try it out! Navigate to your app's Home tab by clicking your app from the sidebar in your workspace. When you open the Home tab, you should see your view appear. Congrats on building your first Bolt for Python app! 🙌

Next steps

With the basics under your belt, you can start exploring the rest of Bolt and the Slack platform. Here's a few paths you may consider wandering down:

  • Check out the examples folder within the Bolt for Python repository. There is a collection of examples for different adapters and platform features.
  • Improve your app's design with Block Kit Builder. This is a prototyping tool that allows you to design Slack apps quickly, then paste the code into your Bolt app (we also have public Figma files if you'd rather use them to design your app).
  • Read the Bolt for Python documentation to learn about advanced functionality and to find example code snippets that show you what else is possible.
  • Explore other surfaces where your app can exist, such as messages and pop-up modals.
  • When you're ready to take your app from development to deployed, you'll want to host it on the platform of your choice.

Need help or have questions?

Email our developer support team