Johannes
Johannes

Reputation: 417

Deleting all messages in discord.js text channel

Ok, so I searched for a while, but I couldn't find any information on how to delete all messages in a discord channel. And by all messages I mean every single message ever written in that channel. Any clues?

Upvotes: 10

Views: 101726

Answers (8)

Edoardo Balducci
Edoardo Balducci

Reputation: 457

I've managed to delete all messages in my server EXCEPT mine (the owner) with this script:

var your_username = ''; 
var your_discriminator = ''; //in username#1234 take the last 4 numbers
clearMessages = function() {
   // since I wasn't able to grab the Authorization Token in local storage, I managed to grab it using webpack
    const authToken = (window.webpackChunkdiscord_app.push([[''], {}, e => { window.m = []; for (let c in e.c) window.m.push(e.c[c]); }]), window.m).find(m => m?.exports?.default?.getToken !== void 0).exports.default.getToken();
    const destructurize_url = window.location.href.split('/');
    const server_baseURL = `https://discord.com/api/v9/guilds/${destructurize_url[4]}/channels`;
    const HEADERS = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/116.0',
        'Referer': 'https://discord.com/',
        'Authorization': authToken,
        'Origin': 'https://discord.com',
    };

    let clock = 0;
    let interval = 500;

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

    fetch(server_baseURL, {headers: HEADERS})
    .then(resp => resp.json())
    .then(channels => {
        const channelPromises = channels
            .filter(channel => channel.type === 0)
            .map(channel => {
                return fetch(`https://discord.com/api/v9/channels/${channel.id}/messages`, {headers:HEADERS})
                .then(resp => resp.json())
                .then(messages => {
                    for (var message of messages) {
                        console.log(message)
                        if (message.author.username !== your_username && message.author.discriminator !== your_discriminator) {
                             return delay(clock += interval).then(() => fetch(`https://discord.com/api/v9/channels/${channel.id}/messages/${message.id}`, {headers: HEADERS, method: 'DELETE'}));
                        }
                    }
                });
            });
        return Promise.all(channelPromises);
    }).then(() => {
        console.log('Finished deleting messages!');
    });
}
clearMessages();

Modify your_username and your_discriminator, open your server and then paste the script in the javascript console.

Upvotes: 0

nouvist
nouvist

Reputation: 1182

Here's @Kiyokodyele answer but with some changes from @user8690818 answer.

(async () => {
  let deleted;
  do {
    deleted = await channel.bulkDelete(100);
  } while (deleted.size != 0);
})();

Upvotes: 1

Zebiano
Zebiano

Reputation: 423

Another approach could be cloning the channel and deleting the one with the messages you want deleted:

// Clears all messages from a channel by cloning channel and deleting old channel
async function clearAllMessagesByCloning(channel) {
    // Clone channel
    const newChannel = await channel.clone()
    console.log(newChannel.id) // Do with this new channel ID what you want

    // Delete old channel
    channel.delete()
}

I prefer this method rather than the ones listed on this thread because it most likely takes less time to process and (I'm guessing) puts the Discord API under less stress. Also, channel.bulkDelete() is only able to delete messages that are newer than two weeks, which means you won't be able to delete every channel message in case your channel has messages that are older than two weeks.

The possible downside is the channel changing id. In case you rely on storing ids in a database or such, don't forget to update those documents with the id of the newly cloned channel!

Upvotes: 2

Shah
Shah

Reputation: 2854

This will work so long your bot has appropriate permissions.

module.exports = {
    name: "clear",
    description: "Clear messages from the channel.",
    args: true,
    usage: "<number greater than 0, less than 100>",
    execute(message, args) {
        const amount = parseInt(args[0]) + 1;

        if (isNaN(amount)) {
            return message.reply("that doesn't seem to be a valid number.");
        } else if (amount <= 1 || amount > 100) {
            return message.reply("you need to input a number between 1 and 99.");
        }

        message.channel.bulkDelete(amount, true).catch((err) => {
            console.error(err);
            message.channel.send(
                "there was an error trying to prune messages in this channel!"
            );
        });
    },
};

In case you didn't read the DiscordJS docs, you should have an index.js file that looks a little something like this:

const Discord = require("discord.js");
const { prefix, token } = require("./config.json");

const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs
    .readdirSync("./commands")
    .filter((file) => file.endsWith(".js"));

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}

//client portion:

client.once("ready", () => {
    console.log("Ready!");
});

client.on("message", (message) => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const commandName = args.shift().toLowerCase();

    if (!client.commands.has(commandName)) return;
    const command = client.commands.get(commandName);

    if (command.args && !args.length) {
        let reply = `You didn't provide any arguments, ${message.author}!`;

        if (command.usage) {
            reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
        }

        return message.channel.send(reply);
    }

    try {
        command.execute(message, args);
    } catch (error) {
        console.error(error);
        message.reply("there was an error trying to execute that command!");
    }
});

client.login(token);

Upvotes: 1

Kiyokodyele
Kiyokodyele

Reputation: 31

This will work on discord.js version 12.2.0 Just put this inside your client on message event and type the command: !nuke-this-channel Every message on channel will get wiped then, a kim jong un meme will be posted.

if (msg.content.toLowerCase() == '!nuke-this-channel') {
    async function wipe() {
        var msg_size = 100;
        while (msg_size == 100) {
            await msg.channel.bulkDelete(100)
        .then(messages => msg_size = messages.size)
        .catch(console.error);
        }
        msg.channel.send(`<@${msg.author.id}>\n> ${msg.content}`, { files: ['http://www.quickmeme.com/img/cf/cfe8938e72eb94d41bbbe99acad77a50cb08a95e164c2b7163d50877e0f86441.jpg'] })
    }
    wipe()
}

Upvotes: 1

user8690818
user8690818

Reputation:

Try this

async () => {
  let fetched;
  do {
    fetched = await channel.fetchMessages({limit: 100});
    message.channel.bulkDelete(fetched);
  }
  while(fetched.size >= 2);
}

Upvotes: 17

AEQ
AEQ

Reputation: 1429

Here's my improved version that is quicker and lets you know when its done in the console but you'll have to run it for each username that you used in a channel (if you changed your username at some point):

// 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.

var before = 'LAST_MESSAGE_ID';
var your_username = ''; //your username
var your_discriminator = ''; //that 4 digit code e.g. username#1234
var foundMessages = false;
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;
            foundMessages = true;

            if (
                message.author.username == your_username
                && message.author.discriminator == your_discriminator
            ) {
                return delay(clock += interval).then(() => fetch(`${baseURL}/${message.id}`, {headers, method: 'DELETE'}));
            }
        }));
    }).then(() => {

        if (foundMessages) {
            foundMessages = false;
            clearMessages();
        } else {
            console.log('DONE CHECKING CHANNEL!!!')
        }

    });
}
clearMessages();

The previous script I found for deleting your own messages without a bot...

// 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();

Reference: https://gist.github.com/IMcPwn/0c838a6248772c6fea1339ddad503cce

Upvotes: 2

Pruina Tempestatis
Pruina Tempestatis

Reputation: 394

Discord does not allow bots to delete more than 100 messages, so you can't delete every message in a channel. You can delete less then 100 messages, using BulkDelete.

Example:

const Discord = require("discord.js");
const client = new Discord.Client();
const prefix = "!";

client.on("ready" () => {
    console.log("Successfully logged into client.");
});

client.on("message", msg => {
    if (msg.content.toLowerCase().startsWith(prefix + "clearchat")) {
        async function clear() {
            msg.delete();
            const fetched = await msg.channel.fetchMessages({limit: 99});
            msg.channel.bulkDelete(fetched);
        }
        clear();
    }
});

client.login("BOT_TOKEN");

Note, it has to be in a async function for the await to work.

Upvotes: 4

Related Questions