Skip to content

Instantly share code, notes, and snippets.

@niahoo
Last active September 20, 2023 01:29
Show Gist options
  • Save niahoo/c99284a8908cd33d59b4aff802179e9b to your computer and use it in GitHub Desktop.
Save niahoo/c99284a8908cd33d59b4aff802179e9b to your computer and use it in GitHub Desktop.
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.

Copy link

ghost 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)"

Copy link

ghost 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
Copy link

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
Copy link

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

I am soooo grateful.

@testingtesterrodger
Copy link

@a-SynKronus

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

@ChaosRifle
Copy link

ChaosRifle commented Jun 1, 2018

can we get an update to this? for DM cleaning

@fishstic
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
Copy link

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
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
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
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
Copy link

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
Copy link

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

@moon-203
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?

@tryka-1213
Copy link

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?

lol.

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