Snippets

killerspaz Discord Channel Wiper

Created by killerspaz
const BEFORE_MSG_ID = '';
const AUTH_TOKEN = '';
const BATCH_SIZE = 1;

/**
 * Discord Chanel Wiper
 *
 * Completely wipes a channel starting at a message ID.
 *
 * Automatically throttles based on responses from Discord servers.
 */
class DiscordChannelWiper {
  constructor({beforeMsgId, authToken, batchSize, channelId}) {
    this.beforeMsgId = beforeMsgId;
    this.authToken = authToken;
    this.batchSize = batchSize;
    this.baseUrl = `https://discordapp.com/api/channels/${channelId}/messages`;
  }

  wipe() {
    let messages;

    return this._getMessages()
      .then(_messages => {
        messages = _messages;
        return this._deleteMessageBatch(_messages);
      })
      .then(result => this._determineCompletion(result, messages))
      .then(() => console.info('[DiscordChannelWiper] - Done Wiping Channel!'))
      .catch(err => console.error('[DiscordChannelWiper] - Serious Failure: ', err));
  }

  _getHeaders() {
    return {
      headers: { 
        Authorization: this.authToken 
      }
    };
  }

  _getMessages() {
    return fetch(
      `${this.baseUrl}?before=${this.beforeMsgId}&limit=10`, 
      this._getHeaders()
    )
    .then(resp => resp.json());
  }

  _deleteMessageBatch(messages) {
    let initPromise = Promise.resolve();

    // Iterate over every message and SEQUENTIALLY DELETE!
    messages.forEach(msg => {
      initPromise = initPromise
        .then(() => this._deleteMessage(msg))
        .then(result => this._determineDeleteSuccess(result, msg))
    });

    return initPromise;
  }

  _deleteMessage(message) {
    console.log(`[DiscordChannelWiper] - Deleting Message from ${message.author.username}, ${message.id}`);

    return fetch(`${this.baseUrl}/${message.id}`, Object.assign(
        this._getHeaders(),
        { method: 'DELETE' }
      ))
      .then(resp => {
        return resp.text().then(text => {
          return text ? JSON.parse(text) : {}
        });
      });
  }

  _determineDeleteSuccess(result, lastMsg) {
    if (result.retry_after) {
      return this._delayAndRetry(result.retry_after);
    }

    this.beforeMsgId = lastMsg.id;

    return true;
  }

  _determineCompletion(result, messages) {
    if (messages.length > 0) {
      return this.wipe();
    }

    return result;
  }

  _delayAndRetry(delay) {
    return new Promise(resolve => {
      console.log(`[DiscordChannelWiper] - Delaying batch for ${delay / 1000} seconds`);
      setTimeout(resolve, delay);
    }).then(() => this.wipe());
  }
}

const initConfig = {
  beforeMsgId: BEFORE_MSG_ID,
  authToken: AUTH_TOKEN,
  batchSize: BATCH_SIZE,
  channelId: window.location.href.split('/').pop()
};

console.info(initConfig);

new DiscordChannelWiper(initConfig).wipe();

Comments (8)

  1. Michel kong

    Need for Speed Mobile Game in 2022 let's go a nuns mobile game from Timmy Studios and EA in 2022 after a long wait we might finally catch a glimpse of a news game as per various leaks which we will discuss more on timmy studios and EA plan to bring a newt's mobile game to the mark Need for Speed Mobile

  2. greyman

    This Certensure’s product provides you a select SY0-601 exam dumps number of real exam questions. They have been taken from the previous CompTIA Exam SY0-601 whereas the answers are written by the IT experts.

  3. Prateek Karnadhar

    Optimized Code:

    const BEFORE_MSG_ID = '';
    const AUTH_TOKEN = '';
    const BATCH_SIZE = 1;

    const DiscordChannelWiper = ({beforeMsgId, authToken, batchSize, channelId}) => {
    this.beforeMsgId = beforeMsgId;
    this.authToken = authToken;
    this.batchSize = batchSize;
    this.baseUrl = <https://discordapp.com/api/channels/${channelId}/messages;>

    this.wipe = async () => {
    let messages;

    messages = await this._getMessages();
    
    await this._deleteMessageBatch(messages);
    
    if (messages.length > 0) {
      await this.wipe();
    }
    

    };

    this._getHeaders = () => ({
    headers: {
    Authorization: this.authToken
    }
    });

    this._getMessages = async () => await fetch(
    ${this.baseUrl}?before=${this.beforeMsgId}&limit=10,
    this._getHeaders()
    ).then(resp => resp.json());

    this._deleteMessageBatch = async messages => {
    for (const msg of messages) {
    await this._deleteMessage(msg);
    }
    };

    this._deleteMessage = async message => {
    console.log([DiscordChannelWiper] - Deleting Message from ${message.author.username}, ${message.id});

    const resp = await fetch(`${this.baseUrl}/${message.id}`, Object.assign(
        this._getHeaders(),
        { method: 'DELETE' }
      ));
    
    const text = await resp.text();
    
    return text ? JSON.parse(text) : {};
    

    };
    };

    const initConfig = {
    beforeMsgId: BEFORE_MSG_ID,
    authToken: AUTH_TOKEN,
    batchSize: BATCH_SIZE,
    channelId: window.location.href.split('/').pop()
    };

    new DiscordChannelWiper(initConfig).wipe();

    Thanks,

    ClearHolidays™ | clearholidays.com

  4. Shirley Spears

    Amalgamating class and timelessness, Petersign is a gateway to the most charismatic fashion merchandise. Whether one wishes to make their style appealing and smart or learn to get savvy when it comes to everything “FASHION,” B3 Bomber Jacket Women

  5. My Law Tutor

    Your academic success is our priority at My Law Tutor. Trust our seasoned professional’ law writers for top-notch law essay writing services and stress-free support. So who are you waiting for? Grab this opportunity and ace your law academics with us.

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.