使用python利用slack bot发送消息

用到的库

地址

安装: pip install slack_sdk

在slack创建APP

  1. 进入 https://api.slack.com/apps , create a new app
  2. OAuth & Permissions 菜单, 给bot加入权限:
  3. Click the "Allow" button.
  4. https://api.slack.com/apps/xxx/app-home 设置app的名字
  5. 然后可以在 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']}")
        

Flutter 写的app, 需要源码可以私信~~

  • 简繁火星字体转换
  • 哄女友神器
  • 号码测吉凶
  • 电视节目直播表

最好的笔记软件

你可能感兴趣的:(使用python利用slack bot发送消息)