美文网首页
使用python利用slack bot发送消息

使用python利用slack bot发送消息

作者: yytester | 来源:发表于2021-01-29 16:27 被阅读0次

    用到的库

    地址

    安装: 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发送消息

          本文链接:https://www.haomeiwen.com/subject/reaqtltx.html