Skip to content

Instantly share code, notes, and snippets.

@brunohq
Forked from firatkucuk/delete-slack-messages.js
Created August 28, 2017 11:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brunohq/7d39d2afebe2175a66093b5e816a6b6e to your computer and use it in GitHub Desktop.
Save brunohq/7d39d2afebe2175a66093b5e816a6b6e to your computer and use it in GitHub Desktop.
Deletes slack public/private channel messages.
var https = require('https');
// CONFIGURATION #######################################################################################################
var token = 'SLACK TOKEN';
var channel = 'CHANNEL ID';
var privateChannel = false;
var delay = 300; // delay between delete operations in millisecond
// GLOBALS #############################################################################################################
var channelApi = privateChannel ? 'groups' : 'channels';
var baseApiUrl = 'https://slack.com/api/';
var historyApiUrl = baseApiUrl + channelApi + '.history?token=' + token + '&count=1000&channel=' + channel;
var deleteApiUrl = baseApiUrl + 'chat.delete?token=' + token + '&channel=' + channel + '&ts='
var messages = [];
// ---------------------------------------------------------------------------------------------------------------------
function deleteMessage() {
if (messages.length == 0) {
return;
}
var ts = messages.shift();
https.get(deleteApiUrl + ts, function (res) {
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function(){
var response = JSON.parse(body);
if (response.ok === true) {
console.log(ts + ' deleted!');
} else if (response.ok === false) {
messages.push(ts);
}
setTimeout(deleteMessage, delay);
});
}).on('error', function (e) {
console.log("Got an error: ", e);
});
}
// ---------------------------------------------------------------------------------------------------------------------
https.get(historyApiUrl, function(res) {
var body = '';
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
var response = JSON.parse(body);
for (var i = 0; i < response.messages.length; i++) {
messages.push(response.messages[i].ts);
}
deleteMessage();
});
}).on('error', function (e) {
console.log("Got an error: ", e);
});
@brunohq
Copy link
Author

brunohq commented Aug 28, 2017

First modify your token and channel id and run script:

node ./delete-channel-messages
You can learn your token from the following URL:

https://api.slack.com/custom-integrations/legacy-tokens

Also channel ID is written in the url:

https://mycompany.slack.com/messages/MYCHANNELID/

Script deletes 1000 messages in single run.

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