Skip to content

Latest commit

 

History

History
55 lines (42 loc) · 2.98 KB

File metadata and controls

55 lines (42 loc) · 2.98 KB
title Using Socket Mode
lang en
slug socket-mode
order 16
With the introduction of [Socket Mode](https://api.slack.com/apis/connections/socket), Bolt for Python introduced support in version `1.2.0`. With Socket Mode, instead of creating a server with endpoints that Slack sends payloads too, the app will instead connect to Slack via a WebSocket connection and receive data from Slack over the socket connection. Make sure to enable Socket Mode in your app configuration settings.

To use the Socket Mode, add SLACK_APP_TOKEN as an environment variable. You can get your App Token in your app configuration settings under the Basic Information section.

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"])

if __name__ == "__main__":
    # export SLACK_APP_TOKEN=xapp-***
    # export SLACK_BOT_TOKEN=xoxb-***
    SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()

While we recommend using the built-in Socket Mode adapter, there are a few other 3rd party library based implementations. Here is the list of available adapters.

PyPI Project Bolt Adapter
slack_sdk slack_bolt.adapter.socket_mode
websocket_client slack_bolt.adapter.socket_mode.websocket_client
aiohttp (asyncio-based) slack_bolt.adapter.socket_mode.aiohttp
websockets (asyncio-based) slack_bolt.adapter.socket_mode.websockets

To use the asyncio-based adapters such as aiohttp, your app needs to be compatible with asyncio's async/await programming model. AsyncSocketModeHandler is available for running AsyncApp and its async middleware and listeners.

from slack_bolt.app.async_app import AsyncApp
# The default is the aiohttp based implementation
from slack_bolt.adapter.socket_mode.async_handler import AsyncSocketModeHandler

app = AsyncApp(token=os.environ["SLACK_BOT_TOKEN"])

async def main():
    handler = AsyncSocketModeHandler(app, os.environ["SLACK_APP_TOKEN"])
    await handler.start_async()

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

To learn how to use AsyncApp, checkout the Using Async document and relevant examples.