Skip to content

Instantly share code, notes, and snippets.

@jjanusch
Created August 28, 2015 16:26
Show Gist options
  • Save jjanusch/f8854a13fbee1de6530f to your computer and use it in GitHub Desktop.
Save jjanusch/f8854a13fbee1de6530f to your computer and use it in GitHub Desktop.
A simple PHP script that uses the Slack API to automatically delete old files and outputs all errors it encounters.
<?php
// https://api.slack.com/methods/files.list
const SLACK_API_FILES_LIST = 'https://slack.com/api/files.list';
// https://api.slack.com/methods/files.delete
const SLACK_API_FILES_DELETE = 'https://slack.com/api/files.delete';
// retrieved from https://api.slack.com/web
// needs to be admin profile token
const API_TOKEN = '';
// this should be a string like "-1 month". Fed directly to strototime()
const OLDEST_ALLOWED_FILE = '-1 month';
// set timezone to UTC to prevent warnings and to put request in sync with Slack API
date_default_timezone_set('UTC');
$filesDeleted = 0;
while (true) {
$files = getFiles();
try {
output(sprintf('Found %s files to delete', @count($files['files'])));
if ($files['files']) {
foreach ($files['files'] as $file) {
deleteFile($file['id']);
$filesDeleted++;
}
} else {
break;
}
} catch (\Exception $ex) {
output($ex->getMessage());
}
}
output(sprintf('Deleted %s files', $filesDeleted));
function output($message) {
echo sprintf('[%s] %s %s', date('c'), $message, PHP_EOL);
}
function getFiles() {
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, sprintf('%s?token=%s&ts_to=%s', SLACK_API_FILES_LIST, API_TOKEN, strtotime(OLDEST_ALLOWED_FILE)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
if ($result === false) {
output(sprintf('Curl error (%s): %s', SLACK_API_FILES_LIST, curl_error($curl)));
die();
}
curl_close ($curl);
$result = json_decode($result, true);
if (@$result['ok'] === false) {
output(sprintf('[%s] API Error: %s', SLACK_API_FILES_LIST, $result['error']));
die();
}
return $result;
}
function deleteFile($id) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, SLACK_API_FILES_DELETE);
curl_setopt($curl, CURLOPT_POST, 2);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, sprintf('token=%s&file=%s', API_TOKEN, $id));
$result = curl_exec ($curl);
if ($result === false) {
output(sprintf('Curl error (%s): %s', SLACK_API_FILES_DELETE, curl_error($curl)));
die();
}
curl_close ($curl);
$result = json_decode($result, true);
if (@$result['ok'] === false) {
output(sprintf('[%s] API Error: %s', SLACK_API_FILES_DELETE, $result['error']));
die();
}
return $reuslt;
}
@k7y6t5
Copy link

k7y6t5 commented Jun 15, 2016

Typo on line 92 -> return $reuslt

Thank you for this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment