Skip to content

Instantly share code, notes, and snippets.

@fission6
Created March 16, 2017 20:45
Show Gist options
  • Save fission6/16e1a2d0a792fb26e3d3478938ef2797 to your computer and use it in GitHub Desktop.
Save fission6/16e1a2d0a792fb26e3d3478938ef2797 to your computer and use it in GitHub Desktop.
Clean out old slack files to free up space
import os
import requests
from datetime import datetime, timedelta
# Days aged
DAYS_AGED = 30
# token from https://api.slack.com/web
TOKEN = os.environ.get('SLACK_TOKEN') # set an env variable for slack token
ENDPOINT = 'https://slack.com/api/{}'
CUT_OFF_DATE = (datetime.now() + timedelta(-DAYS_AGED)).strftime('%s')
def grab_files():
"""
Return all fiels older than DAYS_AGED
"""
print "Fetching Files"
resource = ENDPOINT.format('files.list')
files = []
page = 0
while True:
# loop through until we've fetched all pages
page += 1
print "Fetching Page: ", page
data = {"token": TOKEN, "ts_to": CUT_OFF_DATE, "page": page}
resp = requests.post(resource, data=data).json()
files.extend(resp.get('files'))
pages = resp.get('paging').get('pages')
# we done?
if page >= pages:
break
return files
def delete_files(files):
"""
Remove files
"""
resource = ENDPOINT.format('files.delete')
for file in files:
name = file.get('name')
file_id = file.get('id')
data = {"token": TOKEN, "file": file_id}
resp = requests.post(resource, data=data).json()
if resp.get('ok'):
print "Deleted: ", name
else:
print "Error Deleted: ", name, resp.get('error')
if __name__ == '__main__':
if TOKEN:
files = grab_files()
delete_files(files)
print "Complete"
else:
print "You need to set a SLACK_API environment variable!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment