Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delete all messages in a Discord channel
(function(){
// Paste your token between the quotes :
var authToken = '________________________________________'
// https://github.com/yanatan16/nanoajax
!function(t,e){function n(t){return t&&e.XDomainRequest&&!/MSIE 1/.test(navigator.userAgent)?new XDomainRequest:e.XMLHttpRequest?new XMLHttpRequest:void 0}function o(t,e,n){t[e]=t[e]||n}var r=["responseType","withCredentials","timeout","onprogress"];t.ajax=function(t,a){function s(t,e){return function(){c||(a(void 0===f.status?t:f.status,0===f.status?"Error":f.response||f.responseText||e,f),c=!0)}}var u=t.headers||{},i=t.body,d=t.method||(i?"POST":"GET"),c=!1,f=n(t.cors);f.open(d,t.url,!0);var l=f.onload=s(200);f.onreadystatechange=function(){4===f.readyState&&l()},f.onerror=s(null,"Error"),f.ontimeout=s(null,"Timeout"),f.onabort=s(null,"Abort"),i&&(o(u,"X-Requested-With","XMLHttpRequest"),e.FormData&&i instanceof e.FormData||o(u,"Content-Type","application/x-www-form-urlencoded"));for(var p,m=0,v=r.length;v>m;m++)p=r[m],void 0!==t[p]&&(f[p]=t[p]);for(var p in u)f.setRequestHeader(p,u[p]);return f.send(i),f},e.nanoajax=t}({},function(){return this}());
var regexReactId = /\$[0-9]+/g
var ids = $$('[data-reactid*=":$"].message-text').map(function getMessageId(el) {
var reactid = el.getAttribute('data-reactid')
var match = reactid.match(regexReactId)
var id = match.pop().substr(1)
return id
}).filter(function(id){
return !!id
})
var channel = window.location.href.split('/').pop()
var base_url = 'https://discordapp.com/api/channels/' + channel + '/messages/'
var deleteLoop = function(){
if (! ids.length) { return }
var id = ids.pop()
nanoajax.ajax({
url: base_url + id,
method: 'DELETE',
headers: {
authorization: authToken
}
}, function(){
setTimeout(deleteLoop, 500)
})
}
deleteLoop()
}())

Delete all messages in a Discord channel

You have to know how to use your browser developer tools to use this thechnique.

1. Open your channel

The URL must be like https://discordapp.com/channels/XXXXXXX and not https://discordapp.com/channels/XXXXXXXXX/YYYYYYYY. If so, change it manually. Once on the right page, you must not reload or navigate.

2. Get your authorization token

  • Open the dev tools (F12), open the Network tab. (You should clear all requests for better readability if you see some.)
  • Delete one message manually. In the request log, you will see a request with a DELETE method.
  • Click on the request to open the details, and on the Headers tab, copy the 'authorization' thoken. It's a long text with dots like MTX5MzQ1MjAyMjU0NjA2MzM2.ROFLMAO.UvqZqBMXLpDuOY3Z456J3JRIfbk.

3. Get the script

Edit the javascript code from this tutorial in a text editor.

Find the line starting with with var authToken = and paste the token. Pay attention to the quotes. The code should read like this :

// Paste your token between the quotes :
var authToken = 'MTX5MzQ1MjAyMjU0NjA2MzM2.ROFLMAO.UvqZqBMXLpDuOY3Z456J3JRIfbk'

4. Launch

This script will only delete the messages that are visible. So, if you want to delete more messages, you should scroll top to show more of them before launch. If you do not have the permissions to delete some messages, the script should still work with yours (not tested).

Copy the full code that you have edited, paste it into the browser javascript console and watch your messages being deleted.

@isama92

This comment has been minimized.

Copy link

isama92 commented Jun 2, 2016

Doesn't work to me 😫
And, probably it's normal, but I'll say it just in case, the output is "undefined".
Did they update something and it doesn't work anymore?

@Cringely

This comment has been minimized.

Copy link

Cringely commented Jun 4, 2016

Ditto, one or more of the variables is returning as undefined.

@niahoo

This comment has been minimized.

Copy link
Owner Author

niahoo commented Jun 15, 2016

hi @isama92 and @Cringely, this script parses the HTML but they HTML structure seems to have changed.

I need a new way to parse the messages ids.

@grand-lotus-iroh

This comment has been minimized.

Copy link

grand-lotus-iroh commented Sep 8, 2016

Does this still work? When I try in Chrome / FF I get undefined... hmm... DARN! I want to love this SCRIPT!!!

@chucktheviking

This comment has been minimized.

Copy link

chucktheviking commented Oct 18, 2016

@niahoo have you made any progress on updating this? I'd really love to use it.

@jchv

This comment has been minimized.

Copy link

jchv commented Nov 6, 2016

@chucktheviking I wanted something like this, so I wrote my own. This deletes the last 100 messages of the current chat. Unlike the script above, it does not require you to grab your auth token, and it does not matter what messages are on the screen - it will plainly and simply delete 100 messages of whatever channel you're viewing.

;(function(){
	const authToken = JSON.parse(localStorage.token);
	const channel = window.location.href.split('/').pop();
	const baseURL = `https://discordapp.com/api/channels/${channel}/messages`;
	const headers = {"Authorization": authToken };

	let clock = 0;
        let interval = 500;

	function delay(duration) {
		return new Promise((resolve, reject) => {
			setTimeout(() => resolve(), duration);
		});
	}

	fetch(baseURL + '?limit=100', {headers})
		.then(resp => resp.json())
		.then(messages => {
		return Promise.all(messages.map((message) => {
			return delay(clock += interval).then(() => fetch(`${baseURL}/${message.id}`, {headers, method: 'DELETE'}));
		}));
	}).then(() => console.log("Done!"));
}());

Just drop it in the console and you're good to go. Note that this requires a modern web browser, not unlike Discord itself. Latest Microsoft Edge, Chrome or Firefox should work. Only tested it in Chrome so far. If you get any 429s you can increase the interval a bit, but if you're deleting a ton, don't worry - the next run will catch any stuff left over from rate limiting.

@CarletonStuberg

This comment has been minimized.

Copy link

CarletonStuberg commented Nov 7, 2016

Thanks for that @johnwchadwick

I modified it slightly to delete all messages before a certain ID. Useful for private messages because your version gets stuck after 100 messages sent by the other person (constant 403s because it tries to delete the other person's messages).

Note this does run forever. I don't know very much JavaScript. 😄

var before = CHANGE_THIS_TO_LAST_MSG_ID;
clearMessages = function(){
	const authToken = JSON.parse(localStorage.token);
	const channel = window.location.href.split('/').pop();
	const baseURL = `https://discordapp.com/api/channels/${channel}/messages`;
	const headers = {"Authorization": authToken };

	let clock = 0;
	let interval = 500;

	function delay(duration) {
		return new Promise((resolve, reject) => {
			setTimeout(() => resolve(), duration);
		});
	}

	fetch(baseURL + '?before=' + before + '&limit=100', {headers})
		.then(resp => resp.json())
		.then(messages => {
		return Promise.all(messages.map((message) => {
			before = message.id;
			return delay(clock += interval).then(() => fetch(`${baseURL}/${message.id}`, {headers, method: 'DELETE'}));
		}));
	}).then(() => clearMessages());
}
clearMessages();
@kuromelo

This comment has been minimized.

Copy link

kuromelo commented Nov 21, 2016

var before = CHANGE_THIS_TO_LAST_MSG_ID; <<
Do you have an example on how i should write this? Specially a DM id?

@rdurham1007

This comment has been minimized.

Copy link

rdurham1007 commented Jan 9, 2017

They recently started deleting the "localStorage" variable so if you were using the method described by @johnwchadwick then you'll have to make sure your script runs early so you can access the variable before they delete it. I'm not sure how to access the storage once the variable has been deleted.

@believer-ufa

This comment has been minimized.

Copy link

believer-ufa commented Jan 14, 2017

Hello all. Discord was updated app and deleted localStorage variable from window object, so you need to get access token from developer console manually. Application tab => Local Storage => find token field and copy its content.

I modified last script by @IMcPwn to delete messages with more thoughtful level.

This script doing these things:

  1. It trying to delete message from one of users in current chat. If it dont can delete message from this user, he automatically will add this user in list of filtered users and dont trying to delete next messages from users in this list.
  2. It trying to load last 100 messages in chat that it can delete.
  3. It will begin loading from last message in chat history and automatically loading next messages.
  4. It detects ending of loading messages history and stopping working after it :)
var authToken = '________________________________________'
    
if (typeof(blockedAuthors) === 'undefined') {
    var blockedAuthors = []
}

clearMessages = function() {
    const channel = window.location.href.split('/').pop()
    const baseURL = `https://discordapp.com/api/channels/${channel}/messages`
    const headers = { Authorization: authToken }

    let clock = 0
    let interval = 500
    let beforeId = null
    let messagesStore = []

    function delay(duration) {
        return new Promise((resolve, reject) => {
            setTimeout(resolve, duration)
        })
    }
    
    function loadMessages() {
        
        let url = `${baseURL}?limit=100`
        
        if (beforeId) {
            url += `&before=${beforeId}`
        }
        
        return fetch(url, { headers })
    }
    
    function tryDeleteMessage(message) {
        if (blockedAuthors.indexOf(message.author.id) === -1) {
            
            console.log(`Deleting message from ${message.author.username} (${message.content.substring(0, 30)}...)`)
                        
            return fetch(`${baseURL}/${message.id}`, { headers, method: 'DELETE' })
        }
    }
    
    function filterMessages(message) {
        return blockedAuthors.indexOf(message.author.id) === -1
    }
    
    function onlyNotDeleted(message) {
        return message.deleted === false
    }
    
    loadMessages()
        .then(resp => resp.json())
        .then(messages => {
            if (messages === null || messages.length === 0) {
                console.log(`We loaded all messages in this chat`)
                
                return
            }

            beforeId = messages[messages.length-1].id
            
            messages.forEach(message => { message.deleted = false })
            
            messagesStore = messagesStore.concat(messages.filter(filterMessages))
                
            return Promise.all(messagesStore.filter(onlyNotDeleted).map(message => {
                return delay(clock += interval)
                    .then(() => tryDeleteMessage(message))
                    .then(resp => {
                        if (resp && resp.status === 204) {
                            message.deleted = true
                            return resp.text()
                        }
                    })
                    .then(result => {
                        if (result) {
                            result = JSON.parse(result)

                            if (result.code === 50003) {
                                
                                console.log(`Cannot delete messages from user ${message.author.username}, skiping it`)
                                
                                blockedAuthors.push(message.author.id)
                                
                                messagesStore = messagesStore.filter(filterMessages)
                            }
                        }
                    })
            }))
        })
        .then(function() {
            if (messagesStore.length !== 0 && messagesStore.length < 100) {
                clearMessages()
            } else {
                console.log(`Finished clearing cycle. You can run again this script if you want delete next 100 messages`)
            }
        })
}

clearMessages()

If you find some caveats, tell me about it.

@believer-ufa

This comment has been minimized.

Copy link

believer-ufa commented Jan 14, 2017

Sorry, small fixes in my above script:

var authToken = '_____________________________________'

if (typeof(blockedAuthors) === 'undefined') {
    var blockedAuthors = []
}

clearMessages = function() {
    const channel = window.location.href.split('/').pop()
    const baseURL = `https://discordapp.com/api/channels/${channel}/messages`
    const headers = { Authorization: authToken }

    let clock = 0
    let interval = 500
    let beforeId = null
    let messagesStore = []

    function delay(duration) {
        return new Promise((resolve, reject) => {
            setTimeout(resolve, duration)
        })
    }

    function loadMessages() {

        let url = `${baseURL}?limit=100`

        if (beforeId) {
            url += `&before=${beforeId}`
        }

        return fetch(url, { headers })
    }

    function tryDeleteMessage(message) {
        if (blockedAuthors.indexOf(message.author.id) === -1) {

            console.log(`Deleting message from ${message.author.username} (${message.content.substring(0, 30)}...)`)

            return fetch(`${baseURL}/${message.id}`, { headers, method: 'DELETE' })
        }
    }

    function filterMessages(message) {
        return blockedAuthors.indexOf(message.author.id) === -1
    }

    function onlyNotDeleted(message) {
        return message.deleted === false
    }

    loadMessages()
        .then(resp => resp.json())
        .then(messages => {
            if (messages === null || messages.length === 0) {
                console.log(`We loaded all messages in this chat`)

                return
            }

            beforeId = messages[messages.length-1].id

            messages.forEach(message => { message.deleted = false })

            messagesStore = messagesStore.concat(messages.filter(filterMessages))

            return Promise.all(messagesStore.filter(onlyNotDeleted).map(message => {
                return delay(clock += interval)
                    .then(() => tryDeleteMessage(message))
                    .then(resp => {
                        if (resp && resp.status === 204) {
                            message.deleted = true
                        } else if (resp && resp.status === 403) {
                            console.log(`Cannot delete messages from user ${message.author.username}, skiping it`)

                            blockedAuthors.push(message.author.id)

                            messagesStore = messagesStore.filter(filterMessages)
                        }
                    })
            }))
        })
        .then(function() {
            if (messagesStore.length !== 0 && messagesStore.length < 100) {
                clearMessages()
            } else {
                console.log(`Finished clearing cycle. You can run again this script if you want delete next 100 messages`)
            }
        })
}

clearMessages()  
@q4z1

This comment has been minimized.

Copy link

q4z1 commented Jan 15, 2017

@believer-ufa:

works perfect - thank you :)

@ghost

This comment has been minimized.

Copy link

ghost commented Jan 20, 2017

Hi !

All the code just above didn't work for me so I develop a new one that delete infinite number of messages.
Works fine on Google Chrome, 20/01/2017

• The channel id is the YYYYYYYYY part here :
https://discordapp.com/channels/XXXXXXXX/YYYYYYYYY

• And for the authorization key, all is explained just above ;)

// VARIABLES
var channelid = '_________________';
var authorization = '_____________________________________';

// FUNCTIONS
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function sleep(ms) {
	return new Promise(resolve => setTimeout(resolve, ms));
}

function deleteOneMessage(id) {
	var xhr = new XMLHttpRequest();
	xhr.open("DELETE", "https://discordapp.com/api/v6/channels/"+channelid+"/messages/"+id, true);
	xhr.setRequestHeader("authorization", authorization);
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			console.log("deleted: "+id+" "+xhr.status);
		}
	}
	xhr.send();
}

async function deleteAllMessages(ids) {
	for (var i=0; i<ids.length; i++) {
		deleteOneMessage(ids[i]);
		await sleep(200);
	}
	getId();
}

function getId() {
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://discordapp.com/api/v6/channels/"+channelid+"/messages?limit=100", true);
	xhr.setRequestHeader("authorization", authorization);
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
			var obj = JSON.parse(xhr.responseText);
			var size = Object.size(obj);
			
			var ids = new Array();
			for (var i=0; i<size; i++) {
				ids[i] = obj[i].id;
			}
			
			deleteAllMessages(ids);
		}
	}
	xhr.send();
}

getId();
@2Monster

This comment has been minimized.

Copy link

2Monster commented Jan 24, 2017

The scripts dont work
@oONitromeOo

@dannigoes

This comment has been minimized.

Copy link

dannigoes commented Feb 3, 2017

@oONitromeOo I love you, I needed this terribly bad and it's working on chrome like a charm. One year of messages to be deleted.

@ViscoPro

This comment has been minimized.

Copy link

ViscoPro commented Feb 16, 2017

@oONitromeOo that worked perfectly on chrome thank you.

@funnbot

This comment has been minimized.

Copy link

funnbot commented Feb 20, 2017

Yall realize that spamming API requests ain't a good idea right? This is how you get banned 101

B1nzy has ratelimited this comment

Btw.. There is in fact a bulk_delete endpoint which would allow you to delete up to 100 messages without recursion.

@CarletonStuberg

This comment has been minimized.

Copy link

CarletonStuberg commented Feb 22, 2017

If anyone wants an alternative way to get the token this currently works:

document.body.appendChild(document.createElement`iframe`).contentWindow.localStorage.token

So you can set:

var authorization = '_____________________________________';

to:

var authorization = document.body.appendChild(document.createElement`iframe`).contentWindow.localStorage.token.replace(/"/g, "");

This may change again in the future though.

Here's the current working script: https://gist.github.com/IMcPwn/0c838a6248772c6fea1339ddad503cce

@cynik6

This comment has been minimized.

Copy link

cynik6 commented Feb 22, 2017

Any chance to get this to work with private messages also?

@CarletonStuberg

This comment has been minimized.

Copy link

CarletonStuberg commented Feb 23, 2017

@cynik6 The link I posted in the comment above yours works in private messages as well as regular channels.

@ordubis

This comment has been minimized.

Copy link

ordubis commented Mar 11, 2017

@believer-ufa I took your first script, which worked well, and just threw in a function call as it left your main function, to then call a function that started the process in the first place.. So your beautiful script (thank you btw ♥) now with infinite message deletion thanks to my poor programming practices. (shoots self in foot)

var authToken = '______________________________'
    
if (typeof(blockedAuthors) === 'undefined') {
    var blockedAuthors = []
}

clearMessages = function() {
    const channel = window.location.href.split('/').pop()
    const baseURL = `https://discordapp.com/api/channels/${channel}/messages`
    const headers = { Authorization: authToken }

    let clock = 0
    let interval = 500
    let beforeId = null
    let messagesStore = []

    function delay(duration) {
        return new Promise((resolve, reject) => {
            setTimeout(resolve, duration)
        })
    }
    
    function loadMessages() {
        
        let url = `${baseURL}?limit=100`
        
        if (beforeId) {
            url += `&before=${beforeId}`
        }
        
        return fetch(url, { headers })
    }
    
    function tryDeleteMessage(message) {
        if (blockedAuthors.indexOf(message.author.id) === -1) {
            
            console.log(`Deleting message from ${message.author.username} (${message.content.substring(0, 30)}...)`)
                        
            return fetch(`${baseURL}/${message.id}`, { headers, method: 'DELETE' })
        }
    }
    
    function filterMessages(message) {
        return blockedAuthors.indexOf(message.author.id) === -1
    }
    
    function onlyNotDeleted(message) {
        return message.deleted === false
    }
    
    loadMessages()
        .then(resp => resp.json())
        .then(messages => {
            if (messages === null || messages.length === 0) {
                console.log(`We loaded all messages in this chat`)
                
                return
            }

            beforeId = messages[messages.length-1].id
            
            messages.forEach(message => { message.deleted = false })
            
            messagesStore = messagesStore.concat(messages.filter(filterMessages))
                
            return Promise.all(messagesStore.filter(onlyNotDeleted).map(message => {
                return delay(clock += interval)
                    .then(() => tryDeleteMessage(message))
                    .then(resp => {
                        if (resp && resp.status === 204) {
                            message.deleted = true
                            return resp.text()
                        }
                    })
                    .then(result => {
                        if (result) {
                            result = JSON.parse(result)

                            if (result.code === 50003) {
                                
                                console.log(`Cannot delete messages from user ${message.author.username}, skiping it`)
                                
                                blockedAuthors.push(message.author.id)
                                
                                messagesStore = messagesStore.filter(filterMessages)
                            }
                        }
                    })
            }))
        })
        .then(function() {
            if (messagesStore.length !== 0 && messagesStore.length < 100) {
                clearMessages()
            } else {
                console.log(`Finished clearing cycle. You can run again this script if you want delete next 100 messages`)
				neverEndingStory();
            }
        })
}

function neverEndingStory(){
clearMessages()
}

neverEndingStory()
@solidsneak

This comment has been minimized.

Copy link

solidsneak commented Mar 25, 2017

Used the modified version by oONitromeOo, thanks a lot.

@eslachance

This comment has been minimized.

Copy link

eslachance commented Mar 31, 2017

Fair warning: doing this under a user account is considered being a selfbot, and purging a channel in this manner, is going to actually risk getting you banned from your account on Discord for API Abuse.

It's understood that bots can no longer delete messages older than 2 weeks and that might be an issue for people who never bothered to lock their default #general channel and can't delete it. However, the best course of action is to wait until the purge endpoint exists which will completely clear a channel - that is an upcoming feature of the API which bots will be able to take advantage of.

So, to repeat, THIS MIGHT GET YOU BANNED FROM THE API AND DISCORD. DO NOT USE IT

@hmthatsweird

This comment has been minimized.

Copy link

hmthatsweird commented Apr 4, 2017

I have an issue with this when using in a direct message chat, it gets to 100 messages sent by the other user and gets hung up on that indefinitely. Any help on getting it to skip other user?

@BrutalCSEjziponken

This comment has been minimized.

Copy link

BrutalCSEjziponken commented May 24, 2017

How can I make this work for private messages? It stops like after a 100 or so. And if I start it all over it still stops after 100 messages of my friend.

@asoldier

This comment has been minimized.

Copy link

asoldier commented May 24, 2017

@oONitromeOo Thank you for that. Plugged it in and it ran no issues. Much appreciated.

@Vanndis

This comment has been minimized.

Copy link

Vanndis commented Jun 2, 2017

How do I use this in DM's ?

@hallowatcher

This comment has been minimized.

Copy link

hallowatcher commented Jun 6, 2017

@Vanndis for DM's it works the same way, just open up your chat in the browser and look at the URL, it will be something like https://discordapp.com/channels/@me/245971251928194701 where the trailing number is the channel ID you plug in the snippet.

@RayKoopa

This comment has been minimized.

Copy link

RayKoopa commented Jun 12, 2017

Did anyone actually get banned for doing this?
Used oONitromeOo's script and the trailing DM channel ID behind the @me/ part, worked fine.

@rekane88

This comment has been minimized.

Copy link

rekane88 commented Jun 15, 2017

Does this still work?

@ghost

This comment has been minimized.

Copy link

ghost commented Jun 18, 2017

Yep, my script is still working on Chrome, 18 Jun 2017 ;)
And i never get banned for using it

@marianpavel

This comment has been minimized.

Copy link

marianpavel commented Jun 21, 2017

This doesn't work

@ProxyNeko

This comment has been minimized.

Copy link

ProxyNeko commented Jun 25, 2017

Is there a way to only remove a certain users messages? Rather than all users chat I only want to remove the one users messages

@elevenchars

This comment has been minimized.

Copy link

elevenchars commented Jul 16, 2017

@ProxyNeko you could modify my script to accomplish this, it works very similarly to this one. https://github.com/elevenchars/discorddelete/

@Teryxeon

This comment has been minimized.

Copy link

Teryxeon commented Jul 23, 2017

This comes up when i try it: 315886931110264832:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

Its the channel id and i dont know what to do, can someone edit the script so it works?

var authToken = '"MjEyNDgzMTU5NjU5MzgwNzM5.DEDaLw.8DjkQp4G1OHWPvZs4dWK7YgnkXw"'

if (typeof(blockedAuthors) === 'undefined') {
var blockedAuthors = []
}

clearMessages = function() {
const channel = window.location.href.split('/').pop()
const baseURL = https://discordapp.com/channels/315886931110264832/315886931110264832
const headers = { Authorization: authToken }

let clock = 0
let interval = 500
let beforeId = null
let messagesStore = []

function delay(duration) {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, duration)
    })
}

function loadMessages() {
    
    let url = `${baseURL}?limit=100`
    
    if (beforeId) {
        url += `&before=${beforeId}`
    }
    
    return fetch(url, { headers })
}

function tryDeleteMessage(message) {
    if (blockedAuthors.indexOf(message.author.id) === -1) {
        
        console.log(`Deleting message from ${message.author.username} (${message.content.substring(0, 30)}...)`)
                    
        return fetch(`${baseURL}/${message.id}`, { headers, method: 'DELETE' })
    }
}

function filterMessages(message) {
    return blockedAuthors.indexOf(message.author.id) === -1
}

function onlyNotDeleted(message) {
    return message.deleted === false
}

loadMessages()
    .then(resp => resp.json())
    .then(messages => {
        if (messages === null || messages.length === 0) {
            console.log(`We loaded all messages in this chat`)
            
            return
        }

        beforeId = messages[messages.length-1].id
        
        messages.forEach(message => { message.deleted = false })
        
        messagesStore = messagesStore.concat(messages.filter(filterMessages))
            
        return Promise.all(messagesStore.filter(onlyNotDeleted).map(message => {
            return delay(clock += interval)
                .then(() => tryDeleteMessage(message))
                .then(resp => {
                    if (resp && resp.status === 204) {
                        message.deleted = true
                        return resp.text()
                    }
                })
                .then(result => {
                    if (result) {
                        result = JSON.parse(result)

                        if (result.code === 50003) {
                            
                            console.log(`Cannot delete messages from user ${message.author.username}, skiping it`)
                            
                            blockedAuthors.push(message.author.id)
                            
                            messagesStore = messagesStore.filter(filterMessages)
                        }
                    }
                })
        }))
    })
    .then(function() {
        if (messagesStore.length !== 0 && messagesStore.length < 100) {
            clearMessages()
        } else {
            console.log(`Finished clearing cycle. You can run again this script if you want delete next 100 messages`)
			neverEndingStory();
        }
    })

}

function neverEndingStory(){
clearMessages()
}

neverEndingStory()

@Raeras

This comment has been minimized.

Copy link

Raeras commented Aug 5, 2017

@oONitromeOo For DMs does this only clear out messages I have sent? And can the other person see they have been removed?

@russibc

This comment has been minimized.

Copy link

russibc commented Sep 10, 2017

I've tested @oONitromeOo script and it is working great (10 Sept 2017) in both Google Chrome and Mozilla Firefox (works on channels and private conversations, also). Thanks for that!

By the way: it does keep deleting messages 'till the end of the world, so it is kinda risky to get banned since it makes a lot of requests and tries to delete other people messages. 🤔 And, just 'cause I'm a lazy person, I followed the @IMcPwn great tip and changed the authorization var to get my token automatically every time I run it.

@sudosoft-net

This comment has been minimized.

Copy link

sudosoft-net commented Oct 5, 2017

This version will finish in a fraction of the time as the interval is set to 10ms. However it has also been set to run from the top of the chat, since if you are only trying to remove your own messages the other way does not work.

  • Scroll to the top of your chat and delete the very first message you sent.
  • Open your developer tools and go to the networking tab, click the bottom request that says DELETED:
  1. Copy the Authorization token and paste over AUTH+TOKEN.
  2. Copy the Message ID and paste over BEFORE+ID.
  3. Copy the Channel ID and paste over CHAN+ID.
  4. Click the Console tab, paste code and hit Enter.
  5. Your messages are being wiped.
  6. Smile.
var authToken = '________AUTH+TOKEN_________'
if (typeof(blockedAuthors) === 'undefined') {
    var blockedAuthors = []
}
let beforeId = null
clearMessages = function() {
    const channel = '________CHAN+ID_________'
    const baseURL = `https://discordapp.com/api/channels/${channel}/messages`
    const headers = { Authorization: authToken }
    let clock = 0
    let interval = 10
    if ( beforeId === null ) { beforeId = __________BEFORE+ID__________ }
    let messagesStore = []
    function delay(duration) {
        return new Promise((resolve, reject) => {
            setTimeout(resolve, duration)
        })
    }
    function loadMessages() {   
        let url = `${baseURL}?limit=100`
        if (beforeId) {
            url += `&after=${beforeId}`
        }
        return fetch(url, { headers })
    }
    function tryDeleteMessage(message) {
        if (blockedAuthors.indexOf(message.author.id) === -1) {       
            console.log(`Deleting message from ${message.author.username} (${message.content.substring(0, 30)}...)`)
            return fetch(`${baseURL}/${message.id}`, { headers, method: 'DELETE' })
        }
    }
    function filterMessages(message) {
        return blockedAuthors.indexOf(message.author.id) === -1
    }
    function onlyNotDeleted(message) {
        return message.deleted === false
    }
    loadMessages()
        .then(resp => resp.json())
        .then(messages => {
            if (messages === null || messages.length === 0) {
                console.log(`We loaded all messages in this chat`)           
                return
            }
            beforeId = messages[messages.length-1].id
            messages.forEach(message => { message.deleted = false })
            messagesStore = messagesStore.concat(messages.filter(filterMessages))
            return Promise.all(messagesStore.filter(onlyNotDeleted).map(message => {
                return delay(clock += interval)
                    .then(() => tryDeleteMessage(message))
                    .then(resp => {
                        if (resp && resp.status === 204) {
                            message.deleted = true
                            return resp.text()
                        }
                    })
                    .then(result => {
                        if (result) {
                            result = JSON.parse(result)
                            if (result.code === 50003) {
                                console.log(`Cannot delete messages from user ${message.author.username}, skiping it`)
                                blockedAuthors.push(message.author.id)
                                messagesStore = messagesStore.filter(filterMessages)
                            }
                        }
                    })
            }))
        })
        .then(function() {
            if (messagesStore.length !== 0 && messagesStore.length < 100) {
                clearMessages()
            } else {
                console.log(`Finished clearing cycle. You can run again this script if you want delete next 100 messages`)
				neverEndingStory();
            }
        })
}
function neverEndingStory(){
clearMessages()
}
neverEndingStory()
@rodrigograca31

This comment has been minimized.

Copy link

rodrigograca31 commented Oct 19, 2017

@antonhs30000

This is working for PM as of right now.... (literally!) just get your "token" and "before id"

var before = CHANGE_THIS_TO_LAST_MSG_ID;
clearMessages = function(){
	const authToken = "TOKEN HERE";
	const channel = window.location.href.split('/').pop();
	const baseURL = `https://discordapp.com/api/channels/${channel}/messages`;
	const headers = {"Authorization": authToken };

	let clock = 0;
	let interval = 500;

	function delay(duration) {
		return new Promise((resolve, reject) => {
			setTimeout(() => resolve(), duration);
		});
	}

	fetch(baseURL + '?before=' + before + '&limit=100', {headers})
		.then(resp => resp.json())
		.then(messages => {
		return Promise.all(messages.map((message) => {
			before = message.id;
			return delay(clock += interval).then(() => fetch(`${baseURL}/${message.id}`, {headers, method: 'DELETE'}));
		}));
	}).then(() => clearMessages());
}
clearMessages();

this is the script provided by @IMcPwn but changed it to not use localstorage since was removed....

@ghost

This comment has been minimized.

Copy link

ghost commented Oct 22, 2017

My code doesn't work anymore, because of Discord new rules.

https://vgy.me/J1LA7s.png

@DFNCTSC

This comment has been minimized.

Copy link

DFNCTSC commented Nov 2, 2017

@funnbot Bulk_delete is only for managing messages on a server you're admin/mod of, not deleting just your messages.

@asdiky

This comment has been minimized.

Copy link

asdiky commented Feb 1, 2018

It works fine for me, but now i have a little issue. i delete all messages, but i have more then 100 calls in a row now.. so script don't work as it might be =_= doing a lot of useless work. Can you help me? =)

@JosepMoney

This comment has been minimized.

Copy link

JosepMoney commented Mar 19, 2018

how to get chanel id or auth token? can you show me how to delete mass messages?

@pokepokey

This comment has been minimized.

Copy link

pokepokey commented Mar 20, 2018

Is it feasible to reduce or delay the cycle of the code to reduce chances of getting banned?
I can run the code for a long period of time with no issues.
I'm doing this with the intention of deleting all messages in a channel (probably a few thousand).

@a-SynKronus

This comment has been minimized.

Copy link

a-SynKronus commented Mar 27, 2018

There's a much simpler way of doing this that involves using the "from:user#0000" syntax. The benefits of doing so are that you only traverse your own messages, rather than combing through heaps and heaps of old messages! :D

Here's what I whipped up:

clearMessages= function() {
	const author = "YOUR_ID_HERE";
	const authToken = "YOUR_TOKEN_HERE";
	const channel = window.location.href.split('/').pop();
	const headers = { 'Authorization': authToken, 'Content-Type': 'application/json' };

	let clock = 0;
	let interval = 500;
	function delay(duration) {
		return new Promise((resolve, reject) => {
			setTimeout(() => resolve(), duration);
		});
	}

	fetch(`https://discordapp.com/api/v6/channels/${channel}/messages/search?author_id=${author}`, {headers})
		.then(response => response.json())
		.then(json => {
			Array.from(json.messages).map(message => {
				message.forEach(function(item) {
					if(item.hit == true) {
						delay(clock += interval).then(() => { fetch(`https://discordapp.com/api/v6/channels/${item.channel_id}/messages/${item.id}`, { headers, method: 'PATCH', body: JSON.stringify({'content': 'This comment has been overwritten.'}) }) });
						delay(clock += interval).then(() => { fetch(`https://discordapp.com/api/v6/channels/${item.channel_id}/messages/${item.id}`, { headers, method: 'DELETE' }) });
					}
				});
			});

			if (json.total_results > 0) { delay(clock += interval).then(() => { clearMessages(); }); }
		});
}
clearMessages();
@tazzrawr

This comment has been minimized.

Copy link

tazzrawr commented Mar 30, 2018

Hi does this work for Direct Messages? I don't wanna associate myself with this one person and wanted to delete all my messages from there.

@Lurkios

This comment has been minimized.

Copy link

Lurkios commented Mar 30, 2018

@a-SynKronus Using your script I get:
"Uncaught (in promise) TypeError: Cannot read property 'map' of undefined
at fetch.then.then.json (:19:17)"

@a-SynKronus

This comment has been minimized.

Copy link

a-SynKronus commented Mar 30, 2018

@Lurkios
I fixed it, it works extremely well now.

clearMessages= function() {
	const author = "YOUR_ID_HERE";
	const authToken = "YOUR_TOKEN_HERE";
	const channel = window.location.href.split('/').pop();
	const headers = { 'Authorization': authToken, 'Content-Type': 'application/json' };

	let clock = 0;
	let interval = 500;
	function delay(duration) {
		return new Promise((resolve, reject) => {
			setTimeout(() => resolve(), duration);
		});
	}

	fetch(`https://discordapp.com/api/v6/channels/${channel}/messages/search?author_id=${author}`, {headers})
		.then(response => response.json())
		.then(json => {
			Array.from(json.messages).map(message => {
				message.forEach(function(item) {
					if(item.hit == true) {
						delay(clock += interval).then(() => { fetch(`https://discordapp.com/api/v6/channels/${item.channel_id}/messages/${item.id}`, { headers, method: 'PATCH', body: JSON.stringify({'content': 'This comment has been overwritten.'}) }) });
						delay(clock += interval).then(() => { fetch(`https://discordapp.com/api/v6/channels/${item.channel_id}/messages/${item.id}`, { headers, method: 'DELETE' }) });
					}
				});
			});

			if (json.total_results > 0) { delay(clock += interval).then(() => { clearMessages(); }); }
		});
}
clearMessages();
@narcolept1c

This comment has been minimized.

Copy link

narcolept1c commented Apr 21, 2018

is there any update on the script?
i got this error:

Uncaught (in promise) TypeError: Cannot convert undefined or null to object
at Function.from (native)
at fetch.then.then.json (:18:10)

@kotorann

This comment has been minimized.

Copy link

kotorann commented Apr 24, 2018

rodrigograca31's code still works like a charm - I was clearing my own contributions to a DM.

I am soooo grateful.

@testingtesterrodger

This comment has been minimized.

Copy link

testingtesterrodger commented Apr 28, 2018

@a-SynKronus

I keep getting: "TypeError: items is undefined" when running your script. Any idea why?

@Chaos3120

This comment has been minimized.

Copy link

Chaos3120 commented Jun 1, 2018

can we get an update to this? for DM cleaning

@fishstic

This comment has been minimized.

Copy link

fishstic commented Jun 4, 2018

@a-SynKronus can you help us on the specific user id? I am getting the same Uncaught error as @narcolept1c

@Just4Discord

This comment has been minimized.

Copy link

Just4Discord commented Jun 15, 2018

Made an account just to say that a-SynKronus solution doesn't work, however rodrigograca31's did.

Reporting in from June 15th. Thank you, rodrigograca31 👍

@flxtrsh

This comment has been minimized.

Copy link

flxtrsh commented Jun 19, 2018

Hello;
I want to try out @rodrigograca31's script if @Just4Discord claims that it worked just 4days ago.
I just need some help getting the "before id" because i'm new to this. Can anyone help me out? :)

@smellyonionman

This comment has been minimized.

Copy link

smellyonionman commented Jun 27, 2018

@flxtrsh sure, I am finding this problem and solution for the first time. I don't like how hard Discord is making it to delete information. Seems awfully big-data to me, like they are hoping for a FB purchase lol.

[New on GitHub! View my edit history for all the dumb things I've said!]

To obtain the Before ID, click the vertical ellipsis "..." next to the reaction icon in the upper-right corner of a message. Then select "copy ID" from the list, and paste away.

If it stops working for a while, then it has timed out due to Discord rate limiting. This is one way they protect their service from DDoS-like behaviour. So just open your Network tab in Firebug / Inspector / Developer Tools, and look at a response header coded "429." This is how Apache servers say "fuck off for a while ok" and the retry-in header should tell you how many milliseconds to wait, often around 120 seconds in this case.

I'm glad to have all my server testing bot spam removed. Shame I couldn't just delete the channel without expiring all my links. Going to use a subdomain and just start 301'ing my invite links from now on. Lesson learned.

@orion-v

This comment has been minimized.

Copy link

orion-v commented Jul 1, 2018

@a-SynKronus @testingtesterrodger @narcolept1c @fishstic

Hello everyone. I posted an updated variation of the delete discord history script that deletes an user's history by using discords search API.
Here is the link. https://gist.github.com/orion-v/95cb48fa73808cdc5c589fe415cc65f1
Big thanks to niahoo, a-SynKronus and all the other users that have been working on variations of this script. Let's hope discord will provide an easier way to delete message history.

@TheOutride

This comment has been minimized.

Copy link

TheOutride commented Jan 21, 2019

I've updated Altoid1's version. This currently works, and as a little bonus tracks how many of your messages it has deleted.

https://github.com/TheOutride/Delete-Discord-Direct-Messages

Let me know if it works!

@victornpb

This comment has been minimized.

Copy link

victornpb commented Apr 8, 2019

My version https://gist.github.com/victornpb/135f5b346dea4decfc8f63ad7d9cc182
It logs progress and gives you an estimated time

@moon-203

This comment has been minimized.

Copy link

moon-203 commented Oct 28, 2019

Hey, I managed to delete all the messages I've sent in DM, but I was wondering if it is possible to delete the messages of the other as well?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.