Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
delete images from slack
'''
delete_slack_images.py
Deletes all images from slack to free up space on free slack.
Usage:
Set your slack user token to the env variable "SLACK_TOKEN" then run like:
python delete_slack_images.py
It will tell you how many images it's about to delete and ask for confirmation.
'''
from __future__ import print_function
import requests
import os
import sys
token = os.getenv('SLACK_TOKEN')
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}
def get_ids(maxpages=None):
print("Gathering list of files to delete....")
if maxpages is None:
maxtries = 1000
else:
maxtries = maxpages
ids = []
currentpage = 1
maxpages = 0
filetype = "images"
attempt = 0
while True:
attempt += 1
if attempt > maxtries:
break
url = "https://slack.com/api/files.list?token=%s&types=%s&page=%s" % (token,filetype,str(currentpage))
response = requests.get(url=url, headers=headers)
if response.json().get('ok'):
for thing in response.json().get("files"):
ids.append(thing.get('id'))
maxpages = int(response.json().get("paging").get("pages"))
print(response.json().get("paging"))
currentpage += 1
if currentpage > maxpages:
break
return ids
def delete_ids(ids):
oneshot = False
for i,fid in enumerate(ids):
print("Deleting %d of %d..." % (i+1, len(ids)))
url = "https://slack.com/api/files.delete?token=%s&file=%s" % (token,fid)
response = requests.post(url=url,headers=headers)
if oneshot:
break
print("Done")
def main():
#ids = get_ids(maxpages=1)
ids = get_ids()
print("Deleting %d images." % len(ids))
response = raw_input("ARE YOU SURE YOU WANT TO DELETE ALL THESE IMAGES??!?!?!?!? (y/n): ")
if response.lower() == 'y':
print("Ok, here we go...")
delete_ids(ids)
else:
sys.exit(0)
if __name__ == "__main__":
main()
GC02RQ08ZG8WPE:slackin russellendicott$ python delete_slack_images.py
Gathering list of files to delete....
{u'count': 100, u'total': 4259, u'page': 1, u'pages': 43}
Deleting 39 images.
ARE YOU SURE YOU WANT TO DELETE ALL THESE IMAGES??!?!?!?!? (y/n): y
Ok, here we go...
Deleting 1 of 39...
Deleting 2 of 39...
....
Deleting 37 of 39...
Deleting 38 of 39...
Deleting 39 of 39...
Done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.