Created
August 15, 2016 16:44
-
-
Save gregswift/df68c3b58c9449ad8b3a05f231ed7b6c to your computer and use it in GitHub Desktop.
Script to clean up files older than X period from Slack
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
#!/usr/bin/env python | |
# Original credit to Santiago L. Valdarrama | |
# http://www.shiftedup.com/2014/11/13/how-to-bulk-remove-files-from-slack | |
# | |
# Script requires SLACK_TEAM and SLACK_TOKEN to be defined in your environment. | |
# You can get the token from https://api.slack.com/docs/oauth-test-tokens | |
# | |
import requests | |
import json | |
import calendar | |
from datetime import datetime, timedelta | |
import os | |
import sys | |
DEFAULT_PERIOD=-30 | |
def get_file_list(token, timeperiod=DEFAULT_PERIOD): | |
""" | |
timeperiod should be a negative integer | |
""" | |
date = str(calendar.timegm((datetime.now() + timedelta(timeperiod)) | |
.utctimetuple())) | |
data = {'token': token, 'ts_to': date} | |
files_uri = 'https://slack.com/api/files.list' | |
response = requests.post(files_uri, data = data) | |
if response.status_code != 200: | |
raise Exception, 'Query failed with data {0}'.format(data) | |
return response.json()['files'] | |
def delete_file(team, token, file_id): | |
""" | |
file_id should be the value of 'id' from the file hash returned by the Slack API | |
""" | |
timestamp = str(calendar.timegm(datetime.now().utctimetuple())) | |
delete_url = 'https://{0}.slack.com/api/files.delete?t={1}' | |
response = requests.post(delete_url.format(team, timestamp), data = { | |
'token': token, | |
'file': file_id, | |
'set_active': 'true', | |
'_attempts': '1'}) | |
if response.status_code == 200: | |
return True | |
return False | |
def cleanup(team, token, timeperiod): | |
deleted = 0 | |
errored = 0 | |
remaining = 1 | |
last_files = None | |
while remaining: | |
files = get_file_list(team, token, timeperiod) | |
if last_files == files: | |
print("WARNING: Only undeleteable files remain. " | |
"Listed files above may still exist. " | |
"Re-run to see a list") | |
break | |
remaining = len(files) | |
for f in files: | |
try: | |
print('Deleting file {0} ({1})...'.format(f['name'], f['id'])) | |
except UnicodeEncodeError: | |
print('Deleting file id {0}...'.format(f['id'])) | |
if delete_file(team, token, f['id']): | |
deleted += 1 | |
else: | |
errored += 1 | |
last_files = files | |
print('Status: {0} Deleted. {1} Errored.'.format(deleted, errored)) | |
print('DONE! {0} Deleted. {1} Errored.'.format(deleted, errored)) | |
if __name__ == '__main__': | |
token = os.environ.get('SLACK_TOKEN', None) | |
team = os.environ.get('SLACK_TEAM', None) | |
if not token or not team: | |
sys.stderr.write('Must define both SLACK_TOKEN and SLACK_TEAM in your environment\n') | |
sys.exit(1) | |
timeperiod = DEFAULT_PERIOD | |
if len(sys.argv) == 2: | |
timeperiod = sys.argv[1] | |
if timeperiod > 0: | |
# Let people define positive or negative time periods at the CLI | |
# translate all of them to negative, cause you can't delete the future! | |
timeperiod = 0 - timeperiod | |
cleanup(team, token, timeperiod) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment