Top Related Projects
A framework to build Slack apps using Python
Slack Developer Kit for Python
Quick Overview
The python-slack-sdk is the official Python SDK for Slack's Web API, RTM API, and various other Slack tools. It provides a comprehensive set of tools for building Slack apps and integrations, making it easier for developers to interact with Slack's platform using Python.
Pros
- Comprehensive coverage of Slack's APIs and features
- Well-documented and actively maintained by Slack
- Supports both synchronous and asynchronous programming models
- Includes helpful utilities like rate limiting and retry logic
Cons
- Learning curve can be steep for beginners
- Some advanced features may require additional setup or dependencies
- Documentation can be overwhelming due to the breadth of features covered
- Occasional breaking changes between major versions
Code Examples
- Sending a message to a channel:
from slack_sdk import WebClient
client = WebClient(token="YOUR_BOT_TOKEN")
response = client.chat_postMessage(channel="#general", text="Hello, Slack!")
- Listening for events using the Socket Mode client:
from slack_sdk.socket_mode import SocketModeClient
from slack_sdk.socket_mode.response import SocketModeResponse
def process_event(client, req):
if req.type == "events_api":
print(f"Received event: {req.payload}")
client.send_socket_mode_response(SocketModeResponse(envelope_id=req.envelope_id))
client = SocketModeClient(app_token="YOUR_APP_TOKEN")
client.socket_mode_request_listeners.append(process_event)
client.connect()
- Using the Web API asynchronously:
import asyncio
from slack_sdk.web.async_client import AsyncWebClient
async def send_message():
client = AsyncWebClient(token="YOUR_BOT_TOKEN")
response = await client.chat_postMessage(channel="#general", text="Hello, async Slack!")
print(f"Message sent: {response['ts']}")
asyncio.run(send_message())
Getting Started
-
Install the SDK:
pip install slack-sdk
-
Import and initialize the client:
from slack_sdk import WebClient client = WebClient(token="YOUR_BOT_TOKEN")
-
Use the client to interact with Slack:
response = client.chat_postMessage(channel="#general", text="Hello, Slack!") print(f"Message sent: {response['ts']}")
Competitor Comparisons
A framework to build Slack apps using Python
Pros of bolt-python
- Simplified API for building Slack apps with less boilerplate code
- Built-in support for common Slack app features like slash commands and interactive messages
- Easier handling of events and middleware
Cons of bolt-python
- Less flexibility for advanced use cases compared to python-slack-sdk
- Steeper learning curve for developers already familiar with python-slack-sdk
- Limited control over low-level API interactions
Code Comparison
python-slack-sdk:
from slack import WebClient
client = WebClient(token="YOUR_TOKEN")
response = client.chat_postMessage(channel="#general", text="Hello, Slack!")
bolt-python:
from slack_bolt import App
app = App(token="YOUR_TOKEN")
@app.message("hello")
def message_hello(message, say):
say(f"Hey there <@{message['user']}>!")
app.start(port=3000)
The python-slack-sdk example shows direct API interaction, while bolt-python demonstrates its event-driven approach with decorators and simplified message handling. bolt-python abstracts away many low-level details, making it easier to build Slack apps quickly, but potentially limiting fine-grained control over API interactions.
Slack Developer Kit for Python
Pros of python-slack-sdk
- Comprehensive and official SDK for Slack API
- Supports both synchronous and asynchronous operations
- Regularly updated with new Slack API features
Cons of python-slack-sdk
- Larger codebase, potentially more complex for simple use cases
- May have a steeper learning curve for beginners
Code Comparison
Both repositories are the same, so there's no code comparison to make. The python-slack-sdk repository is the official Slack SDK for Python, and there isn't a separate repository to compare it against.
Summary
The python-slack-sdk is the official Python SDK for interacting with the Slack API. It provides a comprehensive set of tools and features for building Slack apps and integrations. The SDK supports both synchronous and asynchronous operations, making it versatile for different programming styles and requirements.
While the SDK is powerful and regularly updated, its comprehensive nature may make it more complex for developers working on simple integrations. However, for those building more advanced Slack applications, the additional features and official support make it an excellent choice.
As there is no separate repository to compare against, developers should consider their specific needs when deciding whether to use the python-slack-sdk or implement a custom solution using direct API calls.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Python Slack SDK
The Slack platform offers several APIs to build apps. Each Slack API delivers part of the capabilities from the platform, so that you can pick just those that fit for your needs. This SDK offers a corresponding package for each of Slackâs APIs. They are small and powerful when used independently, and work seamlessly when used together, too.
Comprehensive documentation on using the Slack Python can be found at https://slack.dev/python-slack-sdk/
Whether you're building a custom app for your team, or integrating a third party service into your Slack workflows, Slack Developer Kit for Python allows you to leverage the flexibility of Python to get your project up and running as quickly as possible.
The Python Slack SDK allows interaction with:
slack_sdk.web
: for calling the Web API methodsslack_sdk.webhook
: for utilizing the Incoming Webhooks andresponse_url
s in payloadsslack_sdk.signature
: for verifying incoming requests from the Slack API serverslack_sdk.socket_mode
: for receiving and sending messages over Socket Mode connectionsslack_sdk.audit_logs
: for utilizing Audit Logs APIsslack_sdk.scim
: for utilizing SCIM APIsslack_sdk.oauth
: for implementing the Slack OAuth flowslack_sdk.models
: for constructing Block Kit UI components using easy-to-use buildersslack_sdk.rtm
: for utilizing the RTM API
If you want to use our Events API and Interactivity features, please check the Bolt for Python library. Details on the Tokens and Authentication can be found in our Auth Guide.
slackclient is in maintenance mode
Are you looking for slackclient? The website is live here just like before. However, the slackclient project is in maintenance mode now and this slack_sdk
is the successor. If you have time to make a migration to slack_sdk v3, please follow our migration guide to ensure your app continues working after updating.
Table of contents
- Requirements
- Installation
- Getting started tutorial
- Basic Usage of the Web Client
- Async usage
- Advanced Options
- Migrating from v1
- Support
- Development
Requirements
This library requires Python 3.6 and above. If you require Python 2, please use our SlackClient - v1.x. If you're unsure how to check what version of Python you're on, you can check it using the following:
Note: You may need to use
python3
before your commands to ensure you use the correct Python path. e.g.python3 --version
python --version
-- or --
python3 --version
Installation
We recommend using PyPI to install the Slack Developer Kit for Python.
$ pip install slack_sdk
Getting started tutorial
We've created this tutorial to build a basic Slack app in less than 10 minutes. It requires some general programming knowledge, and Python basics. It focuses on the interacting with the Slack Web API and RTM API. Use it to give you an idea of how to use this SDK.
Read the tutorial to get started!
Basic Usage of the Web Client
Slack provide a Web API that gives you the ability to build applications that interact with Slack in a variety of ways. This Development Kit is a module based wrapper that makes interaction with that API easier. We have a basic example here with some of the more common uses but a full list of the available methods are available here. More detailed examples can be found in our guide.
Sending a message to Slack
One of the most common use-cases is sending a message to Slack. If you want to send a message as your app, or as a user, this method can do both. In our examples, we specify the channel name, however it is recommended to use the channel_id
where possible. Also, if your app's bot user is not in a channel yet, invite the bot user before running the code snippet (or add chat:write.public
to Bot Token Scopes for posting in any public channels).
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])
try:
response = client.chat_postMessage(channel='#random', text="Hello world!")
assert response["message"]["text"] == "Hello world!"
except SlackApiError as e:
# You will get a SlackApiError if "ok" is False
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"Got an error: {e.response['error']}")
# Also receive a corresponding status_code
assert isinstance(e.response.status_code, int)
print(f"Received a response status_code: {e.response.status_code}")
Here we also ensure that the response back from Slack is a successful one and that the message is the one we sent by using the assert
statement.
Uploading files to Slack
We've changed the process for uploading files to Slack to be much easier and straight forward. You can now just include a path to the file directly in the API call and upload it that way.
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])
try:
filepath="./tmp.txt"
response = client.files_upload_v2(channel='C0123456789', file=filepath)
assert response["file"] # the uploaded file
except SlackApiError as e:
# You will get a SlackApiError if "ok" is False
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"Got an error: {e.response['error']}")
More details on the files_upload_v2
method can be found here.
Async usage
AsyncWebClient
in this SDK requires AIOHttp under the hood for asynchronous requests.
AsyncWebClient in a script
import asyncio
import os
from slack_sdk.web.async_client import AsyncWebClient
from slack_sdk.errors import SlackApiError
client = AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])
async def post_message():
try:
response = await client.chat_postMessage(channel='#random', text="Hello world!")
assert response["message"]["text"] == "Hello world!"
except SlackApiError as e:
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"Got an error: {e.response['error']}")
asyncio.run(post_message())
AsyncWebClient in a framework
If you are using a framework invoking the asyncio event loop like : sanic/jupyter notebook/etc.
import os
from slack_sdk.web.async_client import AsyncWebClient
from slack_sdk.errors import SlackApiError
client = AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])
# Define this as an async function
async def send_to_slack(channel, text):
try:
# Don't forget to have await as the client returns asyncio.Future
response = await client.chat_postMessage(channel=channel, text=text)
assert response["message"]["text"] == text
except SlackApiError as e:
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
raise e
from aiohttp import web
async def handle_requests(request: web.Request) -> web.Response:
text = 'Hello World!'
if 'text' in request.query:
text = "\t".join(request.query.getall("text"))
try:
await send_to_slack(channel="#random", text=text)
return web.json_response(data={'message': 'Done!'})
except SlackApiError as e:
return web.json_response(data={'message': f"Failed due to {e.response['error']}"})
if __name__ == "__main__":
app = web.Application()
app.add_routes([web.get("/", handle_requests)])
# e.g., http://localhost:3000/?text=foo&text=bar
web.run_app(app, host="0.0.0.0", port=3000)
Advanced Options
SSL
You can provide a custom SSL context or disable verification by passing the ssl
option, supported by both the RTM and the Web client.
For async requests, see the AIOHttp SSL documentation.
For sync requests, see the urllib SSL documentation.
Proxy
A proxy is supported when making async requests, pass the proxy
option, supported by both the RTM and the Web client.
For async requests, see AIOHttp Proxy documentation.
For sync requests, setting either HTTPS_PROXY
env variable or the proxy
option works.
DNS performance
Using the async client and looking for a performance boost? Installing the optional dependencies (aiodns) may help speed up DNS resolving by the client. We've included it as an extra called "optional":
$ pip install slack_sdk[optional]
Example
import os
from slack_sdk import WebClient
from ssl import SSLContext
sslcert = SSLContext()
# pip3 install proxy.py
# proxy --port 9000 --log-level d
proxyinfo = "http://localhost:9000"
client = WebClient(
token=os.environ['SLACK_BOT_TOKEN'],
ssl=sslcert,
proxy=proxyinfo
)
response = client.chat_postMessage(channel="#random", text="Hello World!")
print(response)
Migrating from v2
If you're migrating from slackclient v2.x of slack_sdk to v3.x, Please follow our migration guide to ensure your app continues working after updating.
Check out the Migration Guide here!
Migrating from v1
If you're migrating from v1.x of slackclient to v2.x, Please follow our migration guide to ensure your app continues working after updating.
Check out the Migration Guide here!
Support
If you get stuck, weâre here to help. The following are the best ways to get assistance working through your issue:
Use our Github Issue Tracker for reporting bugs or requesting features. Visit the Slack Community for getting help using Slack Developer Kit for Python or just generally bond with your fellow Slack developers.
Contributing
We welcome contributions from everyone! Please check out our Contributor's Guide for how to contribute in a helpful and collaborative way.
Top Related Projects
A framework to build Slack apps using Python
Slack Developer Kit for Python
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot