Deleting all messages in discord.js text channel

Try this

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

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.


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