How to bulk remove files from Slack

We are starting to roll out Slack at my company. Coming from Skype, Slack feels just right for us, so I'm very excited about the transition. However, the basic plan comes with just 5GB of file storage and we already found ourselves out of space.

If you are an admin, you can always remove files using the web interface, but right now there's no way to bulk remove them, so you have to go file by file which takes an insane amount of time. The API neither provides a method to delete files just yet, so that isn't an option. You're basically stuck...

Or not.

I put together We put together (see update at the end of this post) a short Python script to remove all the files older than 30 days. It combines the API method to retrieve the list of existing files with a form POST to the URL the web interface uses to remove a particular file.

import requests
import json
import calendar
from datetime import datetime, timedelta

_token = "YOUR TOKEN GOES HERE"
_domain = "YOUR SUB DOMAIN HERE"

if __name__ == '__main__':
    while 1:
        files_list_url = 'https://slack.com/api/files.list'
        date = str(calendar.timegm((datetime.now() + timedelta(-30))
            .utctimetuple()))
        data = {"token": _token, "ts_to": date}
        response = requests.post(files_list_url, data = data)
        if len(response.json()["files"]) == 0:
            break
        for f in response.json()["files"]:
            print "Deleting file " + f["name"] + "..."
            timestamp = str(calendar.timegm(datetime.now().utctimetuple()))
            delete_url = "https://" + _domain + ".slack.com/api/files.delete?t=" + timestamp
            requests.post(delete_url, data = {
                "token": _token, 
                "file": f["id"], 
                "set_active": "true", 
                "_attempts": "1"})
    print "DONE!"

If you want to use it, make sure you do the following:

  1. Get a token from the Slack API page
  2. Copy the script above and save it as slack.py
  3. Plug your token in the code (using the _token variable)
  4. Install Python in your system if you don't have it already
  5. Install the (awesome) requests library
  6. Execute your script by running "python slack.py" (without the quotes)

Now you can enjoy your space back.

(The Slack API returns 100 files at the time, so you might need to run the script multiple times in order to remove all the files. Of course, you can always modify the script in code to take care of that, but we didn't need it.)

Update 08/20/2015: Dana Hanna contacted me via Twitter. He made some modifications to my script to make sure it's easy for you to run in case you want to do so. I went ahead and updated this post to use his solution. Much better now!

Have something to say about this post? Get in touch!

Want to read more? Visit the archive.