Skip to content

Instantly share code, notes, and snippets.

@nicolasbrugneaux
Last active October 18, 2017 13:45
Show Gist options
  • Save nicolasbrugneaux/811eb5140cc32107a73e02fb18938578 to your computer and use it in GitHub Desktop.
Save nicolasbrugneaux/811eb5140cc32107a73e02fb18938578 to your computer and use it in GitHub Desktop.
const fetch = require('node-fetch');
const API_URL = 'https://slack.com/api/';
const TOKEN = '?token=' + 'redacted';
const DEFAULT_COUNT = 100; // as per slack's doc
const PAST_THRESHHOLD = new Date();
PAST_THRESHHOLD.setHours(-120 * 24, 0, 0, 0);
const IGNORED_CHANNELS = [
'deathwatch',
];
function getFilesPage(page=1) {
return fetch(
API_URL + 'files.list' +
TOKEN +
'&page=' + page +
'&ts_to=' + (PAST_THRESHHOLD.getTime() / 1000).toFixed(0)
)
.then(x => x.json())
}
function deleteFile(file) {
console.warn('deleting', file.id, file.name);
return fetch(
API_URL + 'files.delete' +
TOKEN +
'&file=' + file.id,
{ method: 'POST' }
)
.then(x => x.json())
.then(x => x.ok);
}
async function main() {
const pageCount = await getFilesPage().then(x => x.paging.pages);
const files = [];
for (let i = 1; i < pageCount + 1; i++) {
const _files = await getFilesPage(i).then(x => x.files);
files.push.apply(files, _files);
}
console.info(files.length, 'files found before', PAST_THRESHHOLD);
const ignoredChannels = (await getChannels())
.filter(x => IGNORED_CHANNELS.indexOf(x.name) > -1);
const filesToBeDeleted = files.filter(file =>
(!file.pinned_to || !file.pinned_to.length) &&
!file.channels.some(x => ignoredChannels.indexOf(x) > -1)
);
console.info(filesToBeDeleted.length, 'files to be deleted');
const oks = await Promise.all(filesToBeDeleted.map(deleteFile));
if (!oks.every(Boolean)) {
throw new Error('Some files couldn\'t be delete');
}
return oks;
}
async function getChannels() {
const channels = await fetch(API_URL + 'channels.list' + TOKEN)
.then(x => x.json())
.then(x => x.channels);
return channels;
}
main()
.then(oks => console.info(oks.length, 'files deleted') || process.exit(0))
.catch(e => console.error(e) || process.exit(1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment