用到的库
安装: pip install slack_sdk
在slack创建APP
- 进入
https://api.slack.com/apps
,create a new app
- 在
OAuth & Permissions
菜单, 给bot加入权限: - Click the "Allow" button.
- 在
https://api.slack.com/apps/xxx/app-home
设置app的名字 - 然后可以在
OAuth Tokens for Your Team
看到 Token
加入channel
创建完app后, 在slack里, Add xxx to a channel
代码
发送文本消息代码
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
client = WebClient(token='xxxx')
try:
response = client.chat_postMessage(channel='xxx', text="Hello world22!")
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']}")
发送图片或者其他文本附件
import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
client = WebClient(token='xxx')
try:
filepath="./tmp.txt"
response = client.files_upload(channels='#random', 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']}")