0

I have this script to delete files from my slack account:

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

_token = re.escape("token")
_domain = re.escape("domain")

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!"

Im getting this error:

File "main.py", line 28, in files = json.loads(content)["files"] KeyError: 'files'

Am i missing something? Tks!

2 Answers 2

1

You're expecting that json.loads() will return a dict that will have a key named files. But in reality, the parsed data doesn't have that key.

You can do these instead:

payload = json.loads(content)
files = payload.get('files')

This way files will either contain the actual files as in the JSON payload. If the files key does not exist, it will return None.

You can also pass a value to the get method to set the default value if the key is not found, like these:

files = payload.get('files', [])

This way files will be an empty list if the files key doesn't exist.

Sign up to request clarification or add additional context in comments.

Comments

1

Switch

if len(response.json()["files"]) == 0:

To

if len(response.json().get("files", [])) == 0:

By default, the get method returns None if the attribute doesn't exist, whereas the [] notation throws up an error if the item doesn't exist. If the response.json() doesn't have a files attribute (which is what's happening here) then it will break out.

2 Comments

If "files" key doesn't exist, the get method will return None. Running len() on None will not be fun ;)
Great point, thank you! Switching get to return an empty list instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.