How to delete all old files in Slack with one command

The free plan of Slack has some limitations. One is the disk space. You have 5Gb of storage. When you reach the limit, you have to delete each file individually. I will use a script to delete all the files older than 2 months.

First I need to create a Slack token (an alphanumeric string) to get access to delete the files. I access the URL and I click in the “Create token” button.

I get the token

Then I use this PHP script to delete all the files older than 2 months. You need PHP on one machine.

#!/usr/bin/env php

if (count($argv)<2) {
	echo $argv[0] . ' <token> <until>' . PHP_EOL;
	echo 'Example: ' . $argv[0] . ' abcd-12345678-123456789-12345 \'-3 months\'' . PHP_EOL;

$token = $argv[1];
$timestamp = isset($argv[2]) ? strtotime($argv[2]) : null;

function slack($function, $options = []) {
	global $token;
	$response = file_get_contents('' . $function . '?' . http_build_query(array_merge(['token' => $token],$options)));
	return json_decode($response, true);

$files = slack('files.list', ['ts_to' => $timestamp]);
foreach ($files['files'] as $file) {
	$response = slack('files.delete', ['file' => $file['id']]);
	echo 'file ' . $file['id'] . ' deleted: ' . $file['permalink'] . PHP_EOL; 

I save this script to the delete-from-slack.php file.

To execute the script, I pass the token and the date until I want to delete the files:

$ php delete-from-slack.php xoxp-1111111111-1321232121-343490803926-6dd2352423bb48aasfasdfssd91c942 '-2 months'

Leave a Reply

Your email address will not be published. Required fields are marked *