Snippets

Denis Nelubin Script to delete old files from Slack

Created by Denis Nelubin
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from urllib.parse import urlencode, urlparse, parse_qs
import webbrowser
import http.server
import socketserver
from datetime import datetime, timedelta
import requests


# Create and register your app in Slack: https://api.slack.com/apps
client_id = '1234567890.1234567890'
client_secret = '1234567890abcdef1234567890abcdef'
redirect_server_port = 9999
redirect_url = 'http://localhost:%s/slack/oauth/callback' % redirect_server_port    # must be registered in Slack


url_authorize = 'https://slack.com/oauth/authorize'
url_access = 'https://slack.com/api/oauth.access'
url_delete = 'https://slack.com/api/files.delete'
url_list = 'https://slack.com/api/files.list'


params = {
    'client_id': client_id,
    'scope': 'files:read files:write:user',
    'redirect_uri': redirect_url
}
webbrowser.open(url_authorize + '?' + urlencode(params))


code = None

class RedirectHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        global code
        code = parse_qs(urlparse(self.path).query)['code']
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(b'<p>Close this window. Processing continues in the command line.</p>')

httpd = socketserver.TCPServer(("", redirect_server_port), RedirectHandler)
httpd.handle_request()

if code is None:
    print('Code is not received')
    sys.exit(1)


params = {
    'client_id': client_id,
    'client_secret': client_secret,
    'code': code,
    'redirect_uri': redirect_url
}
r = requests.get(url_access, params=params)
token = r.json()['access_token']
print('token:', token)


before = datetime.now() - timedelta(days=30)
print('Deleting before', before)

params = {
    'token': token,
    'ts_to': int(before.timestamp()),
    'count': 500
}
r = requests.get(url_list, params=params)
file_list = r.json()['files']
print('files total:', r.json()["paging"]["total"])


params = {
    'token': token,
    'file': ''
}
for file in file_list:
    params['file'] = file['id']
    r = requests.get(url_delete, params=params)
    print(r.json())


print('all')

Comments (0)