Slack SDK for Python (Official)

3.27.0 · active · verified Thu Apr 16

The Slack SDK for Python provides a comprehensive and easy-to-use toolkit for building Slack applications. It offers corresponding packages for various Slack APIs, including Web API, Webhooks, Socket Mode, and OAuth. This library (and `slack_bolt`) is the official and actively maintained successor to `slackclient`. It is designed to be small, powerful, and to work seamlessly across different Slack platform features. The current version is 3.x, with frequent updates to support new Slack features and improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates sending a basic message to a Slack channel using the `WebClient` from `slack_sdk`. It handles authentication via an environment variable and includes basic error handling for common API issues. A commented-out example for a simple 'hello' response using the `slack_bolt` framework is also provided. Remember to set `SLACK_BOT_TOKEN` (and `SLACK_APP_TOKEN` for Socket Mode) environment variables.

import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

# Your bot token (xoxb-...) or user token (xoxp-...)
# You can find these at https://api.slack.com/apps
slack_token = os.environ.get('SLACK_BOT_TOKEN', 'YOUR_SLACK_BOT_TOKEN')

client = WebClient(token=slack_token)

try:
    response = client.chat_postMessage(
        channel='#general', # Or a channel ID like 'C12345ABC'
        text='Hello from your Python Slack SDK app!'
    )
    print(f"Message posted: {response['ts']}")
except SlackApiError as e:
    # You will get a SlackApiError if 'ok' is False
    print(f"Error sending message: {e.response['error']}")
    # e.g., 'invalid_auth', 'channel_not_found', 'not_in_channel' etc.
    if e.response['error'] == 'invalid_auth':
        print("Please check your SLACK_BOT_TOKEN or SLACK_APP_TOKEN environment variable.")
    elif e.response['error'] == 'channel_not_found':
        print("The specified channel does not exist or your bot is not in it.")

# Example for Slack Bolt App (requires 'pip install slack_bolt')
# from slack_bolt import App
# from slack_bolt.adapter.socket_mode import SocketModeHandler

# app = App(token=os.environ.get('SLACK_BOT_TOKEN'))

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

# if __name__ == "__main__":
#     SocketModeHandler(app, os.environ.get("SLACK_APP_TOKEN")).start()

view raw JSON →