Undiscord3233

Delete all messages in a Discord channel or DM (Bulk deletion) delete

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/476338/1270038/Undiscord3233.js

  1. // ==UserScript==
  2. // @name Undiscord
  3. // @description Delete all messages in a Discord channel or DM (Bulk deletion)
  4. // @version 5.2.0
  5. // @author victornpb
  6. // @homepageURL https://github.com/victornpb/undiscord
  7. // @supportURL https://github.com/victornpb/undiscord/discussions
  8. // @match https://*.discord.com/app
  9. // @match https://*.discord.com/channels/*
  10. // @match https://*.discord.com/login
  11. // @license MIT
  12. // @namespace https://github.com/victornpb/deleteDiscordMessages
  13. // @icon https://victornpb.github.io/undiscord/images/icon128.png
  14. // @contributionURL https://www.buymeacoffee.com/vitim
  15. // @grant none
  16. // ==/UserScript==
  17. (function () {
  18. 'use strict';
  19. /* rollup-plugin-baked-env */
  20. const VERSION = "5.2.0";
  21. var themeCss = (`
  22. /* undiscord window */
  23. #undiscord.browser { box-shadow: var(--elevation-stroke), var(--elevation-high); overflow: hidden; }
  24. #undiscord.container,
  25. #undiscord .container { background-color: var(--background-secondary); border-radius: 8px; box-sizing: border-box; cursor: default; flex-direction: column; }
  26. #undiscord .header { background-color: var(--background-tertiary); height: 48px; align-items: center; min-height: 48px; padding: 0 16px; display: flex; color: var(--header-secondary); cursor: grab; }
  27. #undiscord .header .icon { color: var(--interactive-normal); margin-right: 8px; flex-shrink: 0; width: 24; height: 24; }
  28. #undiscord .header .icon:hover { color: var(--interactive-hover); }
  29. #undiscord .header h3 { font-size: 16px; line-height: 20px; font-weight: 500; font-family: var(--font-display); color: var(--header-primary); flex-shrink: 0; margin-right: 16px; }
  30. #undiscord .spacer { flex-grow: 1; }
  31. #undiscord .header .vert-divider { width: 1px; height: 24px; background-color: var(--background-modifier-accent); margin-right: 16px; flex-shrink: 0; }
  32. #undiscord legend,
  33. #undiscord label { color: var(--header-secondary); font-size: 12px; line-height: 16px; font-weight: 500; text-transform: uppercase; cursor: default; font-family: var(--font-display); margin-bottom: 8px; }
  34. #undiscord .multiInput { display: flex; align-items: center; font-size: 16px; box-sizing: border-box; width: 100%; border-radius: 3px; color: var(--text-normal); background-color: var(--input-background); border: none; transition: border-color 0.2s ease-in-out 0s; }
  35. #undiscord .multiInput :first-child { flex-grow: 1; }
  36. #undiscord .multiInput button:last-child { margin-right: 4px; }
  37. #undiscord .input { font-size: 16px; box-sizing: border-box; width: 100%; border-radius: 3px; color: var(--text-normal); background-color: var(--input-background); border: none; transition: border-color 0.2s ease-in-out 0s; padding: 10px; height: 40px; }
  38. #undiscord fieldset { margin-top: 16px; }
  39. #undiscord .input-wrapper { display: flex; align-items: center; font-size: 16px; box-sizing: border-box; width: 100%; border-radius: 3px; color: var(--text-normal); background-color: var(--input-background); border: none; transition: border-color 0.2s ease-in-out 0s; }
  40. #undiscord input[type="text"],
  41. #undiscord input[type="search"],
  42. #undiscord input[type="password"],
  43. #undiscord input[type="datetime-local"],
  44. #undiscord input[type="number"],
  45. #undiscord input[type="range"] { font-size: 16px; box-sizing: border-box; width: 100%; border-radius: 3px; color: var(--text-normal); background-color: var(--input-background); border: none; transition: border-color 0.2s ease-in-out 0s; padding: 10px; height: 40px; }
  46. #undiscord .divider,
  47. #undiscord hr { border: none; margin-bottom: 24px; padding-bottom: 4px; border-bottom: 1px solid var(--background-modifier-accent); }
  48. #undiscord .sectionDescription { margin-bottom: 16px; color: var(--header-secondary); font-size: 14px; line-height: 20px; font-weight: 400; }
  49. #undiscord a { color: var(--text-link); text-decoration: none; }
  50. #undiscord .btn,
  51. #undiscord button { position: relative; display: flex; -webkit-box-pack: center; justify-content: center; -webkit-box-align: center; align-items: center; box-sizing: border-box; background: none; border: none; border-radius: 3px; font-size: 14px; font-weight: 500; line-height: 16px; padding: 2px 16px; user-select: none; /* sizeSmall */ width: 60px; height: 32px; min-width: 60px; min-height: 32px; /* lookFilled colorPrimary */ color: rgb(255, 255, 255); background-color: var(--button-secondary-background); }
  52. #undiscord .sizeMedium { width: 96px; height: 38px; min-width: 96px; min-height: 38px; }
  53. #undiscord .sizeMedium.icon { width: 38px; min-width: 38px; }
  54. #undiscord sup { vertical-align: top; }
  55. /* lookFilled colorPrimary */
  56. #undiscord .accent { background-color: var(--brand-experiment); }
  57. #undiscord .danger { background-color: var(--button-danger-background); }
  58. #undiscord .positive { background-color: var(--button-positive-background); }
  59. #undiscord .info { font-size: 12px; line-height: 16px; padding: 8px 10px; color: var(--text-muted); }
  60. /* Scrollbar */
  61. #undiscord .scroll::-webkit-scrollbar { width: 8px; height: 8px; }
  62. #undiscord .scroll::-webkit-scrollbar-corner { background-color: transparent; }
  63. #undiscord .scroll::-webkit-scrollbar-thumb { background-clip: padding-box; border: 2px solid transparent; border-radius: 4px; background-color: var(--scrollbar-thin-thumb); min-height: 40px; }
  64. #undiscord .scroll::-webkit-scrollbar-track { border-color: var(--scrollbar-thin-track); background-color: var(--scrollbar-thin-track); border: 2px solid var(--scrollbar-thin-track); }
  65. /* fade scrollbar */
  66. #undiscord .scroll::-webkit-scrollbar-thumb,
  67. #undiscord .scroll::-webkit-scrollbar-track { visibility: hidden; }
  68. #undiscord .scroll:hover::-webkit-scrollbar-thumb,
  69. #undiscord .scroll:hover::-webkit-scrollbar-track { visibility: visible; }
  70. /**** functional classes ****/
  71. #undiscord.redact .priv { display: none !important; }
  72. #undiscord.redact x:not(:active) { color: transparent !important; background-color: var(--primary-700) !important; cursor: default; }
  73. #undiscord.redact x:hover { position: relative; }
  74. #undiscord.redact x:hover::after { content: "Redacted information (Streamer mode: ON)"; position: absolute; display: inline-block; top: -32px; left: -20px; padding: 4px; width: 150px; font-size: 8pt; text-align: center; white-space: pre-wrap; background-color: var(--background-floating); -webkit-box-shadow: var(--elevation-high); box-shadow: var(--elevation-high); color: var(--text-normal); border-radius: 5px; pointer-events: none; }
  75. #undiscord.redact [priv] { -webkit-text-security: disc !important; }
  76. #undiscord :disabled { display: none; }
  77. /**** layout and utility classes ****/
  78. #undiscord,
  79. #undiscord * { box-sizing: border-box; }
  80. #undiscord .col { display: flex; flex-direction: column; }
  81. #undiscord .row { display: flex; flex-direction: row; align-items: center; }
  82. #undiscord .mb1 { margin-bottom: 8px; }
  83. #undiscord .log { margin-bottom: 0.25em; }
  84. #undiscord .log-debug { color: inherit; }
  85. #undiscord .log-info { color: #00b0f4; }
  86. #undiscord .log-verb { color: #72767d; }
  87. #undiscord .log-warn { color: #faa61a; }
  88. #undiscord .log-error { color: #f04747; }
  89. #undiscord .log-success { color: #43b581; }
  90. `);
  91. var mainCss = (`
  92. /**** Undiscord Button ****/
  93. #undicord-btn { position: relative; width: auto; height: 24px; margin: 0 8px; cursor: pointer; color: var(--interactive-normal); flex: 0 0 auto; }
  94. #undicord-btn progress { position: absolute; top: 23px; left: -4px; width: 32px; height: 12px; display: none; }
  95. #undicord-btn.running { color: var(--button-danger-background) !important; }
  96. #undicord-btn.running progress { display: block; }
  97. /**** Undiscord Interface ****/
  98. #undiscord { position: fixed; z-index: 100; top: 58px; right: 10px; display: flex; flex-direction: column; width: 800px; height: 80vh; min-width: 610px; max-width: 100vw; min-height: 448px; max-height: 100vh; color: var(--text-normal); border-radius: 4px; background-color: var(--background-secondary); box-shadow: var(--elevation-stroke), var(--elevation-high); will-change: top, left, width, height; }
  99. #undiscord .header .icon { cursor: pointer; }
  100. #undiscord .window-body { height: calc(100% - 48px); }
  101. #undiscord .sidebar { overflow: hidden scroll; overflow-y: auto; width: 270px; min-width: 250px; height: 100%; max-height: 100%; padding: 8px; background: var(--background-secondary); }
  102. #undiscord .sidebar legend,
  103. #undiscord .sidebar label { display: block; width: 100%; }
  104. #undiscord .main { display: flex; max-width: calc(100% - 250px); background-color: var(--background-primary); flex-grow: 1; }
  105. #undiscord.hide-sidebar .sidebar { display: none; }
  106. #undiscord.hide-sidebar .main { max-width: 100%; }
  107. #undiscord #logArea { font-family: Consolas, Liberation Mono, Menlo, Courier, monospace; font-size: 0.75rem; overflow: auto; padding: 10px; user-select: text; flex-grow: 1; flex-grow: 1; cursor: auto; }
  108. #undiscord .tbar { padding: 8px; background-color: var(--background-secondary-alt); }
  109. #undiscord .tbar button { margin-right: 4px; margin-bottom: 4px; }
  110. #undiscord .footer { cursor: se-resize; padding-right: 30px; }
  111. #undiscord .footer #progressPercent { padding: 0 1em; font-size: small; color: var(--interactive-muted); flex-grow: 1; }
  112. .resize-handle { position: absolute; bottom: -15px; right: -15px; width: 30px; height: 30px; transform: rotate(-45deg); background: repeating-linear-gradient(0, var(--background-modifier-accent), var(--background-modifier-accent) 1px, transparent 2px, transparent 4px); cursor: nwse-resize; }
  113. /**** Elements ****/
  114. #undiscord summary { font-size: 16px; font-weight: 500; line-height: 20px; position: relative; overflow: hidden; margin-bottom: 2px; padding: 6px 10px; cursor: pointer; white-space: nowrap; text-overflow: ellipsis; color: var(--interactive-normal); border-radius: 4px; flex-shrink: 0; }
  115. #undiscord fieldset { padding-left: 8px; }
  116. #undiscord legend a { float: right; text-transform: initial; }
  117. #undiscord progress { height: 8px; margin-top: 4px; flex-grow: 1; }
  118. #undiscord .importJson { display: flex; flex-direction: row; }
  119. #undiscord .importJson button { margin-left: 5px; width: fit-content; }
  120. `);
  121. var dragCss = (`
  122. [name^="grab-"] { position: absolute; --size: 6px; --corner-size: 16px; --offset: -1px; z-index: 9; }
  123. [name^="grab-"]:hover{ background: rgba(128,128,128,0.1); }
  124. [name="grab-t"] { top: 0px; left: var(--corner-size); right: var(--corner-size); height: var(--size); margin-top: var(--offset); cursor: ns-resize; }
  125. [name="grab-r"] { top: var(--corner-size); bottom: var(--corner-size); right: 0px; width: var(--size); margin-right: var(--offset);
  126. cursor: ew-resize; }
  127. [name="grab-b"] { bottom: 0px; left: var(--corner-size); right: var(--corner-size); height: var(--size); margin-bottom: var(--offset); cursor: ns-resize; }
  128. [name="grab-l"] { top: var(--corner-size); bottom: var(--corner-size); left: 0px; width: var(--size); margin-left: var(--offset); cursor: ew-resize; }
  129. [name="grab-tl"] { top: 0px; left: 0px; width: var(--corner-size); height: var(--corner-size); margin-top: var(--offset); margin-left: var(--offset); cursor: nwse-resize; }
  130. [name="grab-tr"] { top: 0px; right: 0px; width: var(--corner-size); height: var(--corner-size); margin-top: var(--offset); margin-right: var(--offset); cursor: nesw-resize; }
  131. [name="grab-br"] { bottom: 0px; right: 0px; width: var(--corner-size); height: var(--corner-size); margin-bottom: var(--offset); margin-right: var(--offset); cursor: nwse-resize; }
  132. [name="grab-bl"] { bottom: 0px; left: 0px; width: var(--corner-size); height: var(--corner-size); margin-bottom: var(--offset); margin-left: var(--offset); cursor: nesw-resize; }
  133. `);
  134. var buttonHtml = (`
  135. <div id="undicord-btn" tabindex="0" role="button" aria-label="Delete Messages" title="Delete Messages with Undiscord">
  136. <svg aria-hidden="false" width="24" height="24" viewBox="0 0 24 24">
  137. <path fill="currentColor" d="M15 3.999V2H9V3.999H3V5.999H21V3.999H15Z"></path>
  138. <path fill="currentColor" d="M5 6.99902V18.999C5 20.101 5.897 20.999 7 20.999H17C18.103 20.999 19 20.101 19 18.999V6.99902H5ZM11 17H9V11H11V17ZM15 17H13V11H15V17Z"></path>
  139. </svg>
  140. <progress></progress>
  141. </div>
  142. `);
  143. var undiscordTemplate = (`
  144. <div id="undiscord" class="browser container redact" style="display:none;">
  145. <div class="header">
  146. <svg class="icon" aria-hidden="false" width="24" height="24" viewBox="0 0 24 24">
  147. <path fill="currentColor" d="M15 3.999V2H9V3.999H3V5.999H21V3.999H15Z"></path>
  148. <path fill="currentColor"
  149. d="M5 6.99902V18.999C5 20.101 5.897 20.999 7 20.999H17C18.103 20.999 19 20.101 19 18.999V6.99902H5ZM11 17H9V11H11V17ZM15 17H13V11H15V17Z">
  150. </path>
  151. </svg>
  152. <h3>Undiscord</h3>
  153. <div class="vert-divider"></div>
  154. <span> Bulk delete messages</span>
  155. <div class="spacer"></div>
  156. <div id="hide" class="icon" aria-label="Close" role="button" tabindex="0">
  157. <svg aria-hidden="false" width="24" height="24" viewBox="0 0 24 24">
  158. <path fill="currentColor"
  159. d="M18.4 4L12 10.4L5.6 4L4 5.6L10.4 12L4 18.4L5.6 20L12 13.6L18.4 20L20 18.4L13.6 12L20 5.6L18.4 4Z">
  160. </path>
  161. </svg>
  162. </div>
  163. </div>
  164. <div class="window-body" style="display: flex; flex-direction: row;">
  165. <div class="sidebar scroll">
  166. <details open>
  167. <summary>General</summary>
  168. <fieldset>
  169. <legend>
  170. Author ID
  171. <a href="{{WIKI}}/authorId" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  172. </legend>
  173. <div class="multiInput">
  174. <div class="input-wrapper">
  175. <input class="input" id="authorId" type="text" priv>
  176. </div>
  177. <button id="getAuthor">me</button>
  178. </div>
  179. </fieldset>
  180. <hr>
  181. <fieldset>
  182. <legend>
  183. Server ID
  184. <a href="{{WIKI}}/guildId" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  185. </legend>
  186. <div class="multiInput">
  187. <div class="input-wrapper">
  188. <input class="input" id="guildId" type="text" priv>
  189. </div>
  190. <button id="getGuild">current</button>
  191. </div>
  192. </fieldset>
  193. <fieldset>
  194. <legend>
  195. Channel ID
  196. <a href="{{WIKI}}/channelId" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  197. </legend>
  198. <div class="multiInput mb1">
  199. <div class="input-wrapper">
  200. <input class="input" id="channelId" type="text" priv>
  201. </div>
  202. <button id="getChannel">current</button>
  203. </div>
  204. <div class="sectionDescription">
  205. <label class="row"><input id="includeNsfw" type="checkbox">This is a NSFW channel</label>
  206. </div>
  207. </fieldset>
  208. </details>
  209. <details>
  210. <summary>Wipe Archive</summary>
  211. <fieldset>
  212. <legend>
  213. Import index.json
  214. <a href="{{WIKI}}/importJson" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  215. </legend>
  216. <div class="input-wrapper">
  217. <input type="file" id="importJsonInput" accept="application/json,.json" style="width:100%";>
  218. </div>
  219. <div class="sectionDescription">
  220. <br>
  221. After requesting your data from discord, you can import it here.<br>
  222. Select the "messages/index.json" file from the discord archive.
  223. </div>
  224. </fieldset>
  225. </details>
  226. <hr>
  227. <details>
  228. <summary>Filter</summary>
  229. <fieldset>
  230. <legend>
  231. Search
  232. <a href="{{WIKI}}/filters" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  233. </legend>
  234. <div class="input-wrapper">
  235. <input id="search" type="text" placeholder="Containing text" priv>
  236. </div>
  237. <div class="sectionDescription">
  238. Only delete messages that contain the text
  239. </div>
  240. <div class="sectionDescription">
  241. <label><input id="hasLink" type="checkbox">has: link</label>
  242. </div>
  243. <div class="sectionDescription">
  244. <label><input id="hasFile" type="checkbox">has: file</label>
  245. </div>
  246. <div class="sectionDescription">
  247. <label><input id="includePinned" type="checkbox">Include pinned</label>
  248. </div>
  249. </fieldset>
  250. <hr>
  251. <fieldset>
  252. <legend>
  253. Pattern
  254. <a href="{{WIKI}}/pattern" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  255. </legend>
  256. <div class="sectionDescription">
  257. Delete messages that match the regular expression
  258. </div>
  259. <div class="input-wrapper">
  260. <span class="info">/</span>
  261. <input id="pattern" type="text" placeholder="regular expression" priv>
  262. <span class="info">/</span>
  263. </div>
  264. </fieldset>
  265. </details>
  266. <details>
  267. <summary>Messages interval</summary>
  268. <fieldset>
  269. <legend>
  270. Interval of messages
  271. <a href="{{WIKI}}/messageId" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  272. </legend>
  273. <div class="multiInput mb1">
  274. <div class="input-wrapper">
  275. <input id="minId" type="text" placeholder="After a message" priv>
  276. </div>
  277. <button id="pickMessageAfter">Pick</button>
  278. </div>
  279. <div class="multiInput">
  280. <div class="input-wrapper">
  281. <input id="maxId" type="text" placeholder="Before a message" priv>
  282. </div>
  283. <button id="pickMessageBefore">Pick</button>
  284. </div>
  285. <div class="sectionDescription">
  286. Specify an interval to delete messages.
  287. </div>
  288. </fieldset>
  289. </details>
  290. <details>
  291. <summary>Date interval</summary>
  292. <fieldset>
  293. <legend>
  294. After date
  295. <a href="{{WIKI}}/dateRange" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  296. </legend>
  297. <div class="input-wrapper mb1">
  298. <input id="minDate" type="datetime-local" title="Messages posted AFTER this date">
  299. </div>
  300. <legend>
  301. Before date
  302. <a href="{{WIKI}}/dateRange" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  303. </legend>
  304. <div class="input-wrapper">
  305. <input id="maxDate" type="datetime-local" title="Messages posted BEFORE this date">
  306. </div>
  307. <div class="sectionDescription">
  308. Delete messages that were posted between the two dates.
  309. </div>
  310. <div class="sectionDescription">
  311. * Filtering by date doesn't work if you use the "Messages interval".
  312. </div>
  313. </fieldset>
  314. </details>
  315. <hr>
  316. <details>
  317. <summary>Advanced settings</summary>
  318. <fieldset>
  319. <legend>
  320. Search delay
  321. <a href="{{WIKI}}/delay" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  322. </legend>
  323. <div class="input-wrapper">
  324. <input id="searchDelay" type="range" value="1000" step="50" min="50" max="5000">
  325. <div id="searchDelayValue"></div>
  326. </div>
  327. </fieldset>
  328. <fieldset>
  329. <legend>
  330. Delete delay
  331. <a href="{{WIKI}}/delay" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  332. </legend>
  333. <div class="input-wrapper">
  334. <input id="deleteDelay" type="range" value="1000" step="50" min="50" max="5000">
  335. <div id="deleteDelayValue"></div>
  336. </div>
  337. <br>
  338. <div class="sectionDescription">
  339. This will affect the speed in which the messages are deleted.
  340. Use the help link for more information.
  341. </div>
  342. </fieldset>
  343. </details>
  344. <hr>
  345. <div></div>
  346. <div class="info">
  347. Undiscord {{VERSION}}
  348. <br> victornpb
  349. </div>
  350. </div>
  351. <div class="main col">
  352. <div class="tbar col">
  353. <div class="row">
  354. <button id="toggleSidebar" class="sizeMedium icon">☰</button>
  355. <button id="start" class="sizeMedium danger" style="width: 150px;" title="Start the deletion process">▶︎ Delete</button>
  356. <button id="stop" class="sizeMedium" title="Stop the deletion process" disabled>🛑 Stop</button>
  357. <button id="clear" class="sizeMedium">Clear log</button>
  358. <label class="row" title="Hide sensitive information on your screen for taking screenshots">
  359. <input id="redact" type="checkbox" checked> Streamer mode
  360. </label>
  361. </div>
  362. <div class="row">
  363. <progress id="progressBar" style="display:none;"></progress>
  364. </div>
  365. </div>
  366. <pre id="logArea" class="logarea scroll">
  367. <center>
  368. <div>Star <a href="{{HOME}}" target="_blank" rel="noopener noreferrer">this project</a> on GitHub!</div>
  369. <div><a href="{{HOME}}/discussions" target="_blank" rel="noopener noreferrer">Issues or help</a></div>
  370. </center>
  371. </pre>
  372. <div class="tbar footer row">
  373. <div id="progressPercent"></div>
  374. <span class="spacer"></span>
  375. <label>
  376. <input id="autoScroll" type="checkbox" checked> Auto scroll
  377. </label>
  378. <div class="resize-handle"></div>
  379. </div>
  380. </div>
  381. </div>
  382. </div>
  383. `);
  384. const log = {
  385. debug() { return logFn ? logFn('debug', arguments) : console.debug.apply(console, arguments); },
  386. info() { return logFn ? logFn('info', arguments) : console.info.apply(console, arguments); },
  387. verb() { return logFn ? logFn('verb', arguments) : console.log.apply(console, arguments); },
  388. warn() { return logFn ? logFn('warn', arguments) : console.warn.apply(console, arguments); },
  389. error() { return logFn ? logFn('error', arguments) : console.error.apply(console, arguments); },
  390. success() { return logFn ? logFn('success', arguments) : console.info.apply(console, arguments); },
  391. };
  392. var logFn; // custom console.log function
  393. const setLogFn = (fn) => logFn = fn;
  394. // Helpers
  395. const wait = async ms => new Promise(done => setTimeout(done, ms));
  396. const msToHMS = s => `${s / 3.6e6 | 0}h ${(s % 3.6e6) / 6e4 | 0}m ${(s % 6e4) / 1000 | 0}s`;
  397. const escapeHTML = html => String(html).replace(/[&<"']/g, m => ({ '&': '&amp;', '<': '&lt;', '"': '&quot;', '\'': '&#039;' })[m]);
  398. const redact = str => `<x>${escapeHTML(str)}</x>`;
  399. const queryString = params => params.filter(p => p[1] !== undefined).map(p => p[0] + '=' + encodeURIComponent(p[1])).join('&');
  400. const ask = async msg => new Promise(resolve => setTimeout(() => resolve(window.confirm(msg)), 10));
  401. const toSnowflake = (date) => /:/.test(date) ? ((new Date(date).getTime() - 1420070400000) * Math.pow(2, 22)) : date;
  402. const replaceInterpolations = (str, obj, removeMissing = false) => str.replace(/\{\{([\w_]+)\}\}/g, (m, key) => obj[key] || (removeMissing ? '' : m));
  403. const PREFIX$1 = '[UNDISCORD]';
  404. /**
  405. * Delete all messages in a Discord channel or DM
  406. * @author Victornpb <https://www.github.com/victornpb>
  407. * @see https://github.com/victornpb/undiscord
  408. */
  409. class UndiscordCore {
  410. options = {
  411. authToken: null, // Your authorization token
  412. authorId: null, // Author of the messages you want to delete
  413. guildId: null, // Server were the messages are located
  414. channelId: null, // Channel were the messages are located
  415. minId: null, // Only delete messages after this, leave blank do delete all
  416. maxId: null, // Only delete messages before this, leave blank do delete all
  417. content: null, // Filter messages that contains this text content
  418. hasLink: null, // Filter messages that contains link
  419. hasFile: null, // Filter messages that contains file
  420. includeNsfw: null, // Search in NSFW channels
  421. includePinned: null, // Delete messages that are pinned
  422. pattern: null, // Only delete messages that match the regex (insensitive)
  423. searchDelay: null, // Delay each time we fetch for more messages
  424. deleteDelay: null, // Delay between each delete operation
  425. maxAttempt: 2, // Attempts to delete a single message if it fails
  426. askForConfirmation: true,
  427. };
  428. state = {
  429. running: false,
  430. delCount: 0,
  431. failCount: 0,
  432. grandTotal: 0,
  433. offset: 0,
  434. iterations: 0,
  435. _seachResponse: null,
  436. _messagesToDelete: [],
  437. _skippedMessages: [],
  438. };
  439. stats = {
  440. startTime: new Date(), // start time
  441. throttledCount: 0, // how many times you have been throttled
  442. throttledTotalTime: 0, // the total amount of time you spent being throttled
  443. lastPing: null, // the most recent ping
  444. avgPing: null, // average ping used to calculate the estimated remaining time
  445. etr: 0,
  446. };
  447. // events
  448. onStart = undefined;
  449. onProgress = undefined;
  450. onStop = undefined;
  451. resetState() {
  452. this.state = {
  453. running: false,
  454. delCount: 0,
  455. failCount: 0,
  456. grandTotal: 0,
  457. offset: 0,
  458. iterations: 0,
  459. _seachResponse: null,
  460. _messagesToDelete: [],
  461. _skippedMessages: [],
  462. };
  463. this.options.askForConfirmation = true;
  464. }
  465. /** Automate the deletion process of multiple channels */
  466. async runBatch(queue) {
  467. if (this.state.running) return log.error('Already running!');
  468. log.info(`Runnning batch with queue of ${queue.length} jobs`);
  469. for (let i = 0; i < queue.length; i++) {
  470. const job = queue[i];
  471. log.info('Starting job...', `(${i + 1}/${queue.length})`);
  472. // set options
  473. this.options = {
  474. ...this.options, // keep current options
  475. ...job, // override with options for that job
  476. };
  477. await this.run(true);
  478. if (!this.state.running) break;
  479. log.info('Job ended.', `(${i + 1}/${queue.length})`);
  480. this.resetState();
  481. this.options.askForConfirmation = false;
  482. this.state.running = true; // continue running
  483. }
  484. log.info('Batch finished.');
  485. this.state.running = false;
  486. }
  487. /** Start the deletion process */
  488. async run(isJob = false) {
  489. if (this.state.running && !isJob) return log.error('Already running!');
  490. this.state.running = true;
  491. this.stats.startTime = new Date();
  492. log.success(`\nStarted at ${this.stats.startTime.toLocaleString()}`);
  493. log.debug(
  494. `authorId = "${redact(this.options.authorId)}"`,
  495. `guildId = "${redact(this.options.guildId)}"`,
  496. `channelId = "${redact(this.options.channelId)}"`,
  497. `minId = "${redact(this.options.minId)}"`,
  498. `maxId = "${redact(this.options.maxId)}"`,
  499. `hasLink = ${!!this.options.hasLink}`,
  500. `hasFile = ${!!this.options.hasFile}`,
  501. );
  502. if (this.onStart) this.onStart(this.state, this.stats);
  503. do {
  504. this.state.iterations++;
  505. log.verb('Fetching messages...');
  506. // Search messages
  507. await this.search();
  508. // Process results and find which messages should be deleted
  509. await this.filterResponse();
  510. log.verb(
  511. `Grand total: ${this.state.grandTotal}`,
  512. `(Messages in current page: ${this.state._seachResponse.messages.length}`,
  513. `To be deleted: ${this.state._messagesToDelete.length}`,
  514. `Skipped: ${this.state._skippedMessages.length})`,
  515. `offset: ${this.state.offset}`
  516. );
  517. this.printStats();
  518. // Calculate estimated time
  519. this.calcEtr();
  520. log.verb(`Estimated time remaining: ${msToHMS(this.stats.etr)}`);
  521. // if there are messages to delete, delete them
  522. if (this.state._messagesToDelete.length > 0) {
  523. if (await this.confirm() === false) {
  524. this.state.running = false; // break out of a job
  525. break; // immmediately stop this iteration
  526. }
  527. await this.deleteMessagesFromList();
  528. }
  529. else if (this.state._skippedMessages.length > 0) {
  530. // There are stuff, but nothing to delete (example a page full of system messages)
  531. // check next page until we see a page with nothing in it (end of results).
  532. const oldOffset = this.state.offset;
  533. this.state.offset += this.state._skippedMessages.length;
  534. log.verb('There\'s nothing we can delete on this page, checking next page...');
  535. log.verb(`Skipped ${this.state._skippedMessages.length} out of ${this.state._seachResponse.messages.length} in this page.`, `(Offset was ${oldOffset}, ajusted to ${this.state.offset})`);
  536. }
  537. } while (this.state.running);
  538. this.stats.endTime = new Date();
  539. log.success(`Ended at ${this.stats.endTime.toLocaleString()}! Total time: ${msToHMS(this.stats.endTime.getTime() - this.stats.startTime.getTime())}`);
  540. this.printStats();
  541. log.debug(`Deleted ${this.state.delCount} messages, ${this.state.failCount} failed.\n`);
  542. if (this.onStop) this.onStop(this.state, this.stats);
  543. }
  544. stop() {
  545. this.state.running = false;
  546. }
  547. /** Calculate the estimated time remaining based on the current stats */
  548. calcEtr() {
  549. this.stats.etr = (this.options.searchDelay * Math.round(this.state.grandTotal / 25)) + ((this.options.deleteDelay + this.stats.avgPing) * this.state.grandTotal);
  550. }
  551. /** As for confirmation in the beggining process */
  552. async confirm() {
  553. if (!this.options.askForConfirmation) return true;
  554. log.verb('Waiting for your confirmation...');
  555. const preview = this.state._messagesToDelete.map(m => `${m.author.username}#${m.author.discriminator}: ${m.attachments.length ? '[ATTACHMENTS]' : m.content}`).join('\n');
  556. const answer = await ask(
  557. `Do you want to delete ~${this.state.grandTotal} messages? (Estimated time: ${msToHMS(this.stats.etr)})` +
  558. '(The actual number of messages may be less, depending if you\'re using filters to skip some messages)' +
  559. '\n\n---- Preview ----\n' +
  560. preview
  561. );
  562. if (!answer) {
  563. log.error('Aborted by you!');
  564. return false;
  565. }
  566. else {
  567. log.verb('OK');
  568. this.options.askForConfirmation = false; // do not ask for confirmation again on the next request
  569. return true;
  570. }
  571. }
  572. async search() {
  573. let API_SEARCH_URL;
  574. if (this.options.guildId === '@me') API_SEARCH_URL = `https://discord.com/api/v9/channels/${this.options.channelId}/messages/`; // DMs
  575. else API_SEARCH_URL = `https://discord.com/api/v9/guilds/${this.options.guildId}/messages/`; // Server
  576. let resp;
  577. try {
  578. this.beforeRequest();
  579. resp = await fetch(API_SEARCH_URL + 'search?' + queryString([
  580. ['author_id', this.options.authorId || undefined],
  581. ['channel_id', (this.options.guildId !== '@me' ? this.options.channelId : undefined) || undefined],
  582. ['min_id', this.options.minId ? toSnowflake(this.options.minId) : undefined],
  583. ['max_id', this.options.maxId ? toSnowflake(this.options.maxId) : undefined],
  584. ['sort_by', 'timestamp'],
  585. ['sort_order', 'desc'],
  586. ['offset', this.state.offset],
  587. ['has', this.options.hasLink ? 'link' : undefined],
  588. ['has', this.options.hasFile ? 'file' : undefined],
  589. ['content', this.options.content || undefined],
  590. ['include_nsfw', this.options.includeNsfw ? true : undefined],
  591. ]), {
  592. headers: {
  593. 'Authorization': this.options.authToken,
  594. }
  595. });
  596. this.afterRequest();
  597. } catch (err) {
  598. this.state.running = false;
  599. return log.error('Search request threw an error:', err);
  600. }
  601. // not indexed yet
  602. if (resp.status === 202) {
  603. const w = (await resp.json()).retry_after * 1000;
  604. this.stats.throttledCount++;
  605. this.stats.throttledTotalTime += w;
  606. log.warn(`This channel isn't indexed yet. Waiting ${w}ms for discord to index it...`);
  607. await wait(w);
  608. return await this.search();
  609. }
  610. if (!resp.ok) {
  611. // searching messages too fast
  612. if (resp.status === 429) {
  613. const w = (await resp.json()).retry_after * 1000;
  614. this.stats.throttledCount++;
  615. this.stats.throttledTotalTime += w;
  616. this.stats.searchDelay += w; // increase delay
  617. log.warn(`Being rate limited by the API for ${w}ms! Increasing search delay...`);
  618. this.printStats();
  619. log.verb(`Cooling down for ${w * 2}ms before retrying...`);
  620. await wait(w * 2);
  621. return await this.search();
  622. } else {
  623. this.state.running = false;
  624. return log.error(`Error searching messages, API responded with status ${resp.status}!\n`, await resp.json());
  625. }
  626. }
  627. const data = await resp.json();
  628. this.state._seachResponse = data;
  629. console.log(PREFIX$1, 'search', data);
  630. return data;
  631. }
  632. async filterResponse() {
  633. const data = this.state._seachResponse;
  634. // the search total will decrease as we delete stuff
  635. const total = data.total_results;
  636. if (total > this.state.grandTotal) this.state.grandTotal = total;
  637. // search returns messages near the the actual message, only get the messages we searched for.
  638. const discoveredMessages = data.messages.map(convo => convo.find(message => message.hit === true));
  639. // we can only delete some types of messages, system messages are not deletable.
  640. let messagesToDelete = discoveredMessages;
  641. messagesToDelete = messagesToDelete.filter(msg => msg.type === 0 || (msg.type >= 6 && msg.type <= 21));
  642. messagesToDelete = messagesToDelete.filter(msg => msg.pinned ? this.options.includePinned : true);
  643. // custom filter of messages
  644. try {
  645. const regex = new RegExp(this.options.pattern, 'i');
  646. messagesToDelete = messagesToDelete.filter(msg => regex.test(msg.content));
  647. } catch (e) {
  648. log.warn('Ignoring RegExp because pattern is malformed!', e);
  649. }
  650. // create an array containing everything we skipped. (used to calculate offset for next searches)
  651. const skippedMessages = discoveredMessages.filter(msg => !messagesToDelete.find(m => m.id === msg.id));
  652. this.state._messagesToDelete = messagesToDelete;
  653. this.state._skippedMessages = skippedMessages;
  654. console.log(PREFIX$1, 'filterResponse', this.state);
  655. }
  656. async deleteMessagesFromList() {
  657. for (let i = 0; i < this.state._messagesToDelete.length; i++) {
  658. const message = this.state._messagesToDelete[i];
  659. if (!this.state.running) return log.error('Stopped by you!');
  660. log.debug(
  661. // `${((this.state.delCount + 1) / this.state.grandTotal * 100).toFixed(2)}%`,
  662. `[${this.state.delCount + 1}/${this.state.grandTotal}] `+
  663. `<sup>${new Date(message.timestamp).toLocaleString()}</sup> `+
  664. `<b>${redact(message.author.username + '#' + message.author.discriminator)}</b>`+
  665. `: <i>${redact(message.content).replace(/\n/g, '↵')}</i>`+
  666. (message.attachments.length ? redact(JSON.stringify(message.attachments)) : ''),
  667. `<sup>{ID:${redact(message.id)}}</sup>`
  668. );
  669. // Delete a single message (with retry)
  670. let attempt = 0;
  671. while (attempt < this.options.maxAttempt) {
  672. const result = await this.deleteMessage(message);
  673. if (result === 'RETRY') {
  674. attempt++;
  675. log.verb(`Retrying in ${this.options.deleteDelay}ms... (${attempt}/${this.options.maxAttempt})`);
  676. await wait(this.options.deleteDelay);
  677. }
  678. else break;
  679. }
  680. this.calcEtr();
  681. if (this.onProgress) this.onProgress(this.state, this.stats);
  682. await wait(this.options.deleteDelay);
  683. }
  684. }
  685. async deleteMessage(message) {
  686. const API_DELETE_URL = `https://discord.com/api/v9/channels/${message.channel_id}/messages/${message.id}`;
  687. let resp;
  688. try {
  689. this.beforeRequest();
  690. resp = await fetch(API_DELETE_URL, {
  691. method: 'DELETE',
  692. headers: {
  693. 'Authorization': this.options.authToken,
  694. },
  695. });
  696. this.afterRequest();
  697. } catch (err) {
  698. // no response error (e.g. network error)
  699. log.error('Delete request throwed an error:', err);
  700. log.verb('Related object:', redact(JSON.stringify(message)));
  701. this.state.failCount++;
  702. return 'FAILED';
  703. }
  704. if (!resp.ok) {
  705. if (resp.status === 429) {
  706. // deleting messages too fast
  707. const w = (await resp.json()).retry_after * 1000;
  708. this.stats.throttledCount++;
  709. this.stats.throttledTotalTime += w;
  710. this.options.deleteDelay = w; // increase delay
  711. log.warn(`Being rate limited by the API for ${w}ms! Adjusted delete delay to ${this.options.deleteDelay}ms.`);
  712. this.printStats();
  713. log.verb(`Cooling down for ${w * 2}ms before retrying...`);
  714. await wait(w * 2);
  715. return 'RETRY';
  716. } else {
  717. // other error
  718. log.error(`Error deleting message, API responded with status ${resp.status}!`, await resp.json());
  719. log.verb('Related object:', redact(JSON.stringify(message)));
  720. this.state.failCount++;
  721. return 'FAILED';
  722. }
  723. }
  724. this.state.delCount++;
  725. return 'OK';
  726. }
  727. #beforeTs = 0; // used to calculate latency
  728. beforeRequest() {
  729. this.#beforeTs = Date.now();
  730. }
  731. afterRequest() {
  732. this.stats.lastPing = (Date.now() - this.#beforeTs);
  733. this.stats.avgPing = this.stats.avgPing > 0 ? (this.stats.avgPing * 0.9) + (this.stats.lastPing * 0.1) : this.stats.lastPing;
  734. }
  735. printStats() {
  736. log.verb(
  737. `Delete delay: ${this.options.deleteDelay}ms, Search delay: ${this.options.searchDelay}ms`,
  738. `Last Ping: ${this.stats.lastPing}ms, Average Ping: ${this.stats.avgPing | 0}ms`,
  739. );
  740. log.verb(
  741. `Rate Limited: ${this.stats.throttledCount} times.`,
  742. `Total time throttled: ${msToHMS(this.stats.throttledTotalTime)}.`
  743. );
  744. }
  745. }
  746. const MOVE = 0;
  747. const RESIZE_T = 1;
  748. const RESIZE_B = 2;
  749. const RESIZE_L = 4;
  750. const RESIZE_R = 8;
  751. const RESIZE_TL = RESIZE_T + RESIZE_L;
  752. const RESIZE_TR = RESIZE_T + RESIZE_R;
  753. const RESIZE_BL = RESIZE_B + RESIZE_L;
  754. const RESIZE_BR = RESIZE_B + RESIZE_R;
  755. /**
  756. * Make an element draggable/resizable
  757. * @author Victor N. wwww.vitim.us
  758. */
  759. class DragResize {
  760. constructor({ elm, moveHandle, options }) {
  761. this.options = defaultArgs({
  762. enabledDrag: true,
  763. enabledResize: true,
  764. minWidth: 200,
  765. maxWidth: Infinity,
  766. minHeight: 100,
  767. maxHeight: Infinity,
  768. dragAllowX: true,
  769. dragAllowY: true,
  770. resizeAllowX: true,
  771. resizeAllowY: true,
  772. draggingClass: 'drag',
  773. useMouseEvents: true,
  774. useTouchEvents: true,
  775. createHandlers: true,
  776. }, options);
  777. Object.assign(this, options);
  778. options = undefined;
  779. elm.style.position = 'fixed';
  780. this.drag_m = new Draggable(elm, moveHandle, MOVE, this.options);
  781. if (this.options.createHandlers) {
  782. this.el_t = createElement('div', { name: 'grab-t' }, elm);
  783. this.drag_t = new Draggable(elm, this.el_t, RESIZE_T, this.options);
  784. this.el_r = createElement('div', { name: 'grab-r' }, elm);
  785. this.drag_r = new Draggable(elm, this.el_r, RESIZE_R, this.options);
  786. this.el_b = createElement('div', { name: 'grab-b' }, elm);
  787. this.drag_b = new Draggable(elm, this.el_b, RESIZE_B, this.options);
  788. this.el_l = createElement('div', { name: 'grab-l' }, elm);
  789. this.drag_l = new Draggable(elm, this.el_l, RESIZE_L, this.options);
  790. this.el_tl = createElement('div', { name: 'grab-tl' }, elm);
  791. this.drag_tl = new Draggable(elm, this.el_tl, RESIZE_TL, this.options);
  792. this.el_tr = createElement('div', { name: 'grab-tr' }, elm);
  793. this.drag_tr = new Draggable(elm, this.el_tr, RESIZE_TR, this.options);
  794. this.el_br = createElement('div', { name: 'grab-br' }, elm);
  795. this.drag_br = new Draggable(elm, this.el_br, RESIZE_BR, this.options);
  796. this.el_bl = createElement('div', { name: 'grab-bl' }, elm);
  797. this.drag_bl = new Draggable(elm, this.el_bl, RESIZE_BL, this.options);
  798. }
  799. }
  800. }
  801. class Draggable {
  802. constructor(targetElm, handleElm, op, options) {
  803. Object.assign(this, options);
  804. options = undefined;
  805. this._targetElm = targetElm;
  806. this._handleElm = handleElm;
  807. let vw = window.innerWidth;
  808. let vh = window.innerHeight;
  809. let initialX, initialY, initialT, initialL, initialW, initialH;
  810. const clamp = (value, min, max) => value < min ? min : value > max ? max : value;
  811. const moveOp = (x, y) => {
  812. const deltaX = (x - initialX);
  813. const deltaY = (y - initialY);
  814. const t = clamp(initialT + deltaY, 0, vh - initialH);
  815. const l = clamp(initialL + deltaX, 0, vw - initialW);
  816. this._targetElm.style.top = t + 'px';
  817. this._targetElm.style.left = l + 'px';
  818. };
  819. const resizeOp = (x, y) => {
  820. x = clamp(x, 0, vw);
  821. y = clamp(y, 0, vh);
  822. const deltaX = (x - initialX);
  823. const deltaY = (y - initialY);
  824. const resizeDirX = (op & RESIZE_L) ? -1 : 1;
  825. const resizeDirY = (op & RESIZE_T) ? -1 : 1;
  826. const deltaXMax = (this.maxWidth - initialW);
  827. const deltaXMin = (this.minWidth - initialW);
  828. const deltaYMax = (this.maxHeight - initialH);
  829. const deltaYMin = (this.minHeight - initialH);
  830. const t = initialT + clamp(deltaY * resizeDirY, deltaYMin, deltaYMax) * resizeDirY;
  831. const l = initialL + clamp(deltaX * resizeDirX, deltaXMin, deltaXMax) * resizeDirX;
  832. const w = initialW + clamp(deltaX * resizeDirX, deltaXMin, deltaXMax);
  833. const h = initialH + clamp(deltaY * resizeDirY, deltaYMin, deltaYMax);
  834. if (op & RESIZE_T) { // resize ↑
  835. this._targetElm.style.top = t + 'px';
  836. this._targetElm.style.height = h + 'px';
  837. }
  838. if (op & RESIZE_B) { // resize ↓
  839. this._targetElm.style.height = h + 'px';
  840. }
  841. if (op & RESIZE_L) { // resize ←
  842. this._targetElm.style.left = l + 'px';
  843. this._targetElm.style.width = w + 'px';
  844. }
  845. if (op & RESIZE_R) { // resize →
  846. this._targetElm.style.width = w + 'px';
  847. }
  848. };
  849. let operation = op === MOVE ? moveOp : resizeOp;
  850. function dragStartHandler(e) {
  851. const touch = e.type === 'touchstart';
  852. if ((e.buttons === 1 || e.which === 1) || touch) {
  853. e.preventDefault();
  854. const x = touch ? e.touches[0].clientX : e.clientX;
  855. const y = touch ? e.touches[0].clientY : e.clientY;
  856. initialX = x;
  857. initialY = y;
  858. vw = window.innerWidth;
  859. vh = window.innerHeight;
  860. initialT = this._targetElm.offsetTop;
  861. initialL = this._targetElm.offsetLeft;
  862. initialW = this._targetElm.clientWidth;
  863. initialH = this._targetElm.clientHeight;
  864. if (this.useMouseEvents) {
  865. document.addEventListener('mousemove', this._dragMoveHandler);
  866. document.addEventListener('mouseup', this._dragEndHandler);
  867. }
  868. if (this.useTouchEvents) {
  869. document.addEventListener('touchmove', this._dragMoveHandler, { passive: false });
  870. document.addEventListener('touchend', this._dragEndHandler);
  871. }
  872. this._targetElm.classList.add(this.draggingClass);
  873. }
  874. }
  875. function dragMoveHandler(e) {
  876. e.preventDefault();
  877. let x, y;
  878. const touch = e.type === 'touchmove';
  879. if (touch) {
  880. const t = e.touches[0];
  881. x = t.clientX;
  882. y = t.clientY;
  883. } else { //mouse
  884. // If the button is not down, dispatch a "fake" mouse up event, to stop listening to mousemove
  885. // This happens when the mouseup is not captured (outside the browser)
  886. if ((e.buttons || e.which) !== 1) {
  887. this._dragEndHandler();
  888. return;
  889. }
  890. x = e.clientX;
  891. y = e.clientY;
  892. }
  893. // perform drag / resize operation
  894. operation(x, y);
  895. }
  896. function dragEndHandler(e) {
  897. if (this.useMouseEvents) {
  898. document.removeEventListener('mousemove', this._dragMoveHandler);
  899. document.removeEventListener('mouseup', this._dragEndHandler);
  900. }
  901. if (this.useTouchEvents) {
  902. document.removeEventListener('touchmove', this._dragMoveHandler);
  903. document.removeEventListener('touchend', this._dragEndHandler);
  904. }
  905. this._targetElm.classList.remove(this.draggingClass);
  906. }
  907. // We need to bind the handlers to this instance
  908. this._dragStartHandler = dragStartHandler.bind(this);
  909. this._dragMoveHandler = dragMoveHandler.bind(this);
  910. this._dragEndHandler = dragEndHandler.bind(this);
  911. this.enable();
  912. }
  913. /** Turn on the drag and drop of the instance */
  914. enable() {
  915. this.destroy(); // prevent events from getting binded twice
  916. if (this.useMouseEvents) this._handleElm.addEventListener('mousedown', this._dragStartHandler);
  917. if (this.useTouchEvents) this._handleElm.addEventListener('touchstart', this._dragStartHandler, { passive: false });
  918. }
  919. /** Teardown all events bound to the document and elements. You can resurrect this instance by calling enable() */
  920. destroy() {
  921. this._targetElm.classList.remove(this.draggingClass);
  922. if (this.useMouseEvents) {
  923. this._handleElm.removeEventListener('mousedown', this._dragStartHandler);
  924. document.removeEventListener('mousemove', this._dragMoveHandler);
  925. document.removeEventListener('mouseup', this._dragEndHandler);
  926. }
  927. if (this.useTouchEvents) {
  928. this._handleElm.removeEventListener('touchstart', this._dragStartHandler);
  929. document.removeEventListener('touchmove', this._dragMoveHandler);
  930. document.removeEventListener('touchend', this._dragEndHandler);
  931. }
  932. }
  933. }
  934. function createElement(tag='div', attrs, parent) {
  935. const elm = document.createElement(tag);
  936. if (attrs) Object.entries(attrs).forEach(([k, v]) => elm.setAttribute(k, v));
  937. if (parent) parent.appendChild(elm);
  938. return elm;
  939. }
  940. function defaultArgs(defaults, options) {
  941. function isObj(x) { return x !== null && typeof x === 'object'; }
  942. function hasOwn(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  943. if (isObj(options)) for (let prop in defaults) {
  944. if (hasOwn(defaults, prop) && hasOwn(options, prop) && options[prop] !== undefined) {
  945. if (isObj(defaults[prop])) defaultArgs(defaults[prop], options[prop]);
  946. else defaults[prop] = options[prop];
  947. }
  948. }
  949. return defaults;
  950. }
  951. function createElm(html) {
  952. const temp = document.createElement('div');
  953. temp.innerHTML = html;
  954. return temp.removeChild(temp.firstElementChild);
  955. }
  956. function insertCss(css) {
  957. const style = document.createElement('style');
  958. style.appendChild(document.createTextNode(css));
  959. document.head.appendChild(style);
  960. return style;
  961. }
  962. const messagePickerCss = `
  963. body.undiscord-pick-message [data-list-id="chat-messages"] {
  964. background-color: var(--background-secondary-alt);
  965. box-shadow: inset 0 0 0px 2px var(--button-outline-brand-border);
  966. }
  967. body.undiscord-pick-message [id^="message-content-"]:hover {
  968. cursor: pointer;
  969. cursor: cell;
  970. background: var(--background-message-automod-hover);
  971. }
  972. body.undiscord-pick-message [id^="message-content-"]:hover::after {
  973. position: absolute;
  974. top: calc(50% - 11px);
  975. left: 4px;
  976. z-index: 1;
  977. width: 65px;
  978. height: 22px;
  979. line-height: 22px;
  980. font-family: var(--font-display);
  981. background-color: var(--button-secondary-background);
  982. color: var(--header-secondary);
  983. font-size: 12px;
  984. font-weight: 500;
  985. text-transform: uppercase;
  986. text-align: center;
  987. border-radius: 3px;
  988. content: 'This 👉';
  989. }
  990. body.undiscord-pick-message.before [id^="message-content-"]:hover::after {
  991. content: 'Before 👆';
  992. }
  993. body.undiscord-pick-message.after [id^="message-content-"]:hover::after {
  994. content: 'After 👇';
  995. }
  996. `;
  997. const messagePicker = {
  998. init() {
  999. insertCss(messagePickerCss);
  1000. },
  1001. grab(auxiliary) {
  1002. return new Promise((resolve, reject) => {
  1003. document.body.classList.add('undiscord-pick-message');
  1004. if (auxiliary) document.body.classList.add(auxiliary);
  1005. function clickHandler(e) {
  1006. const message = e.target.closest('[id^="message-content-"]');
  1007. if (message) {
  1008. e.preventDefault();
  1009. e.stopPropagation();
  1010. e.stopImmediatePropagation();
  1011. if (auxiliary) document.body.classList.remove(auxiliary);
  1012. document.body.classList.remove('undiscord-pick-message');
  1013. document.removeEventListener('click', clickHandler);
  1014. try {
  1015. resolve(message.id.match(/message-content-(\d+)/)[1]);
  1016. } catch (e) {
  1017. resolve(null);
  1018. }
  1019. }
  1020. }
  1021. document.addEventListener('click', clickHandler);
  1022. });
  1023. }
  1024. };
  1025. window.messagePicker = messagePicker;
  1026. function getToken() {
  1027. window.dispatchEvent(new Event('beforeunload'));
  1028. const LS = document.body.appendChild(document.createElement('iframe')).contentWindow.localStorage;
  1029. return JSON.parse(LS.token);
  1030. }
  1031. function getAuthorId() {
  1032. const LS = document.body.appendChild(document.createElement('iframe')).contentWindow.localStorage;
  1033. return JSON.parse(LS.user_id_cache);
  1034. }
  1035. function getGuildId() {
  1036. const m = location.href.match(/channels\/([\w@]+)\/(\d+)/);
  1037. if (m) return m[1];
  1038. else alert('Could not the Guild ID!\nPlease make sure you are on a Server or DM.');
  1039. }
  1040. function getChannelId() {
  1041. const m = location.href.match(/channels\/([\w@]+)\/(\d+)/);
  1042. if (m) return m[2];
  1043. else alert('Could not the Channel ID!\nPlease make sure you are on a Channel or DM.');
  1044. }
  1045. const PREFIX = '[UNDISCORD]';
  1046. // -------------------------- User interface ------------------------------- //
  1047. // links
  1048. const HOME = 'https://github.com/victornpb/undiscord';
  1049. const WIKI = 'https://github.com/victornpb/undiscord/wiki';
  1050. const undiscordCore = new UndiscordCore();
  1051. messagePicker.init();
  1052. const ui = {
  1053. undiscordWindow: null,
  1054. undiscordBtn: null,
  1055. logArea: null,
  1056. autoScroll: null,
  1057. // progress handler
  1058. progressMain: null,
  1059. progressIcon: null,
  1060. percent: null,
  1061. };
  1062. const $ = s => ui.undiscordWindow.querySelector(s);
  1063. function initUI() {
  1064. insertCss(themeCss);
  1065. insertCss(mainCss);
  1066. insertCss(dragCss);
  1067. // create undiscord window
  1068. const undiscordUI = replaceInterpolations(undiscordTemplate, {
  1069. VERSION,
  1070. HOME,
  1071. WIKI,
  1072. });
  1073. ui.undiscordWindow = createElm(undiscordUI);
  1074. document.body.appendChild(ui.undiscordWindow);
  1075. // enable drag and resize on undiscord window
  1076. new DragResize({ elm: ui.undiscordWindow, moveHandle: $('.header') });
  1077. // create undiscord Trash icon
  1078. ui.undiscordBtn = createElm(buttonHtml);
  1079. ui.undiscordBtn.onclick = toggleWindow;
  1080. function mountBtn() {
  1081. const toolbar = document.querySelector('#app-mount [class^=toolbar]');
  1082. if (toolbar) toolbar.appendChild(ui.undiscordBtn);
  1083. }
  1084. mountBtn();
  1085. // watch for changes and re-mount button if necessary
  1086. const discordElm = document.querySelector('#app-mount');
  1087. let observerThrottle = null;
  1088. const observer = new MutationObserver((_mutationsList, _observer) => {
  1089. if (observerThrottle) return;
  1090. observerThrottle = setTimeout(() => {
  1091. observerThrottle = null;
  1092. if (!discordElm.contains(ui.undiscordBtn)) mountBtn(); // re-mount the button to the toolbar
  1093. }, 3000);
  1094. });
  1095. observer.observe(discordElm, { attributes: false, childList: true, subtree: true });
  1096. function toggleWindow() {
  1097. if (ui.undiscordWindow.style.display !== 'none') {
  1098. ui.undiscordWindow.style.display = 'none';
  1099. ui.undiscordBtn.style.color = 'var(--interactive-normal)';
  1100. }
  1101. else {
  1102. ui.undiscordWindow.style.display = '';
  1103. ui.undiscordBtn.style.color = 'var(--interactive-active)';
  1104. }
  1105. }
  1106. // cached elements
  1107. ui.logArea = $('#logArea');
  1108. ui.autoScroll = $('#autoScroll');
  1109. ui.progressMain = $('#progressBar');
  1110. ui.progressIcon = ui.undiscordBtn.querySelector('progress');
  1111. ui.percent = $('#progressPercent');
  1112. // register event listeners
  1113. $('#hide').onclick = toggleWindow;
  1114. $('#toggleSidebar').onclick = ()=> ui.undiscordWindow.classList.toggle('hide-sidebar');
  1115. $('button#start').onclick = startAction;
  1116. $('button#stop').onclick = stopAction;
  1117. $('button#clear').onclick = () => ui.logArea.innerHTML = '';
  1118. $('button#getAuthor').onclick = () => $('input#authorId').value = getAuthorId();
  1119. $('button#getGuild').onclick = () => {
  1120. const guildId = $('input#guildId').value = getGuildId();
  1121. if (guildId === '@me') $('input#channelId').value = getChannelId();
  1122. };
  1123. $('button#getChannel').onclick = () => {
  1124. $('input#channelId').value = getChannelId();
  1125. $('input#guildId').value = getGuildId();
  1126. };
  1127. $('#redact').onchange = () => {
  1128. const b = ui.undiscordWindow.classList.toggle('redact');
  1129. if (b) alert('This mode will attempt to hide personal information, so you can screen share / take screenshots.\nAlways double check you are not sharing sensitive information!');
  1130. };
  1131. $('#pickMessageAfter').onclick = async () => {
  1132. alert('Select a message on the chat.\nThe message below it will be deleted.');
  1133. toggleWindow();
  1134. const id = await messagePicker.grab('after');
  1135. if (id) $('input#minId').value = id;
  1136. toggleWindow();
  1137. };
  1138. $('#pickMessageBefore').onclick = async () => {
  1139. alert('Select a message on the chat.\nThe message above it will be deleted.');
  1140. toggleWindow();
  1141. const id = await messagePicker.grab('before');
  1142. if (id) $('input#maxId').value = id;
  1143. toggleWindow();
  1144. };
  1145. // sync delays
  1146. $('input#searchDelay').onchange = (e) => {
  1147. const v = parseInt(e.target.value);
  1148. if (v) undiscordCore.options.searchDelay = v;
  1149. };
  1150. $('input#deleteDelay').onchange = (e) => {
  1151. const v = parseInt(e.target.value);
  1152. if (v) undiscordCore.options.deleteDelay = v;
  1153. };
  1154. $('input#searchDelay').addEventListener('input', (event) => {
  1155. $('div#searchDelayValue').textContent = event.target.value + 'ms';
  1156. });
  1157. $('input#deleteDelay').addEventListener('input', (event) => {
  1158. $('div#deleteDelayValue').textContent = event.target.value + 'ms';
  1159. });
  1160. // import json
  1161. const fileSelection = $('input#importJsonInput');
  1162. // $('button#importJsonBtn').onclick = () => {
  1163. // fileSelection.click();
  1164. // };
  1165. fileSelection.onchange = async () => {
  1166. const files = fileSelection.files;
  1167. // No files added
  1168. if (files.length === 0) return log.warn('No file selected.');
  1169. // Get channel id field to set it later
  1170. const channelIdField = $('input#channelId');
  1171. // Force the guild id to be ourself (@me)
  1172. const guildIdField = $('input#guildId');
  1173. guildIdField.value = '@me';
  1174. // Set author id in case its not set already
  1175. $('input#authorId').value = getAuthorId();
  1176. try {
  1177. const file = files[0];
  1178. const text = await file.text();
  1179. const json = JSON.parse(text);
  1180. const channelIds = Object.keys(json);
  1181. channelIdField.value = channelIds.join(',');
  1182. log.info(`Loaded ${channelIds.length} channels.`);
  1183. } catch(err) {
  1184. log.error('Error parsing file!', err);
  1185. }
  1186. };
  1187. // redirect console logs to inside the window after setting up the UI
  1188. setLogFn(printLog);
  1189. setupUndiscordCore();
  1190. }
  1191. function printLog(type = '', args) {
  1192. ui.logArea.insertAdjacentHTML('beforeend', `<div class="log log-${type}">${Array.from(args).map(o => typeof o === 'object' ? JSON.stringify(o, o instanceof Error && Object.getOwnPropertyNames(o)) : o).join('\t')}</div>`);
  1193. if (ui.autoScroll.checked) ui.logArea.querySelector('div:last-child').scrollIntoView(false);
  1194. }
  1195. function setupUndiscordCore() {
  1196. undiscordCore.onStart = (state, stats) => {
  1197. console.log(PREFIX, 'onStart', state, stats);
  1198. $('#start').disabled = true;
  1199. $('#stop').disabled = false;
  1200. ui.undiscordBtn.classList.add('running');
  1201. ui.progressMain.style.display = 'block';
  1202. ui.percent.style.display = 'block';
  1203. };
  1204. undiscordCore.onProgress = (state, stats) => {
  1205. console.log(PREFIX, 'onProgress', state, stats);
  1206. let max = state.grandTotal;
  1207. const value = state.delCount + state.failCount;
  1208. max = Math.max(max, value, 0); // clamp max
  1209. // status bar
  1210. const percent = value >= 0 && max ? Math.round(value / max * 100) + '%' : '';
  1211. const elapsed = msToHMS(Date.now() - stats.startTime.getTime());
  1212. const remaining = msToHMS(stats.etr);
  1213. ui.percent.innerHTML = `${percent} (${value}/${max}) Elapsed: ${elapsed} Remaining: ${remaining}`;
  1214. ui.progressIcon.value = value;
  1215. ui.progressMain.value = value;
  1216. // indeterminate progress bar
  1217. if (max) {
  1218. ui.progressIcon.setAttribute('max', max);
  1219. ui.progressMain.setAttribute('max', max);
  1220. } else {
  1221. ui.progressIcon.removeAttribute('value');
  1222. ui.progressMain.removeAttribute('value');
  1223. ui.percent.innerHTML = '...';
  1224. }
  1225. // update delays
  1226. const searchDelayInput = $('input#searchDelay');
  1227. searchDelayInput.value = undiscordCore.options.searchDelay;
  1228. $('div#searchDelayValue').textContent = undiscordCore.options.searchDelay+'ms';
  1229. const deleteDelayInput = $('input#deleteDelay');
  1230. deleteDelayInput.value = undiscordCore.options.deleteDelay;
  1231. $('div#deleteDelayValue').textContent = undiscordCore.options.deleteDelay+'ms';
  1232. };
  1233. undiscordCore.onStop = (state, stats) => {
  1234. console.log(PREFIX, 'onStop', state, stats);
  1235. $('#start').disabled = false;
  1236. $('#stop').disabled = true;
  1237. ui.undiscordBtn.classList.remove('running');
  1238. ui.progressMain.style.display = 'none';
  1239. ui.percent.style.display = 'none';
  1240. };
  1241. }
  1242. async function startAction() {
  1243. console.log(PREFIX, 'startAction');
  1244. // general
  1245. let authToken;
  1246. try {
  1247. authToken = getToken();
  1248. } catch (err) {
  1249. console.error(err);
  1250. log.error(err);
  1251. }
  1252. const authorId = $('input#authorId').value.trim();
  1253. const guildId = $('input#guildId').value.trim();
  1254. const channelIds = $('input#channelId').value.trim().split(/\s*,\s*/);
  1255. const includeNsfw = $('input#includeNsfw').checked;
  1256. // filter
  1257. const content = $('input#search').value.trim();
  1258. const hasLink = $('input#hasLink').checked;
  1259. const hasFile = $('input#hasFile').checked;
  1260. const includePinned = $('input#includePinned').checked;
  1261. const pattern = $('input#pattern').value;
  1262. // message interval
  1263. const minId = $('input#minId').value.trim();
  1264. const maxId = $('input#maxId').value.trim();
  1265. // date range
  1266. const minDate = $('input#minDate').value.trim();
  1267. const maxDate = $('input#maxDate').value.trim();
  1268. //advanced
  1269. const searchDelay = parseInt($('input#searchDelay').value.trim());
  1270. const deleteDelay = parseInt($('input#deleteDelay').value.trim());
  1271. // clear logArea
  1272. ui.logArea.innerHTML = '';
  1273. // validate input
  1274. if (!authToken) return log.error('Could not detect the authorization token!') || log.info('Please make sure Undiscord is up to date');
  1275. else if (!guildId) return log.error('You must provide a Server ID!');
  1276. undiscordCore.resetState();
  1277. undiscordCore.options = {
  1278. ...undiscordCore.options,
  1279. authToken,
  1280. authorId,
  1281. guildId,
  1282. channelId: channelIds.length === 1 ? channelIds[0] : undefined, // single or multiple channel
  1283. minId: minId || minDate,
  1284. maxId: maxId || maxDate,
  1285. content,
  1286. hasLink,
  1287. hasFile,
  1288. includeNsfw,
  1289. includePinned,
  1290. pattern,
  1291. searchDelay,
  1292. deleteDelay,
  1293. // maxAttempt: 2,
  1294. };
  1295. if (channelIds.length > 1) {
  1296. const jobs = channelIds.map(ch => ({
  1297. guildId: guildId,
  1298. channelId: ch,
  1299. }));
  1300. try {
  1301. undiscordCore.runBatch(jobs);
  1302. } catch (err) {
  1303. console.error(err);
  1304. log.error(err);
  1305. }
  1306. }
  1307. // single channel
  1308. else {
  1309. try {
  1310. undiscordCore.run();
  1311. } catch (err) {
  1312. console.error(err);
  1313. log.error(err);
  1314. }
  1315. }
  1316. }
  1317. function stopAction() {
  1318. console.log(PREFIX, 'stopAction');
  1319. undiscordCore.stop();
  1320. }
  1321. // ---- END Undiscord ----
  1322. initUI();
  1323. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址