Python Slack SDK

repository·main·Indexed 25 days ago

https://github.com/slackapi/python-slack-sdk

The Slack API Platform SDK for Python, successor to the slackclient library. It provides tools to interact with Slack Web, Socket Mode, Webhooks, Block Kit, Audit Logs, SCIM, and RTM APIs. Features include synchronous WebClient and asynchronous AsyncWebClient (via aiohttp), Block Kit UI component builders, and specialized modules for OAuth and request signature verification. Requires Python 3.7 or higher.

Tokens
34.9K
Snippets
77
Records
167
Agent score
80%

What's inside slack_sdk

  1. Overview of Python Slack SDK modules

    main

    The SDK provides specialized packages for different Slack API capabilities. You can use these modules independently or together:

    • slack_sdk.web: For calling Web API methods.
    • slack_sdk.webhook: For utilizing Incoming Webhooks and response_urls in payloads.
    • slack_sdk.signature: For verifying incoming requests from the Slack API server.
    • slack_sdk.socket_mode: For receiving and sending messages over Socket Mode connections.
    • slack_sdk.audit_logs: For utilizing Audit Logs APIs.
    • slack_sdk.scim: For utilizing SCIM APIs.
    • slack_sdk.oauth: For implementing the Slack OAuth flow.
    • slack_sdk.models: For constructing Block Kit UI components using builders.
    • slack_sdk.rtm: For utilizing the RTM API.
  2. Overview of Python Slack SDK features and packages

    main

    The Python Slack SDK provides specialized packages for interacting with various Slack APIs. Depending on your use case, you can use different modules to send/query data, handle authentication, or manage connections.

    Available API Packages

    FeatureUse CasePackage(s)
    Web APISend or query data using 200+ methodsslack_sdk.web, slack_sdk.web.async_client
    WebhooksSend messages via Incoming Webhooks or response_urlslack_sdk.webhook, slack_sdk.webhook.async_client
    Socket ModeReceive and send messages over Socket Mode connectionsslack_sdk.socket_mode
    OAuthSetup V2 OAuth or OpenID Connect authentication flowsslack_sdk.oauth
    Audit Logs APIReceive audit logs API dataslack_sdk.audit_logs
    SCIM APIProvision and manage user accounts and groupsslack_sdk.scim
    RTM APIListen for events via WebSocket (RTM v2)slack_sdk.rtm_v2
    Request Signature VerificationVerify incoming requests from Slack API serversslack_sdk.signature
    UI BuildersConstruct UI componentsslack_sdk.models
  3. Configure RetryHandlers for AuditLogsClient

    main

    By default, AuditLogsClient uses a ConnectionErrorRetryHandler that performs a single retry using exponential backoff and jitter for connectivity-related failures.

    To handle rate limiting (HTTP 429), you can append a RateLimitErrorRetryHandler to the client's retry_handlers list. You can also provide a custom list of handlers during client initialization.

    To implement a custom handler, inherit from slack_sdk.http_retry.RetryHandler (or AsyncRetryHandler for asyncio) and implement the required logic.

    import os
    from slack_sdk.audit_logs import AuditLogsClient
    from slack_sdk.http_retry.builtin_handlers import RateLimitErrorRetryHandler
    
    client = AuditLogsClient(token=os.environ["SLACK_ORG_ADMIN_USER_TOKEN"])
    
    # Enable rate limited error retries
    rate_limit_handler = RateLimitErrorRetryHandler(max_retry_count=1)
    client.retry_handlers.append(rate_limit_handler)
  4. Set App Credentials for your Slack app

    main

    Before running your application, you must configure your Slack bot token and signing secret as environment variables.

    1. SLACK_BOT_TOKEN: Use the bot user OAuth token (starting with xoxb-) obtained from your Slack App settings.
    2. SLACK_SIGNING_SECRET: Copy the Signing Secret from the Basic Information page under App Credentials in your Slack app configuration.

    To run your app locally, you may need a tool like ngrok to tunnel requests from a public URL to your local machine. If using ngrok, append /slack/events to your ngrok URL (e.g., https://abcdef.ngrok.io/slack/events) and use this in your Slack app configuration.

    $ export SLACK_BOT_TOKEN='xoxb-XXXXXXXXXXXX-xxxxxxxxxxxx-XXXXXXXXXXXXXXXXXXXXXXXX'
    $ export SLACK_SIGNING_SECRET='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    $ python3 app.py
  5. Configure app permissions (Scopes)

    main

    Scopes define what actions your app is allowed to perform. To configure them:

    1. Navigate to OAuth & Permissions in the Slack App settings sidebar.
    2. Scroll to the Bot Token Scopes section.
    3. Click Add an OAuth Scope to add required permissions.

    For basic messaging functionality, add the following scopes:

    • chat:write: Allows the app to post messages in channels it has joined.
    • im:write: Allows the app to post messages in Direct Messages (DMs).
  6. Share an uploaded file in a channel

    main

    When you upload a file using files_upload_v2 without specifying a channel, the file is uploaded but only visible to the bot. To share it with others, retrieve the file's permalink from the response and post it to a channel using chat_postMessage.

    # Retrieve the permalink from the upload response
    file_url = new_file.get("file").get("permalink")
    
    # Post the link to a specific channel
    new_message = client.chat_postMessage(
        channel="C123456789",
        text=f"Here is the file: {file_url}",
    )
  7. Migrate RTM API usage from v1.x to v2.x

    main

    The RTM (Real Time Messaging) API usage was completely redesigned in v2.x.

    Key Changes:

    • Event Handling: Instead of a manual loop reading from the client, use the @slack.RTMClient.run_on(event='...') decorator to link callbacks to events.
    • Data Access: The client no longer stores team data (like client.server.login_data) internally. This information is now passed within the open event payload.
    • Web Client Access: To make API calls from within an RTM callback, access the web_client via the event payload.

    Note: For new projects, Slack recommends using the Events API instead of RTM.

    import slack
    
    slack_token = os.environ["SLACK_API_TOKEN"]
    rtmclient = slack.RTMClient(token=slack_token)
    
    # Example: Handling a message event
    @slack.RTMClient.run_on(event='message')
    def say_hello(**payload):
        data = payload['data']
        if 'Hello' in data['text']:
            channel_id = data['channel']
            thread_ts = data['ts']
            user = data['user']
    
            # Access web_client from payload
            webclient = payload['web_client']
            webclient.chat_postMessage(
                channel=channel_id,
                text="Hi <@{}>!".format(user),
                thread_ts=thread_ts
            )
    
    # Example: Retrieving team data from the 'open' event
    @slack.RTMClient.run_on(event='open')
    def get_team_data(**payload):
        team_domain = payload['data']['team']['domain']
    
    rtmclient.start()
  8. Handle Slack OAuth callback requests

    main

    After a user authorizes your app, Slack redirects them to your Redirect URL with a code and state parameter. To complete the installation:

    1. Retrieve code and state from the request parameters.
    2. Verify the state using state_store.consume(state) to ensure it hasn't expired or been used.
    3. Exchange the code for an access token by calling WebClient.oauth_v2_access().
    4. (Optional) Call WebClient.auth_test(token=bot_token) to retrieve the bot_id and enterprise_url if it is an enterprise installation.
    5. Create an Installation object and save it using your InstallationStore.
  9. Use the RTM API client (v2)

    main

    The RTMClient in slack_sdk.rtm_v2 allows you to communicate with the Legacy Real Time Messaging (RTM) API via WebSockets. This enables receiving real-time events and sending messages.

    Note: Slack recommends using the HTTP-based Events API instead of the Legacy RTM API for new applications.

    To use the RTM API, your Slack app must use a plain bot scope (classic permission model).

    import os
    from slack_sdk.rtm_v2 import RTMClient
    
    rtm = RTMClient(token=os.environ["SLACK_BOT_TOKEN"])
    
    @rtm.on("message")
    def handle(client: RTMClient, event: dict):
        if 'Hello' in event['text']:
            channel_id = event['channel']
            thread_ts = event['ts']
            user = event['user'] # User ID (e.g., U*** or W***)
    
            client.web_client.chat_postMessage(
                channel=channel_id,
                text=f"Hi <@{user}>!",
                thread_ts=thread_ts
            )
    
    rtm.start()
  10. Update or push modals

    main

    There are two ways to modify the user's view:

    1. Response Action: When handling a view_submission request, return a JSON response to Slack with "response_action": "update" and a new view object to replace the current modal. Other actions include errors and push.
    2. API Method: Use views_update to modify an existing modal by providing the view_id, the hash from the payload, and the new view object. To add a new view on top of the current one, use views_push.
    # Using views_update to modify an existing modal
    response = client.views_update(
        view_id=payload["view"]["id"],
        hash=payload["view"]["hash"],
        view={
            "type": "modal",
            "callback_id": "modal-id",
            "title": {
                "type": "plain_text",
                "text": "Awesome Modal"
            },
            "blocks": [
                {
                    "type": "section",
                    "text": {
                        "type": "plain_text",
                        "text": "Updated content",
                    },
                }
            ],
        }
    )