Python Slack API下载二进制文件返回HTML问题求助
Slack私有文件下载失败的解决建议
核心原因是你用命令行或Python请求时没带Slack的身份验证信息,浏览器能成功是因为自动携带了登录状态的Cookie,而工具请求被重定向到Slack的登录页面(那40KB的HTML就是登录页内容)。下面是具体解决方法:
给请求添加认证头
Slack的url_private_download私有链接需要通过API Token验证身份,不管用Python还是命令行工具,都要带上Authorization头:- Python requests示例:
import requests slack_token = "你的Slack API Token" download_url = message['files'][0]['url_private_download'] headers = {"Authorization": f"Bearer {slack_token}"} resp = requests.get(download_url, headers=headers) with open("目标文件名", "wb") as f: f.write(resp.content) - curl示例:
curl -H "Authorization: Bearer 你的Slack API Token" 你的下载URL --output 目标文件名 - wget示例:
wget --header="Authorization: Bearer 你的Slack API Token" -O 目标文件名 你的下载URL
- Python requests示例:
检查Token权限
确保你的Slack API Token拥有files:read权限,没有的话去Slack开发者控制台的权限设置里添加,否则就算带了Token也会被拒绝访问。直接调用files.download API
不用私有下载链接,直接通过Slack的files.download接口下载,更稳定:import requests slack_token = "你的Slack API Token" file_id = message['files'][0]['id'] api_url = "https://slack.com/api/files.download" resp = requests.get(api_url, params={"token": slack_token, "file": file_id}) with open("目标文件名", "wb") as f: f.write(resp.content)
内容的提问来源于stack exchange,提问作者stephen
相关产品推荐
相关产品推荐

