Skip to content

Instantly share code, notes, and snippets.

@edokan
Forked from marnitto/slack-download.py
Last active May 29, 2018 07:26
Show Gist options
  • Save edokan/78f786df9aa217f654c2e1e525c98b71 to your computer and use it in GitHub Desktop.
Save edokan/78f786df9aa217f654c2e1e525c98b71 to your computer and use it in GitHub Desktop.
Slack file downloader from export archive
# -*- coding: utf-8 -*-
#
# Slack file downloader from export archive
#
# Requirements:
# Python 2 (or Python3 if you can use six)
#
# How to use:
# 1. Log in as admin, export your chat logs, and download archive.
# 2. Unarchive archive to directory (ex. TeamName export Apr 24 2016)
# 3. Run this script.
# `python slack-download.py "TeamName export Apr 24 2016"`
import json
import sys
import urllib
import urlparse
import os
import glob
def err(message):
print('[-] '+message)
os.exit(-1)
def main(export_path):
if not os.path.isdir(export_path):
err('Slack exported directory required.')
os.chdir(export_path)
for check_file in ('users.json', 'channels.json'):
if not os.path.isfile(check_file):
err('It seems that given directory is not an export directory.')
for json_path in glob.glob('*/*.json'):
channel, filename = os.path.split(json_path)
date = filename.split('.')[0]
with open(json_path, 'rb') as f:
data = json.load(f)
for content in data:
if 'file' not in content:
continue
if 'url_private_download' not in content['file']:
continue
url = content['file']['url_private_download']
id = content['file']['id']
try:
os.mkdir(os.path.join(channel, date))
except OSError:
pass
filename = "%s - %s" % (id, urlparse.urlparse(url).path.split('/')[-1])
download_path = os.path.join(channel, date, filename)
if os.path.isfile(filename):
print('[*] Already downloaded %s' % url)
continue
print('[+] Downloading %s -> %s' % (url, download_path))
with open(download_path, 'wb') as f:
f.write(urllib.urlopen(url).read())
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: %s <Slack exported directory>' % sys.argv[0])
sys.exit(-1)
export_path = sys.argv[1]
main(export_path)
@edokan
Copy link
Author

edokan commented May 29, 2018

Now does not try to download an already downloaded file and prefixes filenames with slack ids, so files with same name does not get overwritten.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment