Saltar al contenido

Eliminando todos los mensajes en el canal de texto discord.js

Te sugerimos que pruebes esta solución en un entorno controlado antes de enviarlo a producción, saludos.

Solución:

Prueba esto

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

Discord no permite que los bots eliminen más de 100 mensajes, por lo que no puede eliminar todos los mensajes de un canal. Puede eliminar menos de 100 mensajes mediante BulkDelete.

Ejemplo:

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

Tenga en cuenta que tiene que estar en una función asincrónica para el esperar trabajar.

Aquí está mi versión mejorada que es más rápida y le permite saber cuándo se hace en la consola, pero tendrá que ejecutarla para cada nombre de usuario que utilizó en un canal (si cambió su nombre de usuario en algún momento):

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

El script anterior que encontré para eliminar tus propios mensajes sin un 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();

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

No se te olvide recomendar esta reseña si te valió la pena.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *