Mobility Bot

Commute Alerts for Slack and Microsoft Teams

Using Slack Bolt in a Python Litestar App

Slack Bolt is a great way to get started writing a Slack Bot. It gives you the “batteries included” version of the slightly lower-level Slack SDKs, and allows quickly and easily standing up a bot codebase, defining a few callbacks, and running the bot.

If you’re using Bolt for Python, there are several built-in adapters for various web frameworks, such as Flask, FastAPI, and Django. However, there isn’t a copy-paste example for Litestar, the framework we’re using at Mobility Bot.

The good news is Litestar makes it very easy to plug and play other web handlers into an app. Because Slack Bolt can just be an ASGI handler, it can be mounted into any existing Litestar application.

from litestar import Litestar
from litestar.handlers import ASGIRouteHandler
from slack_bolt.adapter.asgi.async_handler import AsyncSlackRequestHandler
from slack_bolt.async_app import AsyncApp

def slack_handler(app: AsyncApp) -> ASGIRouteHandler:
    slack_api = AsyncSlackRequestHandler(app)
    slack_paths = [slack_api.path]
    if app.oauth_flow:
        slack_paths.append(app.oauth_flow.install_path)
        slack_paths.append(app.oauth_flow.redirect_uri_path)
    # The ASGIRouteHandler allows an ASGI-compatible handler to be added to a Litestar application
    return ASGIRouteHandler(name="slack_bolt", path=slack_paths)(slack_api)


# initialize with any necessary settings, such as secrets or oauth
slack_app = AsyncApp()

# add your handlers here, such as slack_app.event(...)

app = Litestar(
    route_handlers=[..., slack_handler(slack_app)],
    # any other Litestar configuration
)
Related Posts

🚌 Ensure your commute is smooth and hassle-free with Mobility Bot. Install it now in your Slack workspace!
🚇 Stay informed with real-time transit alerts tailored to your specific routes and schedule.