繁体   English   中英

无法使用 slack api files.upload 上传文件

[英]Not able to upload file using slack api files.upload

这个问题可能看起来重复,但我尝试了很多但没有成功。 我正在尝试使用https://slack.com/api/files.upload API 上传 html 文件,但我总是遇到以下错误。 响应 {'ok': False, 'error': 'no_file_data'}

我浏览了文档 [链接] https://api.slack.com/methods/files.upload并尝试了不同的选项,但仍然得到相同的响应 {'ok': False, 'error': 'no_file_data' }

我也在堆栈溢出中看到了许多类似的问题,但没有一个解决了问题。 [链接] 使用 Slack API 上传时出现 no_file_data 错误[链接] 如何使用 file.upload 和请求将文件上传到 slack

下面是我的代码。

import requests

def post_reports_to_slack(html_report):
    """
    """
    url = "https://slack.com/api/files.upload"

    # my_file = {html_report, open(html_report, 'rb'), 'html'}

    data = {
        "token": bot_user_token,
        "channels": channel_name,
        "file": html_report,
        "filetype": "html"
    }

    # data = "token=" + bot_user_token + \
    #        "&channels=" + channel_name +\
    #        "&file=" + html_report + "&filetype=" + "html"

    response = requests.post(
        url=url, data=data,
        headers={"Content-Type": "application/x-www-form-urlencoded"})
    print("response", response)
    print(response.json())
    if response.status_code == 200:
        print("successfully completed post_reports_to_slack "
                      "and status code %s" % response.status_code)
    else:
        print("Failed to post report on slack channel "
                      "and status code %s" % response.status_code)

请帮助解决问题。

我需要在 files.upload API 负载中添加“content”参数和“filename”参数而不是“file”参数,现在文件上传到松弛通道工作正常。

import requests

def post_reports_to_slack(html_report):
    url = "https://slack.com/api/files.upload"

    with open(html_report) as fh:
        html_data = fh.read()

    data = {
        "token": bot_user_token,
        "channels": "#channel_name",
        "content": html_data,
        "filename": "report.html",
        "filetype": "html",
    }

    response = requests.post(
        url=url, data=data,
        headers={"Content-Type": "application/x-www-form-urlencoded"})
    if response.status_code == 200:
        print("successfully completed post_reports_to_slack "
                      "and status code %s" % response.status_code)
    else:
        print("Failed to post report on slack channel "
                      "and status code %s" % response.status_code)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM