Last active
February 28, 2017 16:42
-
-
Save raphendyr/5b99d7b3b70f24c534bd128662833244 to your computer and use it in GitHub Desktop.
One more iteration of file delete script for slack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys, argparse, datetime, time, logging | |
try: | |
import requests | |
except ImportError: | |
import json | |
try: | |
from urllib2 import urlopen | |
from urllib import urlencode | |
except ImportError: | |
from urllib.request import urlopen | |
from urllib.parse import urlencode | |
class requests: | |
"""Minimalistic requests implementation using buildins""" | |
class Response: | |
def __init__(self, data): | |
self.text = data | |
def json(self): | |
return json.loads(self.text) | |
def get(self, url, params): | |
response = urlopen(url + '?' + urlencode(params)) | |
return self.Response(response.read().decode('utf-8')) | |
requests = requests() | |
LIST_URL = 'https://slack.com/api/files.list' | |
DEL_URL = 'https://slack.com/api/files.delete' | |
ITEMS_PER_REQUEST = 100 | |
logger = logging.getLogger('slack_delete') | |
logger.setLevel(logging.WARNING) | |
logger.addHandler(logging.StreamHandler()) | |
def app(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-t', '--token', required=True, | |
help="Specifies the OAuth token used for authentication, created at (https://api.slack.com/docs/oauth-test-tokens)") | |
parser.add_argument('-d', '--days', type=int, default=None, | |
help="Delete files older than x days (optional)") | |
parser.add_argument('-S', '--snippets', action='store_true', | |
help="Also delete snippets") | |
parser.add_argument('-D', '--delete', action='store_true', | |
help="Really delete files") | |
parser.add_argument('-v', '--verbose', action='store_true', | |
help="Print deubg messages") | |
options = parser.parse_args() | |
if options.verbose: | |
logger.setLevel(logging.DEBUG) | |
try: | |
files = list_files(options) | |
delete_files(options, files) | |
except KeyboardInterrupt: | |
logger.warning("Abort") | |
sys.exit(1) | |
logger.info("Done") | |
def list_files(options): | |
logger.info("Fetching file list") | |
params = { | |
'token': options.token, | |
'count': ITEMS_PER_REQUEST, | |
} | |
if options.days: | |
when = datetime.datetime.utcnow() - datetime.timedelta(days=options.days) | |
params['ts_to'] = int(time.mktime(when.utctimetuple())) | |
files = [] | |
def handle_files(new_files): | |
files.extend([ | |
f for f in new_files | |
if options.snippets or f['mode'] != 'snippet' | |
]) | |
def get_data(): | |
response = requests.get(LIST_URL, params=params) | |
data = response.json() | |
if not data.get('ok', False): | |
logger.warning("Request to %s with %s failed: %s", LIST_URL, params, data) | |
return data | |
logger.info("List: first request") | |
data = get_data() | |
handle_files(data['files']) | |
for page in range(2, data['paging']['pages'] + 1): | |
params['page'] = page | |
logger.info("List: Request %d", page) | |
data = get_data() | |
handle_files(data['files']) | |
return files | |
def delete_files(options, files): | |
total = len(files) | |
fmt = "{} %{}d/{} %s: %s, %s, %s: %s".format("Deleting" if options.delete else "Listing", len(str(total)), total) | |
params = {'token': options.token} | |
logger.info("Deling %d files", total) | |
for i, f in enumerate(files): | |
d = datetime.datetime.utcfromtimestamp(f['timestamp']).isoformat() | |
logger.info(fmt, i+1, f['id'], f['mode'], f['mimetype'], d, f['name']) | |
if options.delete: | |
params['file'] = f['id'] | |
response = requests.get(DEL_URL, params=params) | |
data = response.json() | |
if not data.get('ok', False): | |
logger.warning("Request to %s with %s failed: %s", DEL_URL, params, data) | |
if __name__ == '__main__': | |
app() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Support python 2.7 and 3. If requests library is not presents, uses urllib.
Based on: