Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.39 KB | None | 0 0
  1. function deleteMessages(authToken, authorId, channelId, afterMessageId) {
  2. const start = new Date();
  3. let delayDelete = 500;
  4. let delaySearch = 1000;
  5. let delCount = 0;
  6. let failCount = 0;
  7. let estimatedPing = 220;
  8. let grandTotal;
  9. let throttledCount = 0;
  10. let throttledTotalTime = 0;
  11. const history = [];
  12.  
  13. const wait = async (ms) => new Promise(done => setTimeout(done, ms));
  14. const msToHMS = (s) => `${s / 3.6e6 | 0}h ${(s % 3.6e6) / 6e4 | 0}m ${(s % 6e4) / 1000 | 0}s`;
  15. function logger(type, args, style = '') {
  16. console[type].apply(console, args);
  17. history.push(args);
  18. pp.insertAdjacentHTML('beforeend', `<div style="${style}">${Array.from(args).map(o => typeof o === 'object' ? JSON.stringify(o) : o).join('\t')}</div>`);
  19. popup.scrollBy(0, 1e10);
  20. }
  21. function log() { logger('log', arguments, 'black'); }
  22. function log_info() { logger('info', arguments, 'color:darkturquoise;'); }
  23. function log_verb() { logger('debug', arguments, 'color:gray;'); }
  24. function log_warn() { logger('warn', arguments, 'color:orange;'); }
  25. function log_error() { logger('error', arguments, 'color:red;'); }
  26. function log_success() { logger('log', arguments, 'color:green;'); }
  27.  
  28. var popup = window.open('', '', 'width=800,height=1000,top=0,left=0');
  29. popup.document.body.innerHTML = '<pre></pre>';
  30. const pp = popup.document.getElementsByTagName('pre')[0];
  31. if (!popup) console.error('Popup blocked!');
  32.  
  33. log_info(`Started at ${start.toLocaleString()}`);
  34. log(`channelId=${channelId} authorId=${authorId} firstMessageId=${afterMessageId}`);
  35. log_info(`---- You can abort by setting STOP=1 on the console ----`);
  36. recurse();
  37.  
  38. async function recurse() {
  39. const headers = {
  40. "Authorization": authToken
  41. };
  42. const deleteAfter = `search?author_id=${authorId}` + (afterMessageId ? `&min_id=${afterMessageId}` : '');
  43. const baseURL = `https://discordapp.com/api/v6/channels/${channelId}/messages/`;
  44.  
  45. let resp;
  46. try {
  47. resp = await fetch(baseURL + deleteAfter, {
  48. headers
  49. });
  50. } catch (err) {
  51. log_error('Something went wrong!', err);
  52. return;
  53. }
  54.  
  55. // not indexed yet
  56. if (resp.status === 202) {
  57. const w = (await resp.json()).retry_after;
  58. throttledCount++;
  59. throttledTotalTime += w;
  60. log_warn(`This channel wasn't indexed, waiting ${w} ms for discord to index it...`);
  61. await wait(w);
  62. return recurse();
  63. }
  64.  
  65. if (!resp.ok) {
  66. if (resp.status === 429) {
  67. const r = await resp.json();
  68. const x = r.retry_after;
  69. throttledCount++;
  70. throttledTotalTime += x;
  71. log_warn(`! Rate limited by the API! Waiting ${x} ms ...`);
  72. await wait(x);
  73. return recurse();
  74. } else {
  75. log_error('API respondend with non OK status!', await resp.json());
  76. return;
  77. }
  78. }
  79.  
  80. const result = await resp.json();
  81.  
  82. const total = result.total_results;
  83. if (!grandTotal) grandTotal = total;
  84. log_info(`Messages to delete: ${result.total_results}`, `Time remaining: ${msToHMS((delaySearch * Math.round(total / 25)) + ((delayDelete + estimatedPing) * total))} (ping: ${estimatedPing << 0}ms)`);
  85.  
  86. if (result.total_results > 0) {
  87. for (let i = 0; i < result.messages.length; i++) {
  88. const element = result.messages[i];
  89. for (let j = 0; j < element.length; j++) {
  90. const message = element[j];
  91.  
  92. if (window.STOP) return log_error('STOPPED! (If you want to continue set STOP=0 and run again!');
  93.  
  94. if (message.type === 3) {
  95. log_verb('Found a System message!? skipping it...', message);
  96. } else if (message.author.id == authorId && message.hit == true) {
  97.  
  98. log(`${((delCount + 1) / grandTotal * 100).toFixed(2)}% (${delCount + 1}/${grandTotal}) Deleting ID:${message.id}`,
  99. `[${new Date(message.timestamp).toLocaleString()}] ${message.author.username}#${message.author.discriminator}: ${message.content}`,
  100. message.attachments.length ? message.attachments : '');
  101. const s = Date.now();
  102.  
  103. let resp;
  104. try {
  105. resp = await fetch(baseURL + message.id, {
  106. headers,
  107. method: "DELETE"
  108. });
  109. delCount++;
  110. } catch (err) {
  111. log_error('Failed to delete message:', message, 'Error:', err);
  112. failCount++;
  113. }
  114.  
  115. if (!resp.ok) {
  116. if (resp.status === 429) {
  117. const r = await resp.json();
  118. const x = r.retry_after;
  119. throttledCount++;
  120. throttledTotalTime += x;
  121. log_warn(`! Rate limited by the API! Waiting ${x} ms ...`);
  122. await wait(x);
  123. i--;
  124. } else {
  125. log_error('API respondend with non OK status!', resp);
  126. }
  127. }
  128. estimatedPing = (estimatedPing + (Date.now() - s)) / 2;
  129. await wait(delayDelete);
  130. }
  131. }
  132. }
  133. log_verb('Getting next messages...');
  134. await wait(delaySearch);
  135. return recurse();
  136. } else {
  137. log_success('---- DONE! ----');
  138. log_info(`Ended at ${new Date().toLocaleString()}! Total time: ${msToHMS(Date.now() - start.getTime())}`);
  139. log(`Rate Limited: ${throttledCount} times. Total time throttled: ${msToHMS(throttledTotalTime)}`);
  140. log(`Deleted ${delCount} messages , ${failCount} failed.`);
  141. return result;
  142. }
  143. }
  144. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement