Skip to content

Instantly share code, notes, and snippets.

@guicaulada
Created February 20, 2022 07:09
Show Gist options
  • Select an option

  • Save guicaulada/751616293ecd337a4cc6f0361be3bb51 to your computer and use it in GitHub Desktop.

Select an option

Save guicaulada/751616293ecd337a4cc6f0361be3bb51 to your computer and use it in GitHub Desktop.
Delete messages from users that left your server
async function clearMessages(server, channel, author, offset=0) {
const authToken = 'YOUR_DISCORD_TOKEN';
const headers = { 'Authorization': authToken, 'Content-Type': 'application/json' };
const baseURL = `https://discordapp.com/api/v6/channels`;
let searchURL = `https://discordapp.com/api/v6/guilds/${server}/messages/search?channel_id=${channel}&offset=${offset}&include_nsfw=true`;
let clock = 0;
let interval = 2000;
function delay(duration) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), duration);
});
}
const response = await fetch(searchURL, {headers});
const json = await response.json();
if (json.retry_after) return delay(json.retry_after).then(() => clearMessages(server, channel, author, offset));
const messages = [].concat.apply([], json.messages).filter(m => m.hit == true && m.author.id == author)
console.log("There are " + messages.length + " messages left to delete.");
console.log(messages, json, offset)
await messages.forEach(async function(item) {
if(item.hit == true && item.author.id == author) {
await delay(clock += interval);
await fetch(`${baseURL}/${item.channel_id}/messages/${item.id}`, { headers, method: 'DELETE' });
}
});
if (offset < json.total_results) {
delay(clock += interval).then(() => clearMessages(server, channel, author, offset+json.messages.length));
} else {
console.log("Finished deleting messages")
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment