Skip to content

version 3.2.0

Compare
Choose a tag to compare
@seratch seratch released this 12 Jan 22:07
· 441 commits to main since this release

New Features

Socket Mode

This version includes support for Socket Mode, which enables developers to receive interactivy payalods and events through WebSocket connections.

https://api.slack.com/socket-mode

For WebSocket connection handling, there are four implementations including major 3rd party open-source libraries.

PyPI Project SocketModeClient
skack_sdk slack_sdk.socket_mode.SocketModeClient
websocket_client slack_sdk.socket_mode.websocket_client.SocketModeClient
aiohttp (asyncio-based) slack_sdk.socket_mode.aiohttp.SocketModeClient
websockets (asyncio-based) slack_sdk.socket_mode.websockets.SocketModeClient

Here is a minimal working example with the built-in WebSocket client. You can switch to other implementation by changing the imports and adding the extra dependencies (websocket_client, aiohttp, websockets).

import os
from slack_sdk.web import WebClient
from slack_sdk.socket_mode import SocketModeClient

# Initialize SocketModeClient with an app-level token + WebClient
client = SocketModeClient(
    # This app-level token will be used only for establishing a connection
    app_token=os.environ.get("SLACK_APP_TOKEN"),  # xapp-A111-222-xyz
    # You will be using this WebClient for performing Web API calls in listeners
    web_client=WebClient(token=os.environ.get("SLACK_BOT_TOKEN"))  # xoxb-111-222-xyz
)

from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.socket_mode.request import SocketModeRequest

def process(client: SocketModeClient, req: SocketModeRequest):
    if req.type == "events_api":
        # Acknowledge the request anyway
        response = SocketModeResponse(envelope_id=req.envelope_id)
        client.send_socket_mode_response(response)
        # Add a reaction to the message if it's a new message
        if req.payload["event"]["type"] == "message" \
            and req.payload["event"].get("subtype") is None:
            client.web_client.reactions_add(
                name="eyes",
                channel=req.payload["event"]["channel"],
                timestamp=req.payload["event"]["ts"],
            )

# Add a new listener to receive messages from Slack
# You can add more listeners like this
client.socket_mode_request_listeners.append(process)

# Establish a WebSocket connection to the Socket Mode servers
client.connect()

# Just not to stop this process
from threading import Event
Event().wait()

Changes