Skip to content

Instantly share code, notes, and snippets.

@johnboxall
Last active February 2, 2017 06:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnboxall/a1a91fe4531f5f7559e909067d17c82f to your computer and use it in GitHub Desktop.
Save johnboxall/a1a91fe4531f5f7559e909067d17c82f to your computer and use it in GitHub Desktop.
Archive Slack channels with no messages in the last three months.
// Archive channels with no new messages in the last two months.
// Usage: npm install slack async
// SLACK_TOKEN=XYZ node slack-cleanup.js
// Get your Slack Token: https://api.slack.com/docs/oauth-test-tokens
"use strict"
const readline = require('readline')
const slack = require('slack')
const async = require('async')
const token = process.env.SLACK_TOKEN
// 2 months
const oldest = ((new Date(Date.now() - (1000 * 60 * 60 * 24 * 30 * 2))).valueOf() / 1000)
const max = 16
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
slack.channels.list({token}, (err, data) => {
if (err) throw err
let toArchive = []
async.eachLimit(data.channels.filter((c) => !c.is_archived), max, (channel, callback) => {
// Has there been a message in the channel since `oldest`?
let options = {
token,
channel: channel.id,
oldest,
count: 1
}
slack.channels.history(options, (err, data) => {
if (err) return callback(err)
if (!data.messages.length) toArchive.push(channel)
return callback(null)
})
}, (err) => {
if (err) throw err
let confirm = `Found ${toArchive.length} channels with no messages:\n\n`
+ toArchive.map(c => c.name).sort().join('\n')
+ "\n\nType 'Yes' to archive the channels: "
rl.question(confirm, (answer) => {
rl.close()
if (answer.toLowerCase() != 'yes') return
async.eachLimit(toArchive, max, (channel, callback) => {
let options = {token, channel: channel.id}
slack.channels.archive(options, (err, data) => {
// You can get a bunch of errors here ...
// https://api.slack.com/methods/channels.archive
// Most of them probably don't matter.
if (err) console.error(`🚫 ${channel.name} ${err}`)
return callback(null)
})
}, (err) => {
if (err) throw err
console.log(`👉 Done!`)
})
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment