【问题标题】:Uploading Image to Slack channel with Python Script使用 Python 脚本将图像上传到 Slack 频道
【发布时间】:2020-06-06 09:00:33
【问题描述】:

我正在尝试简单的事情,使用 python 脚本将本地图片添加到我的 slack 频道。我还没有找到答案。我已经为我的频道创建了 Slack 应用程序,并拥有验证令牌和 APP ID。

我尝试了以下但没有结果:

import requests

    files = {
    'file': ('dog.jpg', open('dog.jpg', 'rb')),
    'channels': (None, 'App ID,#channel'),
    'token': (None, 'Verification Token'),
    }

还有:

    import os
from slack import WebClient
from slack.errors import SlackApiError

client = WebClient(token=os.environ['SLACK_API_TOKEN'])

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']}")

response = requests.post('https://slack.com/api/files.upload', files=files)

在这里,当我将我的 Slack 应用程序令牌插入 SLACK_API_TOKEN 时,它会给我令牌错误。 任何人都知道将本地图像发布到 Slack 的快速简便的方法?

谢谢!

【问题讨论】:

    标签: python slack slack-api


    【解决方案1】:

    验证令牌不能用于 API 调用。您需要用户或机器人令牌。请参阅有关如何获取令牌的答案:Slack App, token for Web API

    您不需要同时使用请求和松弛来进行 API 调用。后者就足够了。

    这是一个使用官方 Slack 库将文件上传到 Slack 的示例 sn-p:

    import os
    import slack
    from slack.errors import SlackApiError
    
    # init slack client with access token
    slack_token = os.environ['SLACK_TOKEN']
    client = slack.WebClient(token=slack_token)
    
    # upload file
    try:
        response = client.files_upload(    
            file='Stratios_down.jpg',
            initial_comment='This space ship needs some repairs I think...',
            channels='general'
        )
    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']}")
    
    

    【讨论】:

    • 感谢您的快速回复。我正在将我的 Slack Bot 用户 OAuth 访问令牌复制到“SLACK_TOKEN”,但它会引发 KeyError: 'xoxb-1190...
    • 嘿。 SLACK_TOKEN 是环境变量,需要在代码外设置。这是一个很好的方法,因为它是安全的。或者,您可以直接将slack_token 设置为您的令牌字符串。
    • 谢谢,工作,并记得在 slack 中邀请机器人加入频道。
    • 很高兴你让它工作。如果此答案解决了您的问题,请考虑通过单击复选标记将其标记为解决方案。谢谢!
    猜你喜欢
    • 2022-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    相关资源
    最近更新 更多