Skip to content

Instantly share code, notes, and snippets.

@betaorbust
Created March 22, 2018 23:46
Show Gist options
  • Save betaorbust/9a164694d0bdf976f8010740bcefc1ae to your computer and use it in GitHub Desktop.
Save betaorbust/9a164694d0bdf976f8010740bcefc1ae to your computer and use it in GitHub Desktop.
Delete largest old Slack files
/**
* Deletes the largest `numToDelete` files older than `minAgeDays` on your slack.
* Can only do 1000 at a time because I didn't want to deal with pagination.
* YOU NEED TO BE AN ADMIN FOR THIS TO DELETE THINGS THAT YOU DIDN'T UPLOAD!
* @param {string} token A legacy slack token. Get yours at https://api.slack.com/custom-integrations/legacy-tokens
* @param {number} minAgeDays The number of days old a file can be to be deleted.
* @param {number} numToDelete The number of files to delete total.
*/
async function deleteOldLargeFiles(token, minAgeDays, numToDelete) {
// Slack does everything in seconds, apparently.
const earliestDate = Date.now() / 1000 - 60 * 60 * 24 * minAgeDays;
const listResponse = await fetch(`https://slack.com/api/files.list?token=${token}&count=1000&ts_to=${earliestDate}`);
const listData = await listResponse.json();
const files = listData.files.slice().sort((a, b) => b.size - a.size);
for (let index = 0; index < Math.min(numToDelete, files.length); index++) {
const response = await fetch(`https://slack.com/api/files.delete?token=${token}&file=${files[index].id}`);
const data = await response.json();
if (data.ok) {
console.log(`Deleted ${files[index].title}`);
} else {
console.error(`Deleting ${files[index].title} failed.\n${data.error}`);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment