-
Notifications
You must be signed in to change notification settings - Fork 853
Expand file tree
/
Copy pathREADME.md
More file actions
Ignoring revisions in .git-blame-ignore-revs.
305 lines (219 loc) · 13.2 KB
/
README.md
File metadata and controls
305 lines (219 loc) · 13.2 KB
Edit and raw actions
OlderNewer
1
<h1 align="center">Python Slack SDK</h1>
2
3
<p align="center">
4
<a href="https://github.com/slackapi/python-slack-sdk/actions/workflows/ci-build.yml">
5
<img alt="Tests" src="https://img.shields.io/github/actions/workflow/status/slackapi/python-slack-sdk/ci-build.yml"></a>
6
<a href="https://codecov.io/gh/slackapi/python-slack-sdk">
7
<img alt="Codecov" src="https://img.shields.io/codecov/c/gh/slackapi/python-slack-sdk"></a>
8
<a href="https://pepy.tech/project/slack-sdk">
9
<img alt="Pepy Total Downloads" src="https://img.shields.io/pepy/dt/slack-sdk"></a>
10
<br>
11
<a href="https://pypi.org/project/slack-sdk/">
12
<img alt="PyPI - Version" src="https://img.shields.io/pypi/v/slack-sdk"></a>
13
<a href="https://pypi.org/project/slack-sdk/">
14
<img alt="Python Versions" src="https://img.shields.io/pypi/pyversions/slack-sdk.svg"></a>
15
<a href="https://docs.slack.dev/tools/python-slack-sdk/">
16
<img alt="Documentation" src="https://img.shields.io/badge/dev-docs-yellow"></a>
17
</p>
18
19
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.
20
21
**Comprehensive documentation on using the Slack Python can be found at [https://docs.slack.dev/tools/python-slack-sdk/](https://docs.slack.dev/tools/python-slack-sdk/)**
22
23
---
24
25
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.
26
27
The **Python Slack SDK** allows interaction with:
28
29
- `slack_sdk.web`: for calling the [Web API methods][api-methods]
30
- `slack_sdk.webhook`: for utilizing the [Incoming Webhooks](https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/) and [`response_url`s in payloads](https://docs.slack.dev/interactivity/handling-user-interaction/#message_responses)
31
- `slack_sdk.signature`: for [verifying incoming requests from the Slack API server](https://docs.slack.dev/authentication/verifying-requests-from-slack/)
32
- `slack_sdk.socket_mode`: for receiving and sending messages over [Socket Mode](https://docs.slack.dev/apis/events-api/using-socket-mode/) connections
33
- `slack_sdk.audit_logs`: for utilizing [Audit Logs APIs](https://docs.slack.dev/admins/audit-logs-api/)
34
- `slack_sdk.scim`: for utilizing [SCIM APIs](https://docs.slack.dev/admins/scim-api/)
35
- `slack_sdk.oauth`: for implementing the [Slack OAuth flow](https://docs.slack.dev/authentication/installing-with-oauth/)
36
- `slack_sdk.models`: for constructing [Block Kit](https://docs.slack.dev/block-kit/) UI components using easy-to-use builders
37
- `slack_sdk.rtm`: for utilizing the [RTM API][rtm-docs]
38
39
If you want to use our [Events API][events-docs] and Interactivity features, please check the [Bolt for Python][bolt-python] library. Details on the Tokens and Authentication can be found in our [Auth Guide](https://docs.slack.dev/tools/python-slack-sdk/installation/).
40
41
## slackclient is in maintenance mode
42
43
Are you looking for [slackclient](https://pypi.org/project/slackclient/)? The slackclient project is in maintenance mode now and this [`slack_sdk`](https://pypi.org/project/slack-sdk/) is the successor. If you have time to make a migration to slack_sdk v3, please follow [our migration guide](https://docs.slack.dev/tools/python-slack-sdk/v3-migration/) to ensure your app continues working after updating.
44
45
## Table of contents
46
47
* [Requirements](#requirements)
48
* [Installation](#installation)
49
* [Getting started tutorial](#getting-started-tutorial)
50
* [Basic Usage of the Web Client](#basic-usage-of-the-web-client)
51
* [Sending a message to Slack](#sending-a-message-to-slack)
52
* [Uploading files to Slack](#uploading-files-to-slack)
53
* [Async usage](#async-usage)
54
* [WebClient as a script](#asyncwebclient-in-a-script)
55
* [WebClient in a framework](#asyncwebclient-in-a-framework)
56
* [Advanced Options](#advanced-options)
57
* [SSL](#ssl)
58
* [Proxy](#proxy)
59
* [DNS performance](#dns-performance)
60
* [Example](#example)
61
* [Migrating from v1](#migrating-from-v1)
62
* [Support](#support)
63
* [Development](#development)
64
65
### Requirements
66
67
---
68
69
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:
70
71
> **Note:** You may need to use `python3` before your commands to ensure you use the correct Python path. e.g. `python3 --version`
72
73
```bash
74
python --version
75
76
-- or --
77
78
python3 --version
79
```
80
81
### Installation
82
83
We recommend using [PyPI][pypi] to install the Slack Developer Kit for Python.
84
85
```bash
86
$ pip install slack_sdk
87
```
88
89
### Getting started tutorial
90
91
---
92
93
We've created this [tutorial](https://github.com/slackapi/python-slack-sdk/tree/main/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.
94
95
**[Read the tutorial to get started!](https://github.com/slackapi/python-slack-sdk/tree/main/tutorial)**
96
97
### Basic Usage of the Web Client
98
99
---
100
101
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][api-methods]. More detailed examples can be found in [our guide](https://docs.slack.dev/tools/python-slack-sdk/web/).
102
103
#### Sending a message to Slack
104
105
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).
106
107
```python
108
import os
109
from slack_sdk import WebClient
110
from slack_sdk.errors import SlackApiError
111
112
client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])
113
114
try:
115
response = client.chat_postMessage(channel='#random', text="Hello world!")
116
assert response["message"]["text"] == "Hello world!"
117
except SlackApiError as e:
118
# You will get a SlackApiError if "ok" is False
119
assert e.response["ok"] is False
120
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
121
print(f"Got an error: {e.response['error']}")
122
# Also receive a corresponding status_code
123
assert isinstance(e.response.status_code, int)
124
print(f"Received a response status_code: {e.response.status_code}")
125
```
126
127
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.
128
129
#### Uploading files to Slack
130
131
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.
132
133
```python
134
import os
135
from slack_sdk import WebClient
136
from slack_sdk.errors import SlackApiError
137
138
client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])
139
140
try:
141
filepath="./tmp.txt"
142
response = client.files_upload_v2(channel='C0123456789', file=filepath)
143
assert response["file"] # the uploaded file
144
except SlackApiError as e:
145
# You will get a SlackApiError if "ok" is False
146
assert e.response["ok"] is False
147
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
148
print(f"Got an error: {e.response['error']}")
149
```
150
151
More details on the `files_upload_v2` method can be found [here][files_upload_v2].
152
153
### Async usage
154
155
`AsyncWebClient` in this SDK requires [AIOHttp][aiohttp] under the hood for asynchronous requests.
156
157
#### AsyncWebClient in a script
158
159
```python
160
import asyncio
161
import os
162
from slack_sdk.web.async_client import AsyncWebClient
163
from slack_sdk.errors import SlackApiError
164
165
client = AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])
166
167
async def post_message():
168
try:
169
response = await client.chat_postMessage(channel='#random', text="Hello world!")
170
assert response["message"]["text"] == "Hello world!"
171
except SlackApiError as e:
172
assert e.response["ok"] is False
173
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
174
print(f"Got an error: {e.response['error']}")
175
176
asyncio.run(post_message())
177
```
178
179
#### AsyncWebClient in a framework
180
181
If you are using a framework invoking the asyncio event loop like : sanic/jupyter notebook/etc.
182
183
```python
184
import os
185
from slack_sdk.web.async_client import AsyncWebClient
186
from slack_sdk.errors import SlackApiError
187
188
client = AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])
189
# Define this as an async function
190
async def send_to_slack(channel, text):
191
try:
192
# Don't forget to have await as the client returns asyncio.Future
193
response = await client.chat_postMessage(channel=channel, text=text)
194
assert response["message"]["text"] == text
195
except SlackApiError as e:
196
assert e.response["ok"] is False
197
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
198
raise e
199
200
from aiohttp import web
201
202
async def handle_requests(request: web.Request) -> web.Response:
203
text = 'Hello World!'
204
if 'text' in request.query:
205
text = "\t".join(request.query.getall("text"))
206
try:
207
await send_to_slack(channel="#random", text=text)
208
return web.json_response(data={'message': 'Done!'})
209
except SlackApiError as e:
210
return web.json_response(data={'message': f"Failed due to {e.response['error']}"})
211
212
213
if __name__ == "__main__":
214
app = web.Application()
215
app.add_routes([web.get("/", handle_requests)])
216
# e.g., http://localhost:3000/?text=foo&text=bar
217
web.run_app(app, host="0.0.0.0", port=3000)
218
```
219
220
### Advanced Options
221
222
#### SSL
223
224
You can provide a custom SSL context or disable verification by passing the `ssl` option, supported by both the RTM and the Web client.
225
226
For async requests, see the [AIOHttp SSL documentation](https://docs.aiohttp.org/en/stable/client_advanced.html#ssl-control-for-tcp-sockets).
227
228
For sync requests, see the [urllib SSL documentation](https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen).
229
230
#### Proxy
231
232
A proxy is supported when making async requests, pass the `proxy` option, supported by both the RTM and the Web client.
233
234
For async requests, see [AIOHttp Proxy documentation](https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support).
235
236
For sync requests, setting either `HTTPS_PROXY` env variable or the `proxy` option works.
237
238
#### DNS performance
239
240
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":
241
```bash
242
$ pip install slack_sdk[optional]
243
```
244
245
#### Example
246
247
```python
248
import os
249
from slack_sdk import WebClient
250
from ssl import SSLContext
251
252
sslcert = SSLContext()
253
# pip3 install proxy.py
254
# proxy --port 9000 --log-level d
255
proxyinfo = "http://localhost:9000"
256
257
client = WebClient(
258
token=os.environ['SLACK_BOT_TOKEN'],
259
ssl=sslcert,
260
proxy=proxyinfo
261
)
262
response = client.chat_postMessage(channel="#random", text="Hello World!")
263
print(response)
264
```
265
266
### Migrating from v2
267
268
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.
269
270
**[Check out the Migration Guide here!](https://docs.slack.dev/tools/python-slack-sdk/v3-migration/)**
271
272
### Migrating from v1
273
274
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.
275
276
**[Check out the Migration Guide here!](https://github.com/slackapi/python-slack-sdk/wiki/Migrating-to-2.x)**
277
278
### Support
279
280
---
281
282
If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue:
283
284
Use our [Github Issue Tracker][gh-issues] for reporting bugs or requesting features.
285
Visit the [Slack Community][slack-community] for getting help using Slack Developer Kit for Python or just generally bond with your fellow Slack developers.
286
287
### Contributing
288
289
We welcome contributions from everyone! Please check out our
290
[Contributor's Guide](.github/contributing.md) for how to contribute in a
291
helpful and collaborative way.
292
293
<!-- Markdown links -->
294
295
[slackclientv1]: https://github.com/slackapi/python-slackclient/tree/v1
296
[api-methods]: https://docs.slack.dev/reference/methods
297
[rtm-docs]: https://docs.slack.dev/legacy/legacy-rtm-api/
298
[events-docs]: https://docs.slack.dev/apis/events-api/
299
[bolt-python]: https://github.com/slackapi/bolt-python
300
[pypi]: https://pypi.org/
301
[gh-issues]: https://github.com/slackapi/python-slack-sdk/issues
302
[slack-community]: https://slackcommunity.com/
303
[files_upload_v2]: https://github.com/slackapi/python-slack-sdk/releases/tag/v3.19.0
304
[aiohttp]: https://aiohttp.readthedocs.io/