Skip to content

Instantly share code, notes, and snippets.

@xaman
Created June 29, 2017 14:13
Show Gist options
  • Save xaman/6308edf5b1077ae7a67058186ec1f071 to your computer and use it in GitHub Desktop.
Save xaman/6308edf5b1077ae7a67058186ec1f071 to your computer and use it in GitHub Desktop.
Python script to delete Slack files (older than 1 month)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pycurl
import json
import time
from StringIO import StringIO
#
# Inspired by this Ruby version: https://gist.github.com/jamescmartinez/909401b19c0f779fc9c1
# Legacy token obtained in https://api.slack.com/custom-integrations/legacy-tokens
#
TOKEN = ""
ONE_MONTH = 30 * 24 * 3600
TIMESTAMP = int(round(time.time())) - ONE_MONTH
COUNT = 1000
def _main():
json = request_files()
if (json):
delete_files(json)
def request_files():
endpoint = "https://slack.com/api/files.list"
data = "token=%s&ts_to=%s&count=%s" % (TOKEN, TIMESTAMP, COUNT)
response = request(endpoint, data, 10)
if (response):
return json.loads(response)
def delete_files(json):
files = json["files"]
print "%s files to delete" % len(files)
pos = 0
for file in files:
pos += 1
print "%s) Deleting file: %s" % (pos, file["title"]),
delete_file(file)
def delete_file(file):
endpoint = "https://slack.com/api/files.delete"
data = "token=%s&file=%s" % (TOKEN, file["id"])
response = request(endpoint, data)
if (response):
response_json = json.loads(response)
print "-> %s" % response_json["ok"]
def request(endpoint, data, timeout=2):
try:
request = pycurl.Curl()
request.setopt(pycurl.URL, endpoint)
request.setopt(pycurl.POSTFIELDS, data)
request.setopt(pycurl.CONNECTTIMEOUT, timeout)
request.setopt(pycurl.TIMEOUT, timeout)
request.setopt(pycurl.SSL_VERIFYHOST, 0)
request.setopt(pycurl.SSL_VERIFYPEER, False)
buffer = StringIO()
request.setopt(pycurl.WRITEFUNCTION, buffer.write)
request.perform()
response = buffer.getvalue()
buffer.close()
request.close()
return response
except pycurl.error, e:
print "-> %s" % e.args[1]
request.close()
return None
if __name__ == '__main__':
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment