TweetXer

Delete all your Tweets for free.

当前为 2023-09-30 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name TweetXer
  3. // @namespace https://gist.github.com/lucahammer/a4d1e957ec9e061e3cccafcbed599e16/
  4. // @version 0.3
  5. // @description Delete all your Tweets for free.
  6. // @author Luca
  7. // @match https://twitter.com/*
  8. // @icon https://www.google.com/s2/favicons?domain=twitter.com
  9. // @license MIT
  10. // @grant unsafeWindow
  11. // ==/UserScript==
  12.  
  13. /*
  14. TweetXer
  15.  
  16. You can use this script to delete all your Tweets. Even if they don't show up on your profile. But you need your Data Export for it to work.
  17. Because this automates the deletion, it may get your account banned. Not that bad. Copies of your Tweets may still exist on backups and so on.
  18.  
  19. # Usage
  20. 0. Log into your Twitter account
  21. 1. You must have at least one visible Tweet on your profile. Post a new one, if there isn't one.
  22. 2. Open the browser console (F12)
  23. 3. Paste the whole script into the console and press enter
  24. 4. A light blue bar appears at the top of the window
  25. 5. Use the file picker to select your tweets.js
  26. 6. Wait a long time for all your Tweets to vanish
  27.  
  28. If the process is interrupted at any time, you can enter how many Tweets have been deleted in the previous run to not start at zero again.
  29.  
  30. # How it works
  31. Never use something like this from an untrusted source. The script intercepts requests from your browser to Twitter and replaces the Tweet-IDs
  32. with IDs from your tweets.js file. This allows it to access the old Tweets and delete them.
  33.  
  34. XHR interception inspired by https://github.com/ttodua/Tamper-Request-Javascript-Tool
  35. Faster deletion inspired by https://github.com/Lyfhael/DeleteTweets
  36.  
  37. Copyright 2023 Nobody
  38. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  39. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  40. */
  41.  
  42. var TweetsXer = {
  43. allowed_requests: [],
  44. dId: "exportUpload",
  45. tIds: [],
  46. tId: "",
  47. ratelimitreset: 0,
  48. more: '[data-testid="tweet"] [aria-label="More"][data-testid="caret"]',
  49. skip: 0,
  50. total: 0,
  51. dCount: 0,
  52. lastHeaders: {},
  53. deleteURL: 'https://twitter.com/i/api/graphql/VaenaVgh5q5ih7kvyVjgtg/DeleteTweet',
  54. unfavURL: 'https://twitter.com/i/api/graphql/ZYKSe-w7KEslx3JhSIk5LA/UnfavoriteTweet',
  55. username: '',
  56. action: '',
  57.  
  58. init() {
  59. // document.querySelector('header>div>div').setAttribute('class', '')
  60. TweetsXer.username = document.location.href.split('/')[3]
  61. this.createUploadForm()
  62. TweetsXer.initXHR()
  63. },
  64.  
  65. sleep(ms) {
  66. return new Promise((resolve) => setTimeout(resolve, ms))
  67. },
  68. async waitForElemToExist(selector) {
  69. return new Promise((resolve) => {
  70. if (document.querySelector(selector)) {
  71. return resolve(document.querySelector(selector))
  72. }
  73.  
  74. var observer = new MutationObserver(() => {
  75. if (document.querySelector(selector)) {
  76. resolve(document.querySelector(selector))
  77. observer.disconnect()
  78. }
  79. })
  80.  
  81. observer.observe(document.body, {
  82. subtree: true,
  83. childList: true,
  84. })
  85. })
  86. },
  87.  
  88. initXHR() {
  89. if (typeof AjaxMonitoring_notfired == "undefined")
  90. var AjaxMonitoring_notfired = false
  91. if (!AjaxMonitoring_notfired) {
  92. AjaxMonitoring_notfired = true
  93.  
  94. /* NOTE: XMLHttpRequest actions happen in this sequence: at first "open"[readyState=1] happens, then "setRequestHeader", then "send", then "open"[readyState=2] */
  95.  
  96. var XHR_SendOriginal = XMLHttpRequest.prototype.send
  97. XMLHttpRequest.prototype.send = function () {
  98. XHR_SendOriginal.apply(this, arguments)
  99. }
  100.  
  101. var XHR_OpenOriginal = XMLHttpRequest.prototype.open
  102. XMLHttpRequest.prototype.open = function () {
  103. if (arguments[1] && arguments[1].includes("DeleteTweet")) {
  104. // POST /DeleteTweet
  105. TweetsXer.deleteURL = arguments[1]
  106. }
  107. XHR_OpenOriginal.apply(this, arguments)
  108. }
  109.  
  110. var XHR_SetRequestHeaderOriginal = XMLHttpRequest.prototype.setRequestHeader
  111. XMLHttpRequest.prototype.setRequestHeader = function (a, b) {
  112. TweetsXer.lastHeaders[a] = b
  113. XHR_SetRequestHeaderOriginal.apply(this, arguments)
  114. }
  115. }
  116. },
  117.  
  118. updateProgressBar() {
  119. document.getElementById('progressbar').setAttribute('value', this.dCount)
  120. document.getElementById("info").textContent = `${this.dCount} deleted`
  121. },
  122.  
  123. processFile() {
  124. let file = false
  125. let tn = document.getElementById(`${TweetsXer.dId}_file`)
  126. if (tn.files && tn.files[0]) {
  127. file = true
  128. let fr = new FileReader()
  129. fr.onloadend = function (evt) {
  130. TweetsXer.skip = document.getElementById('skipCount').value
  131. console.log(`Skipping oldest ${TweetsXer.skip} Tweets`)
  132.  
  133. // window.YTD.tweet_headers.part0
  134. // window.YTD.tweets.part0
  135. // window.YTD.like.part0
  136. let cutpoint = evt.target.result.indexOf('= ')
  137. let filestart = evt.target.result.slice(0, cutpoint)
  138. let json = JSON.parse(evt.target.result.slice(cutpoint + 1))
  139.  
  140. if (filestart.includes('.tweet_headers.')) {
  141. console.log('File contains Tweets.')
  142. TweetsXer.action = 'untweet'
  143. TweetsXer.tIds = json.map((x) => x.tweet.tweet_id)
  144. }
  145. else if (filestart.includes('.tweets.')) {
  146. console.log('File contains Tweets.')
  147. TweetsXer.action = 'untweet'
  148. TweetsXer.tIds = json.map((x) => x.tweet.id_str)
  149. }
  150. else if (filestart.includes('.like.')) {
  151. console.log('File contains Favs.')
  152. TweetsXer.action = 'unfav'
  153. TweetsXer.tIds = json.map((x) => x.like.tweetId)
  154. }
  155. else {
  156. console.log('File contain not recognized. Please use a file from the Twitter data export.')
  157. }
  158.  
  159. document
  160. .querySelector('[data-testid="AppTabBar_Profile_Link"]')
  161. .click()
  162.  
  163. TweetsXer.total = TweetsXer.tIds.length
  164. document.getElementById('start').remove()
  165. TweetsXer.createProgressBar()
  166.  
  167. if (TweetsXer.action == 'untweet') {
  168. TweetsXer.tIds.reverse()
  169. TweetsXer.tIds = TweetsXer.tIds.slice(TweetsXer.skip)
  170. TweetsXer.dCount = TweetsXer.skip
  171. TweetsXer.tIds.reverse()
  172. document.getElementById(
  173. `${TweetsXer.dId}_title`
  174. ).textContent = `Deleting ${TweetsXer.total} Tweets`
  175.  
  176. TweetsXer.deleteTweets()
  177. }
  178.  
  179. else if (TweetsXer.action == 'unfav') {
  180. TweetsXer.tIds.reverse()
  181. document.getElementById(
  182. `${TweetsXer.dId}_title`
  183. ).textContent = `Deleting ${TweetsXer.total} Favs`
  184. TweetsXer.deleteFavs()
  185. }
  186.  
  187. else {
  188. document.getElementById(
  189. `${TweetsXer.dId}_title`
  190. ).textContent = `Please try a different file`
  191. }
  192.  
  193.  
  194.  
  195. }
  196. fr.readAsText(tn.files[0])
  197. }
  198. },
  199.  
  200. createUploadForm() {
  201. var h2_class = document.querySelectorAll("h2")[1].getAttribute("class")
  202. var div = document.createElement("div")
  203. div.id = this.dId
  204. if (document.getElementById(this.dId))
  205. document.getElementById(this.dId).remove()
  206. div.innerHTML = `<style>#${this.dId}{ z-index:99999; position: sticky; top:0px; left:0px; width:auto; margin:0 auto; padding: 20px 10%; background:#87CEFA; opacity:0.9; } #${this.dId} > *{padding:5px;}</style>
  207. <div>
  208. <h2 class="${h2_class}" id="${this.dId}_title">TweetXer</h2>
  209. <p id="info">Select your tweet-headers.js from your Twitter Data Export to start the deletion of all your Tweets. </p>
  210. <p id="start">
  211. <input type="file" value="" id="${this.dId}_file" />
  212. <a href="#" id="toggleAdvanced">Advanced Options</a>
  213. <div id="advanced" style="display:none">
  214. <label for="skipCount">Enter how many Tweets to skip (useful for reruns) before selecting a file.</label>
  215. <input id="skipCount" type="number" value="0" />
  216. <p>To delete your Favs (aka Likes), select your like.js file.</p>
  217. <p>Instead of your tweet-headers.js file, you can use the tweets.js file. Unfaving is limited to 500 unfavs per 15 minutes.</p>
  218. </div>
  219. </p>
  220. </div>`
  221. document.body.insertBefore(div, document.body.firstChild)
  222. document.getElementById("toggleAdvanced").addEventListener("click", (() => { let adv = document.getElementById('advanced'); if (adv.style.display == 'none') { adv.style.display = 'block' } else { adv.style.display = 'none' } }));
  223. document.getElementById(`${this.dId}_file`).addEventListener("change", this.processFile, false)
  224. },
  225.  
  226. createProgressBar() {
  227. let progressbar = document.createElement("progress")
  228. progressbar.setAttribute('id', "progressbar")
  229. progressbar.setAttribute('value', this.dCount)
  230. progressbar.setAttribute('max', this.total)
  231. progressbar.setAttribute('style', 'width:100%')
  232. document.getElementById(this.dId).appendChild(progressbar)
  233. },
  234.  
  235. async deleteFavs() {
  236. // 500 unfavs per 15 Minutes
  237. // x-rate-limit-remaining
  238. // x-rate-limit-reset
  239. while (!('authorization' in this.lastHeaders)) {
  240. await this.sleep(1000)
  241. }
  242. TweetsXer.username = document.location.href.split('/')[3]
  243.  
  244. while (this.tIds.length > 0) {
  245. this.tId = this.tIds.pop()
  246. let response = await fetch(this.unfavURL, {
  247. "headers": {
  248. "accept": "*/*",
  249. "accept-language": 'en-US,en;q=0.5',
  250. "authorization": this.lastHeaders.authorization,
  251. "content-type": "application/json",
  252. "sec-fetch-dest": "empty",
  253. "sec-fetch-mode": "cors",
  254. "sec-fetch-site": "same-origin",
  255. "x-client-transaction-id": this.lastHeaders['X-Client-Transaction-Id'],
  256. "x-client-uuid": this.lastHeaders['x-client-uuid'],
  257. "x-csrf-token": this.lastHeaders['x-csrf-token'],
  258. "x-twitter-active-user": "yes",
  259. "x-twitter-auth-type": "OAuth2Session",
  260. "x-twitter-client-language": 'en'
  261. },
  262. "referrer": `https://twitter.com/${this.username}/likes`,
  263. "referrerPolicy": "strict-origin-when-cross-origin",
  264. "body": `{\"variables\":{\"tweet_id\":\"${this.tId}\"},\"queryId\":\"${this.unfavURL.split('/')[6]}\"}`,
  265. "method": "POST",
  266. "mode": "cors",
  267. "credentials": "include"
  268. })
  269.  
  270. if (response.status == 200) {
  271. TweetsXer.dCount++
  272. TweetsXer.updateProgressBar()
  273. }
  274. else {
  275. console.log(response)
  276. }
  277.  
  278. if (response.headers.get('x-rate-limit-remaining') < 1) {
  279. console.log('rate limit hit')
  280. let ratelimitreset = response.headers.get('x-rate-limit-reset')
  281. let sleeptime = ratelimitreset - Math.floor(Date.now() / 1000)
  282. while (sleeptime > 0) {
  283. sleeptime = ratelimitreset - Math.floor(Date.now() / 1000)
  284. document.getElementById("info").textContent = `Ratelimited. Waiting ${sleeptime} seconds. ${TweetsXer.dCount} deleted.`
  285. await this.sleep(1000)
  286. }
  287. }
  288. }
  289. },
  290.  
  291. async deleteTweets() {
  292. while (!('authorization' in this.lastHeaders)) {
  293. await this.sleep(1000)
  294. }
  295. TweetsXer.username = document.location.href.split('/')[3]
  296.  
  297. while (this.tIds.length > 0) {
  298. this.tId = this.tIds.pop()
  299. let response = await fetch(this.deleteURL, {
  300. "headers": {
  301. "accept": "*/*",
  302. "accept-language": 'en-US,en;q=0.5',
  303. "authorization": this.lastHeaders.authorization,
  304. "content-type": "application/json",
  305. "sec-fetch-dest": "empty",
  306. "sec-fetch-mode": "cors",
  307. "sec-fetch-site": "same-origin",
  308. "x-client-transaction-id": this.lastHeaders['X-Client-Transaction-Id'],
  309. "x-client-uuid": this.lastHeaders['x-client-uuid'],
  310. "x-csrf-token": this.lastHeaders['x-csrf-token'],
  311. "x-twitter-active-user": "yes",
  312. "x-twitter-auth-type": "OAuth2Session",
  313. "x-twitter-client-language": 'en'
  314. },
  315. "referrer": `https://twitter.com/${this.username}/with_replies`,
  316. "referrerPolicy": "strict-origin-when-cross-origin",
  317. "body": `{\"variables\":{\"tweet_id\":\"${this.tId}\",\"dark_request\":false},\"queryId\":\"${this.deleteURL.split('/')[6]}\"}`,
  318. "method": "POST",
  319. "mode": "cors",
  320. "credentials": "include"
  321. })
  322. if (response.status == 200) {
  323. TweetsXer.dCount++
  324. TweetsXer.updateProgressBar()
  325. }
  326. else {
  327. console.log(response)
  328. }
  329. }
  330. },
  331.  
  332. }
  333.  
  334. window.addEventListener('load', function () {
  335. // necessary when used as a userscript
  336. TweetsXer.init()
  337. }, false)
  338.  
  339. TweetsXer.init()