- Notifications
You must be signed in to change notification settings - Fork847
Slack Developer Kit for Python
License
slackapi/python-slack-sdk
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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 athttps://docs.slack.dev/tools/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.
ThePython Slack SDK allows interaction with:
slack_sdk.web: for calling theWeb API methodsslack_sdk.webhook: for utilizing theIncoming Webhooks andresponse_urls in payloadsslack_sdk.signature: forverifying incoming requests from the Slack API serverslack_sdk.socket_mode: for receiving and sending messages overSocket Mode connectionsslack_sdk.audit_logs: for utilizingAudit Logs APIsslack_sdk.scim: for utilizingSCIM APIsslack_sdk.oauth: for implementing theSlack OAuth flowslack_sdk.models: for constructingBlock Kit UI components using easy-to-use buildersslack_sdk.rtm: for utilizing theRTM API
If you want to use ourEvents API and Interactivity features, please check theBolt for Python library. Details on the Tokens and Authentication can be found in ourAuth Guide.
Are you looking forslackclient? The slackclient project is in maintenance mode now and thisslack_sdk is the successor. If you have time to make a migration to slack_sdk v3, please followour migration guide to ensure your app continues working after updating.
- Requirements
- Installation
- Getting started tutorial
- Basic Usage of the Web Client
- Async usage
- Advanced Options
- Migrating from v1
- Support
- Development
This library requires Python 3.7 and above. 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
python3before your commands to ensure you use the correct Python path. e.g.python3 --version
python --version-- or --python3 --version
We recommend usingPyPI to install the Slack Developer Kit for Python.
$ pip install slack_sdk
We've created thistutorial 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!
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 availablehere. More detailed examples can be found inour guide.
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 thechannel_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 addchat:write.public to Bot Token Scopes for posting in any public channels).
importosfromslack_sdkimportWebClientfromslack_sdk.errorsimportSlackApiErrorclient=WebClient(token=os.environ['SLACK_BOT_TOKEN'])try:response=client.chat_postMessage(channel='#random',text="Hello world!")assertresponse["message"]["text"]=="Hello world!"exceptSlackApiErrorase:# You will get a SlackApiError if "ok" is Falseasserte.response["ok"]isFalseasserte.response["error"]# str like 'invalid_auth', 'channel_not_found'print(f"Got an error:{e.response['error']}")# Also receive a corresponding status_codeassertisinstance(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 theassert statement.
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.
importosfromslack_sdkimportWebClientfromslack_sdk.errorsimportSlackApiErrorclient=WebClient(token=os.environ['SLACK_BOT_TOKEN'])try:filepath="./tmp.txt"response=client.files_upload_v2(channel='C0123456789',file=filepath)assertresponse["file"]# the uploaded fileexceptSlackApiErrorase:# You will get a SlackApiError if "ok" is Falseasserte.response["ok"]isFalseasserte.response["error"]# str like 'invalid_auth', 'channel_not_found'print(f"Got an error:{e.response['error']}")
More details on thefiles_upload_v2 method can be foundhere.
AsyncWebClient in this SDK requiresAIOHttp under the hood for asynchronous requests.
importasyncioimportosfromslack_sdk.web.async_clientimportAsyncWebClientfromslack_sdk.errorsimportSlackApiErrorclient=AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])asyncdefpost_message():try:response=awaitclient.chat_postMessage(channel='#random',text="Hello world!")assertresponse["message"]["text"]=="Hello world!"exceptSlackApiErrorase:asserte.response["ok"]isFalseasserte.response["error"]# str like 'invalid_auth', 'channel_not_found'print(f"Got an error:{e.response['error']}")asyncio.run(post_message())
If you are using a framework invoking the asyncio event loop like : sanic/jupyter notebook/etc.
importosfromslack_sdk.web.async_clientimportAsyncWebClientfromslack_sdk.errorsimportSlackApiErrorclient=AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])# Define this as an async functionasyncdefsend_to_slack(channel,text):try:# Don't forget to have await as the client returns asyncio.Futureresponse=awaitclient.chat_postMessage(channel=channel,text=text)assertresponse["message"]["text"]==textexceptSlackApiErrorase:asserte.response["ok"]isFalseasserte.response["error"]# str like 'invalid_auth', 'channel_not_found'raiseefromaiohttpimportwebasyncdefhandle_requests(request:web.Request)->web.Response:text='Hello World!'if'text'inrequest.query:text="\t".join(request.query.getall("text"))try:awaitsend_to_slack(channel="#random",text=text)returnweb.json_response(data={'message':'Done!'})exceptSlackApiErrorase:returnweb.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=barweb.run_app(app,host="0.0.0.0",port=3000)
You can provide a custom SSL context or disable verification by passing thessl option, supported by both the RTM and the Web client.
For async requests, see theAIOHttp SSL documentation.
For sync requests, see theurllib SSL documentation.
A proxy is supported when making async requests, pass theproxy option, supported by both the RTM and the Web client.
For async requests, seeAIOHttp Proxy documentation.
For sync requests, setting eitherHTTPS_PROXY env variable or theproxy option works.
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]
importosfromslack_sdkimportWebClientfromsslimportSSLContextsslcert=SSLContext()# pip3 install proxy.py# proxy --port 9000 --log-level dproxyinfo="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)
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!
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!
If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue:
Use ourGithub Issue Tracker for reporting bugs or requesting features.Visit theSlack Community for getting help using Slack Developer Kit for Python or just generally bond with your fellow Slack developers.
We welcome contributions from everyone! Please check out ourContributor's Guide for how to contribute in ahelpful and collaborative way.
About
Slack Developer Kit for Python
Topics
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.