Skip to content

Instantly share code, notes, and snippets.

@claytongulick
Last active May 24, 2018 06:18
Show Gist options
  • Save claytongulick/bb7042c8d8a92148b12fc996b0d2fb21 to your computer and use it in GitHub Desktop.
Save claytongulick/bb7042c8d8a92148b12fc996b0d2fb21 to your computer and use it in GitHub Desktop.
Delete all messages from a specific user on a slack channel
//this grabs 1000 messages at a time from the history of a specific channel
//it spins through each message and compares it with the user id
//if it matches, it'll delete the message.
//there's a throttle of 1 delete per second so you don't bump against rate limits
let Slack = require('slack');
let API_KEY =''; //your API key - get it here: https://api.slack.com/custom-integrations/legacy-tokens
let CHANNEL_ID =''; //the channel id you want to delete from. This can be found in the url
let USER_ID = ''; //the user id for the user you want to delete. Easiest way to get this is to go to your profile and look in the url. Can also grab it from network traffic in debugger
let slack = new Slack(API_KEY);
function pause() {
return new Promise(
(resolve, reject) => {
setTimeout(()=>{
resolve();
}, 1000)
}
)
}
async function getHistory(latest, oldest) {
let params = {
channel: CHANNEL_ID,
count: 1000,
token: API_KEY,
inclusive: true
};
if(latest)
params.latest = latest;
if(oldest)
params.oldest = oldest;
console.log(`getting history chunk between ${oldest} and ${latest}`);
let history = await slack.channels.history(params);
if(history.ok)
console.log('ok');
else {
console.log('error');
debugger;
}
if(!history.messages.length)
return history;
history.latest = history.messages[0].ts;
history.oldest = history.messages[history.messages.length - 1].ts;
return history;
}
async function cleanHistory(history) {
let messages = history.messages;
for(let i=0; i<messages.length; i++) {
let message = messages[i];
if (message.user != USER_ID)
continue;
console.log('deleting message: ' + message.ts + ' text: ' + message.text);
try {
let result = await slack.chat.delete({
channel: CHANNEL_ID,
ts: message.ts,
token: API_KEY
});
if (result.ok)
console.log('success');
else {
console.log('failed')
debugger;
}
}
catch (e) {
console.error(e);
}
await pause();
}
}
(async ()=>{
let history = await getHistory();
while(true) {
await cleanHistory(history);
history = await getHistory(history.oldest);
if(!history.has_more)
return;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment