Convert Figma logo to code with AI

slackapi logobolt-python

A framework to build Slack apps using Python

1,057
245
1,057
25

Top Related Projects

67,844

The Python micro framework for building web applications.

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

79,643

The Web framework for perfectionists with deadlines.

10,027

The little ASGI framework that shines. 🌟

15,061

Asynchronous HTTP client/server framework for asyncio and Python

52,086

A simple, yet elegant, HTTP library.

Quick Overview

Bolt for Python is a framework designed to simplify the process of building Slack apps using Python. It provides a clear and concise API for handling Slack events and interactions, making it easier for developers to create powerful and responsive Slack applications.

Pros

  • Simplified API for handling Slack events and interactions
  • Built-in support for common Slack app features like modals, shortcuts, and slash commands
  • Excellent documentation and examples for quick start and advanced usage
  • Actively maintained and supported by the Slack team

Cons

  • Limited to Python development, not suitable for other programming languages
  • May have a learning curve for developers new to Slack app development
  • Some advanced features might require additional setup or configuration
  • Performance may be a concern for very large-scale applications

Code Examples

  1. Listening for a message containing "hello":
@app.message("hello")
def message_hello(message, say):
    say(f"Hey there <@{message['user']}>!")
  1. Handling a slash command:
@app.command("/ticket")
def open_ticket(ack, say, command):
    ack()
    say(f"Creating a ticket for {command['text']}...")
  1. Opening a modal:
@app.shortcut("open_modal")
def open_modal(ack, shortcut, client):
    ack()
    client.views_open(
        trigger_id=shortcut["trigger_id"],
        view={
            "type": "modal",
            "title": {"type": "plain_text", "text": "My App"},
            "close": {"type": "plain_text", "text": "Close"},
            "blocks": [
                {
                    "type": "section",
                    "text": {"type": "mrkdwn", "text": "Welcome to the modal!"}
                }
            ]
        }
    )

Getting Started

  1. Install the Bolt for Python package:
pip install slack_bolt
  1. Create a new Python file (e.g., app.py) and add the following code:
from slack_bolt import App

# Initialize your app with your bot token and signing secret
app = App(
    token="YOUR_BOT_TOKEN",
    signing_secret="YOUR_SIGNING_SECRET"
)

@app.message("hello")
def message_hello(message, say):
    say(f"Hey there <@{message['user']}>!")

if __name__ == "__main__":
    app.start(port=3000)
  1. Replace YOUR_BOT_TOKEN and YOUR_SIGNING_SECRET with your actual Slack app credentials.

  2. Run your app:

python app.py

Competitor Comparisons

67,844

The Python micro framework for building web applications.

Pros of Flask

  • More general-purpose web framework, suitable for a wide range of applications
  • Larger community and ecosystem, with extensive third-party extensions
  • Lightweight and flexible, allowing developers to choose their preferred tools

Cons of Flask

  • Requires more setup and configuration for specific use cases like Slack apps
  • Less opinionated, which may lead to more decision-making and potential inconsistencies
  • Steeper learning curve for beginners compared to purpose-built frameworks

Code Comparison

Flask example:

from flask import Flask, request

app = Flask(__name__)

@app.route('/slack/events', methods=['POST'])
def slack_event():
    data = request.json
    # Handle Slack event
    return '', 200

Bolt example:

from slack_bolt import App

app = App(token="YOUR_BOT_TOKEN")

@app.event("message")
def handle_message(event, say):
    # Handle message event
    say("Hello!")

app.start(port=3000)

Flask provides a more general approach, requiring manual handling of Slack events, while Bolt offers a more streamlined, Slack-specific implementation with built-in event handling and response methods.

75,446

FastAPI framework, high performance, easy to learn, fast to code, ready for production

Pros of FastAPI

  • More general-purpose web framework, suitable for a wide range of API development tasks
  • Built-in support for asynchronous programming, offering better performance for I/O-bound operations
  • Automatic API documentation generation with Swagger UI and OpenAPI

Cons of FastAPI

  • Steeper learning curve for developers new to asynchronous programming
  • Less specialized for Slack app development, requiring more setup for Slack-specific features

Code Comparison

FastAPI example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

Bolt-Python example:

from slack_bolt import App

app = App()

@app.message("hello")
def message_hello(message, say):
    say(f"Hey there <@{message['user']}>!")

if __name__ == "__main__":
    app.start(port=int(os.environ.get("PORT", 3000)))

Summary

FastAPI is a versatile web framework for building APIs, while Bolt-Python is specifically designed for Slack app development. FastAPI offers more flexibility and performance optimizations, but requires more setup for Slack-specific features. Bolt-Python provides a simpler, more focused approach for Slack apps but may be less suitable for general API development.

79,643

The Web framework for perfectionists with deadlines.

Pros of Django

  • Comprehensive web framework with built-in features for authentication, admin interface, and ORM
  • Large, mature ecosystem with extensive documentation and community support
  • Follows the "batteries included" philosophy, providing a complete solution for web development

Cons of Django

  • Steeper learning curve due to its full-featured nature
  • Can be overkill for simple applications or microservices
  • Less flexible for non-traditional web applications or specific use cases

Code Comparison

Django (URL routing):

from django.urls import path
from . import views

urlpatterns = [
    path('hello/', views.hello_world, name='hello_world'),
]

Bolt Python (event handling):

from slack_bolt import App

app = App()

@app.event("app_mention")
def handle_app_mention(event, say):
    say(f"Hello, <@{event['user']}>!")

Both frameworks offer different approaches to handling web requests and events. Django provides a more traditional web framework structure, while Bolt Python is specifically designed for building Slack apps with a focus on simplicity and event-driven programming.

Django is better suited for full-featured web applications, while Bolt Python excels in creating Slack bots and integrations quickly and efficiently. The choice between the two depends on the specific requirements of your project and the target platform.

10,027

The little ASGI framework that shines. 🌟

Pros of Starlette

  • More general-purpose web framework, suitable for a wide range of applications
  • High performance and lightweight design
  • Extensive middleware and plugin ecosystem

Cons of Starlette

  • Steeper learning curve for beginners
  • Less specialized for Slack app development
  • Requires more setup and configuration for Slack-specific features

Code Comparison

Bolt-Python (Slack app setup):

from slack_bolt import App

app = App(token="YOUR_BOT_TOKEN")

@app.message("hello")
def message_hello(message, say):
    say(f"Hey there <@{message['user']}>!")

app.start(port=3000)

Starlette (Basic web app setup):

from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

async def homepage(request):
    return JSONResponse({"message": "Hello, World!"})

app = Starlette(debug=True, routes=[
    Route('/', homepage),
])

Bolt-Python is specifically designed for Slack app development, providing a more straightforward setup for Slack-related functionality. Starlette, on the other hand, offers a more flexible and general-purpose web framework that can be adapted for various applications, including Slack apps with additional configuration.

15,061

Asynchronous HTTP client/server framework for asyncio and Python

Pros of aiohttp

  • More general-purpose HTTP client/server framework for asyncio
  • Supports WebSockets and Server-Sent Events
  • Larger community and ecosystem of extensions

Cons of aiohttp

  • Steeper learning curve for beginners
  • Requires more boilerplate code for basic functionality
  • Less Slack-specific features and abstractions

Code Comparison

aiohttp example:

from aiohttp import web

async def handle(request):
    return web.Response(text="Hello, World!")

app = web.Application()
app.add_routes([web.get('/', handle)])
web.run_app(app)

Bolt-python example:

from slack_bolt import App

app = App()

@app.message("hello")
def message_hello(message, say):
    say(f"Hey there <@{message['user']}>!")

if __name__ == "__main__":
    app.start(port=3000)

Summary

aiohttp is a more versatile and powerful asyncio-based HTTP framework, while Bolt-python is specifically designed for building Slack apps. aiohttp offers greater flexibility and a wider range of use cases, but requires more setup and configuration. Bolt-python provides a simpler, more focused approach for Slack app development with built-in abstractions and event handling.

52,086

A simple, yet elegant, HTTP library.

Pros of Requests

  • More general-purpose HTTP library, suitable for a wide range of web-related tasks
  • Extensive documentation and large community support
  • Simpler API for basic HTTP operations

Cons of Requests

  • Not specifically designed for Slack bot development
  • Requires more manual handling of Slack-specific features and authentication
  • May need additional libraries for advanced Slack functionality

Code Comparison

Requests:

import requests

response = requests.get('https://api.slack.com/api/chat.postMessage', 
    params={'channel': 'C1234567890', 'text': 'Hello, World!'}, 
    headers={'Authorization': 'Bearer xoxb-your-token'})

Bolt:

from slack_bolt import App

app = App(token="xoxb-your-token")

@app.message("hello")
def message_hello(message, say):
    say(f"Hey there <@{message['user']}>!")

Summary

Requests is a versatile HTTP library for Python, offering simplicity and broad applicability. It's excellent for general web interactions but requires more setup for Slack-specific tasks. Bolt, on the other hand, is tailored for Slack bot development, providing a more streamlined experience with built-in Slack features. While Requests offers flexibility, Bolt simplifies Slack bot creation with its event-driven approach and pre-configured Slack integrations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Bolt Bolt logo for Python

PyPI - Version Codecov Pepy Total Downloads
Python Versions Documentation

A Python framework to build Slack apps in a flash with the latest platform features. Read the getting started guide and look at our code examples to learn how to build apps using Bolt. The Python module documents are available here.

Setup

# Python 3.6+ required
python -m venv .venv
source .venv/bin/activate

pip install -U pip
pip install slack_bolt

Creating an app

Create a Bolt for Python app by calling a constructor, which is a top-level export. If you'd prefer, you can create an async app.

import logging
logging.basicConfig(level=logging.DEBUG)

from slack_bolt import App

# export SLACK_SIGNING_SECRET=***
# export SLACK_BOT_TOKEN=xoxb-***
app = App()

# Add functionality here

if __name__ == "__main__":
    app.start(3000)  # POST http://localhost:3000/slack/events

Running an app

export SLACK_SIGNING_SECRET=***
export SLACK_BOT_TOKEN=xoxb-***
python app.py

# in another terminal
ngrok http 3000

Running a Socket Mode app

If you use Socket Mode for running your app, SocketModeHandler is available for it.

import os
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

# Install the Slack app and get xoxb- token in advance
app = App(token=os.environ["SLACK_BOT_TOKEN"])

# Add functionality here

if __name__ == "__main__":
    # Create an app-level token with connections:write scope
    handler = SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"])
    handler.start()

Run the app this way:

export SLACK_APP_TOKEN=xapp-***
export SLACK_BOT_TOKEN=xoxb-***
python app.py

# SLACK_SIGNING_SECRET is not required
# Running ngrok is not required

Listening for events

Apps typically react to a collection of incoming events, which can correspond to Events API events, actions, shortcuts, slash commands or options requests. For each type of request, there's a method to build a listener function.

# Listen for an action from a Block Kit element (buttons, select menus, date pickers, etc)
app.action(action_id)(fn)

# Listen for dialog submissions
app.action({"callback_id": callbackId})(fn)

# Listen for slash commands
app.command(command_name)(fn)

# Listen for an event from the Events API
app.event(event_type)(fn)

# Listen for a custom step execution from a workflow
app.function(callback_id)(fn)

# Convenience method to listen to only `message` events using a string or re.Pattern
app.message([pattern ,])(fn)

# Listen for options requests (from select menus with an external data source)
app.options(action_id)(fn)

# Listen for a global or message shortcuts
app.shortcut(callback_id)(fn)

# Listen for view_submission modal events
app.view(callback_id)(fn)

The recommended way to use these methods are decorators:

@app.event(event_type)
def handle_event(event):
    pass

Making things happen

Most of the app's functionality will be inside listener functions (the fn parameters above). These functions are called with a set of arguments, each of which can be used in any order. If you'd like to access arguments off of a single object, you can use args, an slack_bolt.kwargs_injection.Args instance that contains all available arguments for that event.

ArgumentDescription
bodyDictionary that contains the entire body of the request (superset of payload). Some accessory data is only available outside of the payload (such as trigger_id and authorizations).
payloadContents of the incoming event. The payload structure depends on the listener. For example, for an Events API event, payload will be the event type structure. For a block action, it will be the action from within the actions list. The payload dictionary is also accessible via the alias corresponding to the listener (message, event, action, shortcut, view, command, or options). For example, if you were building a message() listener, you could use the payload and message arguments interchangably. An easy way to understand what's in a payload is to log it.
contextEvent context. This dictionary contains data about the event and app, such as the botId. Middleware can add additional context before the event is passed to listeners.
ackFunction that must be called to acknowledge that your app received the incoming event. ack exists for all actions, shortcuts, view submissions, slash command and options requests. ack returns a promise that resolves when complete. Read more in Acknowledging events.
respondUtility function that responds to incoming events if it contains a response_url (shortcuts, actions, and slash commands).
sayUtility function to send a message to the channel associated with the incoming event. This argument is only available when the listener is triggered for events that contain a channel_id (the most common being message events). say accepts simple strings (for plain-text messages) and dictionaries (for messages containing blocks).
clientWeb API client that uses the token associated with the event. For single-workspace installations, the token is provided to the constructor. For multi-workspace installations, the token is returned by using the OAuth library, or manually using the authorize function.
loggerThe built-in logging.Logger instance you can use in middleware/listeners.
completeUtility function used to signal the successful completion of a custom step execution. This tells Slack to proceed with the next steps in the workflow. This argument is only available with the .function and .action listener when handling custom workflow step executions.
failUtility function used to signal that a custom step failed to complete. This tells Slack to stop the workflow execution. This argument is only available with the .function and .action listener when handling custom workflow step executions.

Creating an async app

If you'd prefer to build your app with asyncio, you can import the AIOHTTP library and call the AsyncApp constructor. Within async apps, you can use the async/await pattern.

# Python 3.6+ required
python -m venv .venv
source .venv/bin/activate

pip install -U pip
# aiohttp is required
pip install slack_bolt aiohttp

In async apps, all middleware/listeners must be async functions. When calling utility methods (like ack and say) within these functions, it's required to use the await keyword.

# Import the async app instead of the regular one
from slack_bolt.async_app import AsyncApp

app = AsyncApp()

@app.event("app_mention")
async def event_test(body, say, logger):
    logger.info(body)
    await say("What's up?")

@app.command("/hello-bolt-python")
async def command(ack, body, respond):
    await ack()
    await respond(f"Hi <@{body['user_id']}>!")

if __name__ == "__main__":
    app.start(3000)

If you want to use another async Web framework (e.g., Sanic, FastAPI, Starlette), take a look at the built-in adapters and their examples.

Getting Help

The documentation has more information on basic and advanced concepts for Bolt for Python. Also, all the Python module documents of this library are available here.

If you otherwise get stuck, we're here to help. The following are the best ways to get assistance working through your issue:

  • Issue Tracker for questions, bug reports, feature requests, and general discussion related to Bolt for Python. Try searching for an existing issue before creating a new one.
  • Email our developer support team: support@slack.com