Access Slack files from a slack bot

Viewed 11020

I need a slack bot that's able to receive and save files send from slack chatrooms.

The problem is: slack doesn't send file contents, but an array of links pointing to the file. Most of them, including download link are private and cannot be accessed via bot. It does send one public link, but that link points at the file preview, which does not have the file itself (here's an example).

So the question is: how can I access uploaded files via bot?

4 Answers

Example for using the Python requests library to fetch an example file:

import requests
url = 'https://slack-files.com/T0JU09BGC-F0UD6SJ21-a762ad74d3'
token = 'xoxp-8853424449-8820034832-8891394196-faf6f0'
requests.get(url, headers={'Authorization': 'Bearer %s' % token})

Tested with Python3 - just replace SLACK_TOKEN with your token. Downloads and creates an output file.

#!/usr/bin/env python3
# Usage: python3 download_files_from_slack.py <URL>

import sys
import re
import requests

url = " ".join(sys.argv[1:])

token = 'SLACK_TOKEN'
resp = requests.get(url, headers={'Authorization': 'Bearer %s' % token})

headers = resp.headers['content-disposition']
fname = re.findall("filename=(.*?);", headers)[0].strip("'").strip('"')

assert not os.path.exists(fname), print("File already exists. Please remove/rename and re-run")
out_file = open(fname, mode="wb+")
out_file.write(resp.content)
out_file.close()
Related