无法使用松弛的api files.upload上传文件

时间:2019-06-09 02:21:42

标签: python-3.x python-requests slack-api

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

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

我在堆栈溢出中也看到了许多类似的问题,但没有一个解决了这个问题。 [链接] no_file_data error when using Slack API upload [链接] How to upload files to slack using file.upload and requests

下面是我的代码。

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)

请帮助解决该问题。

1 个答案:

答案 0 :(得分:1)

我需要在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)
相关问题