Невозможно загрузить файл, используя slack api files.upload - PullRequest
0 голосов
/ 09 июня 2019

Этот вопрос может показаться дублирующим, но я много пробовал, но не добился успеха. Я пытаюсь загрузить HTML-файл, используя https://slack.com/api/files.upload API, но всегда получаю ошибку ниже. ответ {'ok': False, 'error': 'no_file_data'}

Я просмотрел документацию [ссылка] https://api.slack.com/methods/files.upload и попытался использовать другие варианты, но все равно получаю один и тот же ответ {'ok': False, 'error': 'no_file_data'}

Также я видел много похожих вопросов о переполнении стека, но ни один из них не решил проблему. [ссылка] ошибка no_file_data при использовании загрузки Slack API [ссылка] Как загрузить файлы в slack, используя file.upload и запросы

Ниже мой код.

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 Ответ

1 голос
/ 11 июня 2019

Мне нужно было добавить аргумент "content" и аргумент "filename" вместо аргумента "file" в полезной нагрузке API files.upload, теперь загрузка файлов в свободный канал работает нормально.

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)
...