Created
October 8, 2018 08:48
-
-
Save igniteflow/170df9808ca5e68c3dc4ba16bb92cb64 to your computer and use it in GitHub Desktop.
Download all images from a Slack channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import requests | |
import os.path | |
TOKEN = 'xxxx-xxxx' | |
TARGET_DIR = './images/' | |
# get slack names | |
response = requests.get( | |
'https://slack.com/api/users.list', | |
params=dict( | |
token=TOKEN | |
) | |
) | |
content = response.json() | |
SLACK_NAMES = { | |
u['id']: u['name'] | |
for u in content['members'] | |
} | |
# get files | |
channel_name = 'foobar' | |
url = 'https://slack.com/api/search.files' | |
params = { | |
'query': 'in:' + channel_name, | |
'pretty': 1, | |
'count': 1000, | |
'token': TOKEN, | |
} | |
response = requests.get(url, params=params) | |
content = response.json() | |
def download_file(match): | |
url = match['url_private_download'] | |
headers = {"Authorization": "Bearer {}".format(TOKEN)} | |
filename = '{}r{}-{}-{}.{}'.format( | |
TARGET_DIR, | |
sum([reaction.get('count', 0) for reaction in match.get('reactions', [])]), | |
datetime.datetime.fromtimestamp(match['timestamp']), | |
SLACK_NAMES[match['user']], | |
match['filetype'] | |
) | |
if os.path.isfile(filename): | |
print('{} exists, skipping...'.format(filename)) | |
return | |
with open(filename, 'wb') as f: | |
r = requests.get(url, stream=True, headers=headers) | |
for chunk in r.iter_content(chunk_size=1024): | |
if chunk: | |
f.write(chunk) | |
print('Saved: {}'.format(TARGET_DIR + filename)) | |
for match in content['files']['matches']: | |
download_file(match) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment