Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delete all messages in a Discord channel
// Turn on Developer Mode under User Settings > Appearance > Developer Mode (at the bottom)
// Then open the channel you wish to delete all of the messages (could be a DM) and click the three dots on the far right.
// Click "Copy ID" and paste that instead of LAST_MESSAGE_ID.
// Copy / paste the below script into the JavaScript console.
// If you're in a DM you will receive a 403 error for every message the other user sent (you don't have permission to delete their messages).
var before = 'LAST_MESSAGE_ID';
clearMessages = function(){
const authToken = document.body.appendChild(document.createElement`iframe`).contentWindow.localStorage.token.replace(/"/g, "");
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();
@CarletonStuberg

This comment has been minimized.

@ross-p

This comment has been minimized.

Copy link

commented Feb 28, 2017

Thanks, works great. :)

I'd make one change though:

if (ids.length)
    deleteAllMessages(ids);

Since currently it's recursively calling deleteAllMessages even when there are no messages to delete.

@axehead15

This comment has been minimized.

Copy link

commented Mar 8, 2017

It doesn't seem to be working for me. Every line has a 403 error. What would cause that? Is that when it tries to delete the other person's messages? This is in DM btw.

@nickstinger

This comment has been minimized.

Copy link

commented Mar 10, 2017

This works amazingly well. Now if only it were faster. ;)

@nickstinger

This comment has been minimized.

Copy link

commented Mar 10, 2017

@axehead15 Error 403 means "unauthorized." Yes, you probably don't have permission to delete the other person's message. However, if your use case is like mine, truncating the general chat, then this works great. Since I can't edit the "read" permissions on the general chat, I am converting it to a read-only welcome channel. This script made that possible.

@BrutalCSEjziponken

This comment has been minimized.

Copy link

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.

@Neodark7

This comment has been minimized.

Copy link

commented May 24, 2017

yep i have the same problem... only delete recent messages and then get stuck in a loop of 403 errors

@RayKoopa

This comment has been minimized.

Copy link

commented Jun 12, 2017

It only really works if both parties run it at the same time, because it seems to stop after ~100 message of any participant.

@CarletonStuberg

This comment has been minimized.

Copy link
Owner Author

commented Jun 26, 2017

@RayKoopa @Neodark7 @BrutalCSEjziponken @nickstinger should work for all messages now, just tested it myself.

@Gamingbuilder

This comment has been minimized.

Copy link

commented Jul 26, 2017

how do i open the javasscript console? & can you give me instructions for mozilla firefox?

@ItemME

This comment has been minimized.

Copy link

commented Aug 3, 2017

It's not working anymore, you're getting banned for too many requests I think (429) @IMcPwn

@thomasxd24

This comment has been minimized.

Copy link

commented Sep 20, 2017

yep 429

@CarletonStuberg

This comment has been minimized.

Copy link
Owner Author

commented Oct 10, 2017

It's still working for me @thomasxd24 @ItemME. I just deleted ~100 messages and I didn't get any errors. If you guys are deleting like 50,000 messages you will run into problems. 429 means "TOO MANY MESSAGES" (source: https://discordapp.com/developers/docs/topics/rate-limits) and you will not be able to delete any more messages until the rate limit expires.

For more information follow that link. Use the code responsibly and don't go over the rate limit.

@RayKoopa

This comment has been minimized.

Copy link

commented Feb 5, 2018

Still works fine to me. Only Discord acts up and sometimes doesn't hide messages even after you deleted them - be sure to refresh your window after it ran through!

@ThatOnePersonn

This comment has been minimized.

Copy link

commented Feb 6, 2018

Hey, could i get some help :) i have no idea how i set this up.. like, how do i get on the JavaScript console :D ?

@Plop

This comment has been minimized.

Copy link

commented Feb 17, 2018

I got this error : Uncaught (in promise) TypeError: messages.map is not a function
at fetch.then.then.messages (:26:31)
at

Can't make the script work...

@lizasaur

This comment has been minimized.

Copy link

commented Feb 26, 2018

I followed the instructions and it said undefined and nothing else happened :c

@kevinff

This comment has been minimized.

Copy link

commented Mar 2, 2018

Same as above:
TypeError: messages.map is not a function

Nevermind i think it happens if you used the search, close it first before running.

@JosepMoney

This comment has been minimized.

Copy link

commented Mar 19, 2018

Uncaught TypeError: Cannot read property 'localStorage' of null
at clearMessages (:9:91)
at :32:1
I get this kind of errors , do I have to have bots to able to run this script? How to solve this problem ? somebody please help me to delete mass messages .

@pokepokey

This comment has been minimized.

Copy link

commented Mar 20, 2018

Hey, how can I reduce the clock time for this command? I figure if I reduce the clock time enough I can run the command for a while without getting banned.
I'm doing this with the intention of deleting a couple thousand messages.

@LegitSoulja

This comment has been minimized.

Copy link

commented Mar 23, 2018

How is this valid? (document.createElement`iframe`)

@jjoujou

This comment has been minimized.

Copy link

commented Apr 22, 2018

it was deleting fine, now i'm trying to delete older messages keep getting this error:
Uncaught (in promise) TypeError: messages.map is not a function
at fetch.then.then.messages (:20:31)

@testttttttttttttttttttttttttttttttttttt

This comment has been minimized.

Copy link

commented Apr 28, 2018

i'm new to this, it worked great at first got to delete about a few thousand messages in dms and then suddenly it stopped working when i wanted to delete another dm. it keeps giving me this message "GET https://discordapp.com/api/channels/@me/messages?before=439919121476616224&limit=100 400 ()
uncaught (in promise) TypeError: messages.map is not a function
at fetch.then.then.messages (:26:31)"
any solutions?

@Terhiman

This comment has been minimized.

Copy link

commented Apr 29, 2018

Not working for me in a DM channel :(

@CarletonStuberg

This comment has been minimized.

Copy link
Owner Author

commented Apr 30, 2018

@LegitSoulja I just looked, and it still works... somehow.

@Terhiman try using the Discord desktop client

@TheKingRei

This comment has been minimized.

Copy link

commented May 1, 2018

Is there a way to delete messages after a call (in DM).
I USED THIS (Worked, but cannot delete after a call)
1
2

@meebolee

This comment has been minimized.

Copy link

commented May 19, 2018

I can only get this to work in direct messages rather than server channels

@Vermillionum

This comment has been minimized.

Copy link

commented Jun 18, 2018

Thank you so much <3
Very useful script right here.

@nivle

This comment has been minimized.

Copy link

commented Jun 28, 2018

I started by using ur code, but it seemed that it stoped working at some point, so I rewrote some parts of it,
It's not the best code but it works good. You have to fill in ur Id and the channel Id.
This deletes all ur messages on that channel, though it does that one by one, so it takes a while if you have like 10k messages. To find ur Id, there are a few ways, one way I find easy is to just open developer tools, go to elements tab and use the little arrow on top to select and inspect my profile img on the left bottom from which I can get my user Id from the link on the element. This works everywhere.

function sleep(milliseconds) {
    var start = new Date().getTime();
    while (true) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

function deleteMessages() {

    const authorId = "ENTER_HERE_UR_ID";
    const channelId = "ENTER_HERE_CHANNEL_ID";
    const deleteAfter = "search?author_id=" + authorId + "&min_id=000000000000000000";
    const baseURL = "https://discordapp.com/api/v6/channels/" + channelId + "/messages/";
    const authToken = document.body.appendChild(document.createElement("iframe"))
        .contentWindow.localStorage.token.replace(/"/g, "");

    const headers = {
        "Authorization": authToken
    };

    fetch(baseURL + deleteAfter, {
            headers
        })
        .then(resp => resp.json())
        .then(result => {
            console.log("There are " + result.total_results + " messages left to delete.");
            if (result.total_results == 0) {
                alert("All the messages got deleted. \nPlease refresh the page before pressing 'OK'.");
            }
            result.messages.forEach(function(element) {
                element.forEach(function(message) {
                    if (message.author.id == authorId && message.hit == true) {
                        console.log("Deleting message with Id #" + message.id);
                        console.log(baseURL + message.id);
                        fetch(baseURL + message.id, {
                            headers,
                            method: "DELETE"
                        });
                    }
                });
                sleep(500);
            });
        })
        .then(() => deleteMessages());
}

deleteMessages();
@orion-v

This comment has been minimized.

Copy link

commented Jul 1, 2018

@nivle what is &min_id=000000000000000000 for?

@orion-v

This comment has been minimized.

Copy link

commented Jul 5, 2018

Thanks for this script IMcPwn. It was very helpful!

I made a version that deletes all messages but of only one user.
Here is the link. https://gist.github.com/orion-v/95cb48fa73808cdc5c589fe415cc65f1

@Elaura1970

This comment has been minimized.

Copy link

commented Aug 6, 2018

I'm guessing a recent update to discord has broken this. I keep getting the error:
"VM399:17 Uncaught TypeError: Cannot read property 'replace' of undefined
at deleteMessages (:17:42)
at :49:1"

@etch286

This comment has been minimized.

Copy link

commented Aug 7, 2018

^same

@ghost

This comment has been minimized.

Copy link

commented Aug 8, 2018

The recent update seems to have relocated where the auth-token for your user-session is, which is causing the error.

I'll see if i can contribute anything.

@glhrmv

This comment has been minimized.

Copy link

commented Aug 8, 2018

There is still a way to find your auth token, but I have only managed to do it with a Tampermonkey userscript, so you can run it as soon as the page loads. Install it on your browser and add this script to it:

// ==UserScript==
// @name         Discord Token
// @namespace    http://tampermonkey.net/
// @version      0.0.1
// @description  try to take over the world!
// @author       Untitled-1#0001
// @match        https://discordapp.com/channels/*/*
// @grant        none
// @run-at       document-start
// @license      MIT License
// ==/UserScript==

(function() {
  "use strict";
  console.log("Discord Token:" + localStorage.getItem("token"));
})();

When this is enabled, it will log your authentication token in the console whenever you're on the web version of Discord, before any of Discord's generated logs. (You might need to refresh at least once for it to start working)

Then you should use @nivle's script (posted a few comments above this one) and replace the contents after const authToken = with your own token, between quotes, i.e., so that it's a JavaScript string.

@ghost

This comment has been minimized.

Copy link

commented Aug 8, 2018

@glhrmcv This is very good, but for people that use the application version, there is an even simpler way.

Simply launch discord, go into application > local storage > discordapp.com

Click in the frame and hit F5. This will reload Discord, then, as soon as it is avaliable, navigate this path again and you will see "token"

Tis' simple enough. From there, copy and paste the token into the script you are using, but the hard-coded path should work after the refresh, as the token appears to stay.

Enjoy!

@glhrmv

This comment has been minimized.

Copy link

commented Aug 9, 2018

Great, thank you for sharing this. 👍

@zombies8myheart

This comment has been minimized.

Copy link

commented Aug 17, 2018

Total newb here. I got the first script to work, months ago, and now that it doesn't work anymore I've tried the suggestions laid out above; however, I am stuck. I believe I am not doing it right. Can someone do a walk through or detailed instructions? I think I have my token, but when I copy and insert it I still get errors leading me to believe that maybe I am doing something wrong.

(I have tried the suggestions from @glhrmv and @nivle )

Thanks :)

@Stokrotka100

This comment has been minimized.

Copy link

commented Sep 3, 2018

Hey, I'm new here too. So the thing is, I couldn't find ''token'' after navigating that path again, but I used this method: https://discordhelp.net/discord-token . And I inserted it the message ID in the "ENTER_HERE_UR_ID". But it didn't work. I got the error

Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined
at fetch.then.then.result (:31:28) and
GET https://discordapp.com/api/v6/channels/ENTER_HERE_CHANNEL_ID/messages/search?author_id=... 400 ()

So yeah maybe I shouldn't have used that other method, or maybe I should have inserted my User ID? Also I want to delete my messages from a private convo, so I'm not sure what to put in the "ENTER_HERE_CHANNEL_ID".
I really hope someone would describe what to do in a more detailed way.
Thank you :)

@someone1233

This comment has been minimized.

Copy link

commented Sep 6, 2018

@nivle's code in the comment above currently works great! get your token using whatever method is current (this one works for now) and replace it into the snippet:

    const authorId = "ENTER_HERE_UR_ID";
    const channelId = "ENTER_HERE_CHANNEL_ID";
    const deleteAfter = "search?author_id=" + authorId + "&min_id=000000000000000000";
    const baseURL = "https://discordapp.com/api/v6/channels/" + channelId + "/messages/";
    const authToken = "ENTER_TOKEN_HERE";

get your user ID by right-clicking your avatar in any message and selecting "copy ID" and use that for "ENTER_HERE_UR_ID". the channel ID for DMs is the long number string after @me/ at the end of the URL in the web version of discord. 👍

I tried replacing the 000000000000000000 with "LAST_MESSAGE_ID" as per the original snippet but it didn't work so I just left it as-is.

Thanks a bunch to everyone who has contributed code & suggestions to make this functionality possible! ❤️ ❤️ ❤️

@crashcandy

This comment has been minimized.

Copy link

commented Sep 9, 2018

@nivle 's code worked for about 20 messages and then stopped. I get "There are XXX messages left to delete." but it is stuck on that one number. Is there a place I should be inputting the last message id?
I also appreciate all of the work that has been going on to make this code

@zombies8myheart

This comment has been minimized.

Copy link

commented Sep 16, 2018

Total newb here. I got the first script to work, months ago, and now that it doesn't work anymore I've tried the suggestions laid out above; however, I am stuck. I believe I am not doing it right. Can someone do a walk through or detailed instructions? I think I have my token, but when I copy and insert it I still get errors leading me to believe that maybe I am doing something wrong.

(I have tried the suggestions from @glhrmv and @nivle )

Thanks :)

As an update, I got Nivle's code to finally work, but just like Crashcandy it only deleted several messages and then stopped. Has anyone got it to work for them? Thanks. :)

@ecx86

This comment has been minimized.

Copy link

commented Sep 30, 2018

(shameless self-promotion)
If this script isn't working for you, try the one I use. https://gist.github.com/ecx86/a29eac843a8ecf97a22accb34ef60b88

@skrillex53

This comment has been minimized.

Copy link

commented Oct 4, 2018

(shameless self-promotion)
If this script isn't working for you, try the one I use. https://gist.github.com/ecx86/a29eac843a8ecf97a22accb34ef60b88

I don't understand the step 2, you can make a video? or frame by frame?

@ecx86

This comment has been minimized.

Copy link

commented Oct 5, 2018

@Skrillex I added instructions in a comment to my gist, check there.

@0x12e

This comment has been minimized.

Copy link

commented Nov 3, 2018

Python 3 implementation, if this doesn't work. Deletes messages from multiple channels in a row, but it also needs to run for a while if there are hundreds of thousands of messages.
https://github.com/0x12e/discorddelete

@GotEnouth

This comment has been minimized.

Copy link

commented Nov 30, 2018

This is just bad joke, right?
Wasted hours to get any working code, still not found. Great. I give up.

Its always the same with people and the reason why nothing is working. I bet everything that nobody of the code poster tried by her own. Copying any old stuff without even know what it does, give just the half of the instructions, evens in the comments you see "Its working... AFTER I corrected this and this" even that is just the half then. I tried several codes, several own mods (there are rows they cannot work, that even I see as non-coder, its missing information about what to do). I still got several different error messages every time I tried any of the hours ago now. I see here (and other posting-sites) people telling things they should know that isn't working, even at this time they posted. People who have any kind of clue are too lazy or selfish to post any corrections. Posting any other code what is exactly the same with the same errors. God... people are people, I have enough of it.

And about discord programmer: They are trying everything to avoid that people can do something against their interest (log everything, for example). Otherwise they would have included a normal function for it already in the program. So what? They changing every stuff even in her own code what is only possible to view by using the dev-mode. "Token" has rename to "fingerprint", and other such things, even in a few days cycle.

I'm wondering about the guys they saying "it works great! wow" - so what worked few days ago and not now? The same code what was posted years ago? You kidding me? So stop posting just the half-true of something. Other guys posting code without any instructions, what the hell... using nice variable names, double symbols, and other what confusing non-coder and wondering about that people have questions. So you learned a job or doing as hobby, what happened if you would be a surgeon?! I don't want to see the patients...

"If this doesn't work, try this... try this.. try this.." - what is neither working. Always the same...

I just can recommend to people who are interest in this and reading this comment:
Think about what to write in a discord-chat, avoid personal information and delete it instantly after the other got it - instantly. This is what I'm doing already, but even this is not really helping so much, the messages getting cached and saved at several places. It's just a little thing what you can do. Better than nothing.

And even more better than wasting time here by using any random code.
Bye people.

@throwawayaccount002

This comment has been minimized.

Copy link

commented Dec 1, 2018

This is just bad joke, right?
Wasted hours to get any working code, still not found. Great. I give up.

Its always the same with people and the reason why nothing is working. I bet everything that nobody of the code poster tried by her own. Copying any old stuff without even know what it does, give just the half of the instructions, evens in the comments you see "Its working... AFTER I corrected this and this" even that is just the half then. I tried several codes, several own mods (there are rows they cannot work, that even I see as non-coder, its missing information about what to do). I still got several different error messages every time I tried any of the hours ago now. I see here (and other posting-sites) people telling things they should know that isn't working, even at this time they posted. People who have any kind of clue are too lazy or selfish to post any corrections. Posting any other code what is exactly the same with the same errors. God... people are people, I have enough of it.

And about discord programmer: They are trying everything to avoid that people can do something against their interest (log everything, for example). Otherwise they would have included a normal function for it already in the program. So what? They changing every stuff even in her own code what is only possible to view by using the dev-mode. "Token" has rename to "fingerprint", and other such things, even in a few days cycle.

I'm wondering about the guys they saying "it works great! wow" - so what worked few days ago and not now? The same code what was posted years ago? You kidding me? So stop posting just the half-true of something. Other guys posting code without any instructions, what the hell... using nice variable names, double symbols, and other what confusing non-coder and wondering about that people have questions. So you learned a job or doing as hobby, what happened if you would be a surgeon?! I don't want to see the patients...

"If this doesn't work, try this... try this.. try this.." - what is neither working. Always the same...

I just can recommend to people who are interest in this and reading this comment:
Think about what to write in a discord-chat, avoid personal information and delete it instantly after the other got it - instantly. This is what I'm doing already, but even this is not really helping so much, the messages getting cached and saved at several places. It's just a little thing what you can do. Better than nothing.

And even more better than wasting time here by using any random code.
Bye people.

The script works, you need to adjust it a little though.

Just add the line: var authToken = "your token here"; and put your token where it's written "your token here". You can get it on Discord console, application, Local Storage, discordapp[dot]com and then scroll down to find it. If it's not there, just refresh with F5 and it will be there.

@Altoids1

This comment has been minimized.

Copy link

commented Dec 2, 2018

Here's a version I eventually was able to cook up for deleting your side of a DM, without any spam about 403's.

//Works as of 1st of Dec, 2018
var lastmsg = "Big ol' num" // Copy the ID of the newest message you want to be cleared
var youruser = "xxxBigTiddy2003xxx" // Your username.
clearMessages = function(){
	const authToken = "A long bit of letters, underscores, periods, whatever"
	// ^ The above is your token value, not fingerprint
	// To get it, open up your browser's dev stuff, go to Applications, and then open up local storage
	// when you refresh the page, a value for token will appear, but only for a few seconds.
	// You have to ninja a CTRL+C of that value so you can put it here.
	const channel = "18-digit num";
	// ^ This you can get from the URL that shows up in the browser version of discord; it's the ~18-digit number in it.
	
/*
MAKE SURE ALL OF THE IDS ARE GIVEN A STRINGS, NOT LITERAL NUMBERS!
OTHERWISE, JAVASCRIPT WILL ROUND THEM A LITTLE, CAUSING STUPID FUCKIN 404 ERRORS
*/
   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=" + lastmsg, {headers, method: 'GET'})// Fetch the message data from discord
		.then(resp => resp.json()) // Make it into a json
		.then(messages => { // Call that json "messages" and do this function with it as the parameter:
			if(typeof messages == "undefined")
			{
				console.log("Yeah, you fucked one of your IDs up, son.");
				throw new Error();
			}
			return Promise.all(messages.map(
			(message) => { // Call this function for all messages we got
				lastmsg = message.id
				if(message.author.username == youruser)
				{
					return delay(clock += interval).then(() => fetch(`${baseURL}/${message.id}`, {headers, method: 'DELETE'}));
				}
				else
				{
					//console.log("Found a message written by someone else!");
					return
				}
			}));
		}).then(() => clearMessages()); // And once we've deleted all the messages we can see, ask for more!
}
clearMessages();
@GotEnouth

This comment has been minimized.

Copy link

commented Dec 3, 2018

Here's a version I eventually was able to cook up for deleting your side of a DM, without any spam about 403's.

"Uncaught SyntaxError: Invalid or unexpected token"
I did exactly the instructions.
As I said, its always the same.

@GotEnouth

This comment has been minimized.

Copy link

commented Dec 3, 2018

God.. people.. I finally got it to working.

Important to know:
1. For first you need to logout all previous sessions, best way also renew your IP (it gave me another token then).
2. Then login via Webversion. (Not Android, not Desktop-App).
3. Click on UserChat you want to do with it, like you want to chat (In URL bar you have the number)
4. Open Dev-View: CTRL+SHIFT+i
5. For get the Message ID: Click the 3 dots "Copy ID"
6. Username is actually for real just your username: Bingo@1234 , so Bingo is your username.
7. Doing the Ninjathing (you can use F5 to refresh the page for faster grab, Click in the value field and CTRL+C). Inserting by CTRL+V.
Your token is something like this you see here in my example-preview (just to show you how the first part of the code looks like):

//Works as of 1st of Dec, 2018
var lastmsg = "994472198856332701" // Copy the ID of the newest message you want to be cleared
var youruser = "SuperIngo" // Your username.
clearMessages = function(){
	const authToken = "REE44RERTetsdfEFWEFWEF4.Dfdfefsfd._cFtretDFGDFG994"
	// ^ The above is your token value, not fingerprint
	// To get it, open up your browser's dev stuff, go to Applications, and then open up local storage
	// when you refresh the page, a value for token will appear, but only for a few seconds.
	// You have to ninja a CTRL+C of that value so you can put it here.
	const channel = "141272198812332701";
	// ^ This you can get from the URL that shows up in the browser version of discord; it's the ~18-digit number in it.
  1. Insert the WHOLE code in the console and hit enter:
//Works as of 3st of Dec, 2018 Contact me via PM if you have questions.
var lastmsg = "994472198856332701" // Copy the ID of the newest message you want to be cleared
var youruser = "SuperIngo" // Your username.
clearMessages = function(){
	const authToken = "REE44RERTetsdfEFWEFWEF4.Dfdfefsfd._cFtretDFGDFG994"
	// ^ The above is your token value, not fingerprint
	// To get it, open up your browser's dev stuff, go to Applications, and then open up local storage
	// when you refresh the page, a value for token will appear, but only for a few seconds.
	// You have to ninja a CTRL+C of that value so you can put it here.
	const channel = "141272198812332701";
	// ^ This you can get from the URL that shows up in the browser version of discord; it's the ~18-digit number in it.
	
/*
MAKE SURE ALL OF THE IDS ARE GIVEN A STRINGS, NOT LITERAL NUMBERS!
OTHERWISE, JAVASCRIPT WILL ROUND THEM A LITTLE, CAUSING STUPID FUCKIN 404 ERRORS
*/
   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=" + lastmsg, {headers, method: 'GET'})// Fetch the message data from discord
		.then(resp => resp.json()) // Make it into a json
		.then(messages => { // Call that json "messages" and do this function with it as the parameter:
			if(typeof messages == "undefined")
			{
				console.log("Yeah, you fucked one of your IDs up, son.");
				throw new Error();
			}
			return Promise.all(messages.map(
			(message) => { // Call this function for all messages we got
				lastmsg = message.id
				if(message.author.username == youruser)
				{
					return delay(clock += interval).then(() => fetch(`${baseURL}/${message.id}`, {headers, method: 'DELETE'}));
				}
				else
				{
					//console.log("Found a message written by someone else!");
					return
				}
			}));
		}).then(() => clearMessages()); // And once we've deleted all the messages we can see, ask for more!
}
clearMessages();

Its very slow, and you may need do it several times, but YES now its working.
(BTW the 404 Messages comes still, but I dont care, the function is working, thats the matter)

  1. The last message (you copied the ID from) you need to delete by your own, it seems.

Probably I will post the whole thing at my own space and updating if necessary.
So you see, you need to do all by your own or its end in wasting time as it was for me.
Contact me via PM if you have questions.

Seeya.

@GotEnouth

This comment has been minimized.

Copy link

commented Dec 3, 2018

Ahhb btw, before I forget, I'm sure some people are interest in this too.
To export your Chat-History first:

https://github.com/Tyrrrz/DiscordChatExporter

Still working today.

@Altoids1

This comment has been minimized.

Copy link

commented Dec 3, 2018

Also I want to note that I was logged into three different sessions when I got mine working, so being logged out is not necessary. I feel like that's this guy accidentally causing a syntax error and accidentally fixing it while doing something else, and then correlating the placebo to it being fixed again.

Also, the script worked in my desktop version, although I had to extract the channel ID manually from the browser version.

@GotEnouth

This comment has been minimized.

Copy link

commented Dec 3, 2018

so being logged out is not necessary

I'm just telling what I did to it working, you didn't read what I said about IP.

accidentally causing a syntax error and accidentally fixing

I feel... I mean - I'm sure this is the only truth, accidentally.

although I had to extract the channel ID manually from the browser version.

So what result in same.
You seems very smart...

btw, you want me to show you the 404 Errors? They still coming...
To not admit something and push reasons to "accidents", don't make it better, just saying.
As I said, next time, do it correct ("your" script) or don't do anything, please - its tilting.

Best regards,
"This guy"

@XHyperY

This comment has been minimized.

Copy link

commented Dec 6, 2018

I started by using ur code, but it seemed that it stoped working at some point, so I rewrote some parts of it,
It's not the best code but it works good. You have to fill in ur Id and the channel Id.
This deletes all ur messages on that channel, though it does that one by one, so it takes a while if you have like 10k messages. To find ur Id, there are a few ways, one way I find easy is to just open developer tools, go to elements tab and use the little arrow on top to select and inspect my profile img on the left bottom from which I can get my user Id from the link on the element. This works everywhere.

function sleep(milliseconds) {
    var start = new Date().getTime();
    while (true) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

function deleteMessages() {

    const authorId = "ENTER_HERE_UR_ID";
    const channelId = "ENTER_HERE_CHANNEL_ID";
    const deleteAfter = "search?author_id=" + authorId + "&min_id=000000000000000000";
    const baseURL = "https://discordapp.com/api/v6/channels/" + channelId + "/messages/";
    const authToken = document.body.appendChild(document.createElement("iframe"))
        .contentWindow.localStorage.token.replace(/"/g, "");

    const headers = {
        "Authorization": authToken
    };

    fetch(baseURL + deleteAfter, {
            headers
        })
        .then(resp => resp.json())
        .then(result => {
            console.log("There are " + result.total_results + " messages left to delete.");
            if (result.total_results == 0) {
                alert("All the messages got deleted. \nPlease refresh the page before pressing 'OK'.");
            }
            result.messages.forEach(function(element) {
                element.forEach(function(message) {
                    if (message.author.id == authorId && message.hit == true) {
                        console.log("Deleting message with Id #" + message.id);
                        console.log(baseURL + message.id);
                        fetch(baseURL + message.id, {
                            headers,
                            method: "DELETE"
                        });
                    }
                });
                sleep(500);
            });
        })
        .then(() => deleteMessages());
}

deleteMessages();

Excellent. Thank you for the code. It works great Dec 06 2018.

@DYAZ970

This comment has been minimized.

Copy link

commented Dec 6, 2018

can we speed up the interval to say 250? or does it need to be 500?

@Xval95

This comment has been minimized.

Copy link

commented Dec 11, 2018

I started by using ur code, but it seemed that it stoped working at some point, so I rewrote some parts of it,
It's not the best code but it works good. You have to fill in ur Id and the channel Id.
This deletes all ur messages on that channel, though it does that one by one, so it takes a while if you have like 10k messages. To find ur Id, there are a few ways, one way I find easy is to just open developer tools, go to elements tab and use the little arrow on top to select and inspect my profile img on the left bottom from which I can get my user Id from the link on the element. This works everywhere.

function sleep(milliseconds) {
    var start = new Date().getTime();
    while (true) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}

function deleteMessages() {

    const authorId = "ENTER_HERE_UR_ID";
    const channelId = "ENTER_HERE_CHANNEL_ID";
    const deleteAfter = "search?author_id=" + authorId + "&min_id=000000000000000000";
    const baseURL = "https://discordapp.com/api/v6/channels/" + channelId + "/messages/";
    const authToken = document.body.appendChild(document.createElement("iframe"))
        .contentWindow.localStorage.token.replace(/"/g, "");

    const headers = {
        "Authorization": authToken
    };

    fetch(baseURL + deleteAfter, {
            headers
        })
        .then(resp => resp.json())
        .then(result => {
            console.log("There are " + result.total_results + " messages left to delete.");
            if (result.total_results == 0) {
                alert("All the messages got deleted. \nPlease refresh the page before pressing 'OK'.");
            }
            result.messages.forEach(function(element) {
                element.forEach(function(message) {
                    if (message.author.id == authorId && message.hit == true) {
                        console.log("Deleting message with Id #" + message.id);
                        console.log(baseURL + message.id);
                        fetch(baseURL + message.id, {
                            headers,
                            method: "DELETE"
                        });
                    }
                });
                sleep(500);
            });
        })
        .then(() => deleteMessages());
}

deleteMessages();

Excellent. Thank you for the code. It works great Dec 06 2018.

I copy and pasted this into my console but it said: "Uncaught TypeError: Cannot read property 'replace' of undefined
at deleteMessages (:17:42)
at :49:1"

Can someone help?

@kmobx

This comment has been minimized.

Copy link

commented Dec 11, 2018

—i get the following error from mozilla:

TypeError: document.body.appendChild(...).contentWindow.localStorage.token is undefined[Learn More]

—i get the following error from chrome:

Uncaught TypeError: Cannot read property 'replace' of undefined
at clearMessages (:3:110)
at :26:1

---- help?

@cphilpot

This comment has been minimized.

Copy link

commented Dec 12, 2018

@GotEnouth I'm getting the following error from Chrome, any ideas?

VM839:37 Uncaught (in promise) TypeError: messages.map is not a function
at fetch.then.then.messages (:37:32)

Thanks

@GotEnouth

This comment has been minimized.

Copy link

commented Dec 21, 2018

@cphilpot
Sorry, wasn't looking here for long time.
Sometimes I got this error by mixed up the replace-fields.
Lastmessage <=> Channel
I guess it comes when Channel or Lastmessage is not found.

Will take a further look, later.

General tip:
Use Notepadd++, insert the code, change view to java-script, replace the token and save it as a document. (trusty place, not public, the token is important as your password is.) So it is much more easier to replace the fields. Copy, Click, Paste.
Mostly i go:

  1. Loggin via Chrome Portable, open dev mode (ctrl + shift + i), open the notepad (see above, prepared)
  2. Choose Channel (like you would chat with someone), double click in url-bar (the number is marked), ctrl+c (copy), go to the code, double click on the channel field, ctrl+v (paste) - its replaced
  3. In chat, click my last message (3 dots), choose Copy ID, go notepad double click in lastmessage-field ctrl+v
  4. Copy whole by ctrl + a, ctrl +c, discord dev dock, click on console, in field, ctrl+v, return

Function is running. Sometimes it give 404 errors or other, but isn't matter.
After a while you need to do again, and again (just ctrl + v, return), but then anytime its cleared completely.
This is how i did for my own, it can take a long time...

(Maybe I will write a full tutorial, this 1-4 step thing i just wrote spontaneous here...)

best regards

@cphilpot

This comment has been minimized.

Copy link

commented Dec 31, 2018

@GotEnouth Thanks for this, it was me not reading your guide properly regarding the "token"

I can confirm this is still working.

Thanks 👍

@BigBelts

This comment has been minimized.

Copy link

commented Jan 2, 2019

does this still work? and does it work on mac?

@WizardsofBoz

This comment has been minimized.

Copy link

commented Jan 8, 2019

I've run @nivle's code and replaced

const authToken = document.body.appendChild(document.createElement("iframe")).contentWindow.localStorage.token.replace(/"/g, "");

with

const authToken = "YOUR_AUTH_TOKEN";

and it brings up the error:

Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined at fetch.then.then.result (<anonymous>:31:28)

I've read back and I don't believe anyone has addressed this issue 🤔

@TheOutride

This comment has been minimized.

Copy link

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!

@Altoids1

This comment has been minimized.

Copy link

commented Jan 24, 2019

Thanks for the tons of credit & al, @TheOutride . Really appreciate it.

I would recommend y'all moving to Outride's repo if you have issues. This gist is starting to get a bit cramped.

@ifeyatta

This comment has been minimized.

Copy link

commented Feb 2, 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!

Doesn't work error 404

@ifeyatta

This comment has been minimized.

Copy link

commented Feb 3, 2019

After trying more i don't get 404 but when i click enter to start script message comes and says undefined

@TheOutride

This comment has been minimized.

Copy link

commented Feb 16, 2019

Hey guys sorry about disappearing. Been busy. Apparently, like an absolute noob, I left my auth token on the original code. Deleted that entire repository and made a new one.

https://github.com/TheOutride/Discord-Deleting-DM/blob/master/Delete-Messages.js

Please drop any issues over there. Someone had made a pull request to update the ReadMe. I didn't have time to update it before deleting it.

@Altoids1 No problem. Thanks for the code really, I didn't do a whole lot beyond looping it

@MattAlp

This comment has been minimized.

Copy link

commented Feb 16, 2019

@TheOutride I'm getting an "VM324:44 Uncaught (in promise) TypeError: messages.map is not a function
at fetch.then.then.messages (:44:32)" error, do you know what might be causing that

@ghost

This comment has been minimized.

Copy link

commented Feb 20, 2019

@TheOutride
Yes its working
, but no any different from mine (/Altoids1's) except for more error messages, some "completed randomnumber" message loops, and a bit faster progress (maybe just illusion). Thanks for credits anyway. Keep it up, bro.

@ghost

This comment has been minimized.

Copy link

commented Feb 20, 2019

btw, some other also cant insert code via webversion?
Get "Scam Warning" and nothing happening, - in normal desktop-app everything is still working fine.

@ghost

This comment has been minimized.

Copy link

commented Feb 22, 2019

I found something much more handy:

  1. Download AutoHotkey:
    https://www.autohotkey.com/
  2. Save a script with a notepad: Name.ahk
    `

^j::

Loop, 100
{
send, {Up}
send, ^a
send, {BS}
send, {Enter}
send, {Enter}
sleep, 500
}
Return

`
3. Go in Disocrd, choose a Channel, start Autohotkey/Script (You have the Icon in tray now)
4. Run the script with ur choosen hotkey (default CTRL + J) (the first letters in script, self explaining)
Now you see how its deleting, without any token sht, without any javascript and console..
No any of this complicated crap is need any more... finaly...

For better handle:
Search ur messages via Discord-Search Funktion, Jump to it, run script, toggle between recent and all for update.
At any time you need to start again (reached the 100 or whatever) - or just increase the value (not tested yet).
If you want to stop (for example choose channel, doing some other: Rightclick on tray-icon and pause scripts.
When you are done, just close the application: Rightclickl on tray-icon and exit.

Source:
https://www.youtube.com/watch?v=7vYQATyqpos

Use it on own risk (for me its working fine)

@LearnSomethingNewEveryDay

This comment has been minimized.

Copy link

commented Mar 4, 2019

This works for me 3/3/19

var before = 'LAST_MESSAGE_ID';
clearMessages = function(){
var authToken = 'ENTER_HERE_UR_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();

To find token: Using F12 > Application > Storage >Discord.app.com > Then look for token, sometimes you have to refresh and it's usually the last Key - copy it quickly

@metalsonic21

This comment has been minimized.

Copy link

commented Mar 4, 2019

I found something much more handy:

  1. Download AutoHotkey:
    https://www.autohotkey.com/
  2. Save a script with a notepad: Name.ahk
    `

^j::
Loop, 100
{
send, {Up}
send, ^a
send, {BS}
send, {Enter}
send, {Enter}
sleep, 500
}
Return

`
3. Go in Disocrd, choose a Channel, start Autohotkey/Script (You have the Icon in tray now)
4. Run the script with ur choosen hotkey (default CTRL + J) (the first letters in script, self explaining)
Now you see how its deleting, without any token sht, without any javascript and console..
No any of this complicated crap is need any more... finaly...

For better handle:
Search ur messages via Discord-Search Funktion, Jump to it, run script, toggle between recent and all for update.
At any time you need to start again (reached the 100 or whatever) - or just increase the value (not tested yet).
If you want to stop (for example choose channel, doing some other: Rightclick on tray-icon and pause scripts.
When you are done, just close the application: Rightclickl on tray-icon and exit.

Source:
https://www.youtube.com/watch?v=7vYQATyqpos

Use it on own risk (for me its working fine)

not working, it doesn't delete anything.

@jackblk

This comment has been minimized.

Copy link

commented Mar 5, 2019

var before = 'LAST_MESSAGE_ID';
clearMessages = function(){
	const authToken = "ENTER_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 code still works (original code). Just replace id of the last message and token then you're good to go.

@protected22

This comment has been minimized.

Copy link

commented Mar 7, 2019

Doesn;t work. I still see my messages. even after reloading or logging in again

@ghost

This comment has been minimized.

Copy link

commented Mar 8, 2019

I found something much more handy:

  1. Download AutoHotkey:
    https://www.autohotkey.com/
  2. Save a script with a notepad: Name.ahk
    `

^j::
Loop, 100
{
send, {Up}
send, ^a
send, {BS}
send, {Enter}
send, {Enter}
sleep, 500
}
Return

`
3. Go in Disocrd, choose a Channel, start Autohotkey/Script (You have the Icon in tray now)
4. Run the script with ur choosen hotkey (default CTRL + J) (the first letters in script, self explaining)
Now you see how its deleting, without any token sht, without any javascript and console..
No any of this complicated crap is need any more... finaly...
For better handle:
Search ur messages via Discord-Search Funktion, Jump to it, run script, toggle between recent and all for update.
At any time you need to start again (reached the 100 or whatever) - or just increase the value (not tested yet).
If you want to stop (for example choose channel, doing some other: Rightclick on tray-icon and pause scripts.
When you are done, just close the application: Rightclickl on tray-icon and exit.
Source:
https://www.youtube.com/watch?v=7vYQATyqpos
Use it on own risk (for me its working fine)

not working, it doesn't delete anything.

Tested right now. Its working, you did something wrong.
Have you followed exactly the instructions? Remember you have to save the quotes plaintext as Your-name.ahk
To start you need to open the program via the file, go in channel and pressing CTRL and J same time.

@ghost

This comment has been minimized.

Copy link

commented Mar 8, 2019

Doesn;t work. I still see my messages. even after reloading or logging in again

Tested mine? Worked still weeks ago, since there I do it with the autohotkey program.

@c-edw

This comment has been minimized.

Copy link

commented Mar 8, 2019

I've been working on another solution for Discord message deletion.
https://github.com/c-edw/discord-delete

@ghost

This comment has been minimized.

Copy link

commented Mar 10, 2019

https://github.com/c-edw/discord-delete

So this thing delete EVERYTHING in discord?
Would be a good solution when I creating new Account.

@JoannaMakary

This comment has been minimized.

Copy link

commented Mar 11, 2019

This script used to work for me until a few updates ago.

Uncaught (in promise) TypeError: messages.map is not a function
at fetch.then.then.messages (:20:31)

is the error I started to get recently.

@simplycontent

This comment has been minimized.

Copy link

commented Mar 11, 2019

I've been working on another solution for Discord message deletion.
https://github.com/c-edw/discord-delete

Is this legit? I like the idea of it!

@z861gz6wb2

This comment has been minimized.

Copy link

commented Mar 21, 2019

https://gist.github.com/z861gz6wb2/fd89c6cf9db9662c68698736d937f0d2
Hey guys, I updated the Discord "mass message deletion browser script" with LOTS of improvements and bug fixes. I rewrote most parts of the script. Now you don't even need to fill in your auth token, user id, channel id. The message id part is optional. My script fetches all the needed information for you so all you gotta do is copy and paste. It works anywhere, in channels and DMs. It even lets you know when it's finished deleting all the messages, so just chill until you get the alert. I made the alert tell you how many messages it deleted too so lots of good stuff. Feel free to look at the code and tweak it anyway you like. You can even turn it into a bookmark for easy launching, just use the "javascript:" prefix followed by the code (run my script through a JS minifier first) then put it in the URL box when adding it as a bookmark.

EDIT: People are reporting that this script fails to grab the auth token in chromium browsers like Opera and Brave. However I tested it in Chrome Canary and it worked. So if you don't want to use Chrome, you can fill in your token manually.

@testing123the

This comment has been minimized.

Copy link

commented Mar 22, 2019

https://gist.github.com/z861gz6wb2/fd89c6cf9db9662c68698736d937f0d2
Hey guys, I updated the Discord "mass message deletion browser script" with LOTS of improvements and bug fixes. I rewrote most parts of the script. Now you don't even need to fill in your auth token, user id, channel id. The message id part is optional. My script fetches all the needed information for you so all you gotta do is copy and paste. It works anywhere, in channels and DMs. It even lets you know when it's finished deleting all the messages, so just chill until you get the alert. I made the alert tell you how many messages it deleted too so lots of good stuff. Feel free to look at the code and tweak it anyway you like. You can even turn it into a bookmark for easy launching, just use the "javascript:" prefix followed by the code (run my script through a JS minifier first) then put it in the URL box when adding it as a bookmark.

I replied to your code that I'm getting this error that it cannot find the IDs:
"VM369:20 Uncaught TypeError: Cannot read property 'replace' of undefined
at :20:62
at :84:3"

EDIT:
I can confirm it works if you do it manually, as the Authtoken just appears for a brief 1 sec when you load the page and the script cannot find it afterwards when it runs.
Manually:

  1. Simply use the original method to catch it (I used screenshot and typed it in manually, cause I'm too slow to copy+paste or it doesn't work?!).
  2. Paste/type it here <<const authToken = frame.contentWindow.localStorage.token.replace(/"/g, "");>>, meaning you replace <<frame.contentWindow.localStorage.token.replace(/"/g, "")>> with <<"YOUR_AUTHTOKEN">>
    (I used <<>> to quote, so remove those and don't forget to add the "")
  3. Thank the guys that helped with the code! <3
@victornpb

This comment has been minimized.

Copy link

commented Apr 8, 2019

UPDATE: 2019-APRIL

I wrote a mass delete script properly, it logs the messages being deleted along with a progress on a popup.
it also gives you an estimated time!

https://gist.github.com/victornpb/135f5b346dea4decfc8f63ad7d9cc182

@thegohst

This comment has been minimized.

Copy link

commented Jun 3, 2019

There another solution , using android mobile application to delete the messages , it work , i tested it

https://play.google.com/store/apps/details?id=com.mlika.discorddelete.free

@TheOutride

This comment has been minimized.

Copy link

commented Jun 26, 2019

Please be EXTREMELY careful of downloading applications. Make sure you trust them with the permissions you give them.

Code currently working found here: https://github.com/TheOutride/Discord-Deleting-DM

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.