I created a bot which collects info from users in a workspace. It stores this info in a csv file on the local server. How do I download said file? I got this bit of code from Stack Overflow, attempted to contact the author but didn't get any response.
import requests
url = 'https://slack-files.com/T0JU09BGC-F0UD6SJ21-a762ad74d3'
token = 'xoxp-TOKEN'
requests.get(url, headers={'Authorization': 'Bearer %s' % token})
How do I obtain the URL & token of the file? What is the token? Is it the OAuth token of the bot?
Say I wished to download the file named stats.csv
from the server that was created by the slackbot and I don't have it's URL, how would I download it?
I would not recommend to patch together the URL for downloading the file yourself, because Slack might change it and then your code breaks.
Instead, first get the current URL of the file by calling the API method files.info
with the file ID. Then use property url_private
as URL for download. Alternatively you can also call files.list
to get the list of all files with IDs and their URLs.
To ensure you have access to the file its best to use the token from it's creator, e.g. your slackbot.
I also included the code to save the downloaded data to file and some rudimentary error handling. Note that the token is excepted to be set as environment variable names SLACK_TOKEN
. This is much safer than putting it directly into the code.
Here is a complete example:
import os
import requests
token = os.environ['SLACK_TOKEN']
file_id = "F12345678"
# call file info to get url
url = "https://slack.com/api/files.info"
r = requests.get(url, {"token": token, "file": file_id})
r.raise_for_status
response = r.json()
assert response["ok"]
file_name = response["file"]["name"]
file_url = response["file"]["url_private"]
print("Downloaded " + file_name)
# download file
r = requests.get(file_url, headers={'Authorization': 'Bearer %s' % token})
r.raise_for_status
file_data = r.content # get binary content
# save file to disk
with open(file_name , 'w+b') as f:
f.write(bytearray(file_data))
print("Saved " + file_name + " in current folder")