使用 Python 脚本将图像上传到 Slack 频道

Uploading Image to Slack channel with Python Script

我正在尝试简单的事情,使用 python 脚本将本地图片添加到我的松弛频道。我还没有找到答案。我已经为我的频道创建了 slack 应用程序,并且有验证令牌和应用程序 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 时,它给了我令牌错误。 任何人都知道 post 本地图像松弛的快速简便方法吗?

谢谢!

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

您无需同时使用 requests 和 slack 来进行 API 调用。后者就足够了。

这是使用官方 Slack 库将文件上传到 Slack 的示例片段:

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